repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
roshkadev/Form
Example/Form/InstagramSignInViewController.swift
1
7125
// // InstagramSignInViewController.swift // Form // // Created by Paul Von Schrottky on 5/22/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import Form import Pastel import ActiveLabel class InstagramSignInViewController: UIViewController { let label = ActiveLabel() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() setNeedsStatusBarAppearanceUpdate() Form(in: self, constructor: { form in // Add the instagram pastel header. let instaView = InstagramView(frame: self.view.bounds) form.add(view: instaView) instaView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true instaView.heightAnchor.constraint(equalToConstant: 145).isActive = true Input(form: form).placeholder("Phone number, username or email").style { input in input.textField.font = UIFont.systemFont(ofSize: 11) }.bind(.formOnSubmit, .nonempty, .shake).top(36).horizontal(36).height(43).bottom(0).style { $0.contentView.backgroundColor = UIColor.foreground $0.contentView.layer.cornerRadius = 4 $0.contentView.layer.masksToBounds = true $0.contentView.layer.borderColor = UIColor.border.cgColor $0.contentView.layer.borderWidth = 1 / UIScreen.main.scale } Input(form: form).placeholder("Password").secure(true).style { input in input.textField.font = UIFont.systemFont(ofSize: 11) }.bind(.formOnSubmit, .nonempty, .shake).top(15).horizontal(36).height(43).bottom(20).style { $0.contentView.backgroundColor = UIColor.foreground $0.contentView.layer.cornerRadius = 4 $0.contentView.layer.masksToBounds = true $0.contentView.layer.borderColor = UIColor.border.cgColor $0.contentView.layer.borderWidth = 1 / UIScreen.main.scale } Button(form: form).title("Login").style { button in button.button.backgroundColor = .blue button.button.layer.cornerRadius = 4 button.button.layer.masksToBounds = true button.contentView.backgroundColor = .disabled button.button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) }.bind(.formOnChange) { loginButton in print(form.isValid) loginButton.contentView.backgroundColor = form.isValid ? .enabled : .disabled }.height(44).horizontal(36).bottom(20) let signinLabel = LinkLabel(title: "Forgot your login details? Get help signing in.", pattern: "\\Q Get help signing in.\\E", handler: { print("Sign in.") }) signinLabel.font = UIFont.boldSystemFont(ofSize: 10) form.add(view: signinLabel) Separator(form: form).title("OR").style { $0.label?.textColor = .gray $0.label?.font = UIFont.systemFont(ofSize: 11) }.horizontal(36).vertical(20) form.add(view: FacebookButton()) let signupLabel = LinkLabel(title: "Don't have an account? Sign up.", pattern: "\\Q Sign up.\\E", handler: { print("Sign up") }) signupLabel.font = UIFont.boldSystemFont(ofSize: 10) signupLabel.heightAnchor.constraint(equalToConstant: 80).isActive = true form.add(view: signupLabel) }).navigation(true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) self.view.endEditing(true) } } extension UIColor { static var foreground: UIColor { return UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1) } static var background: UIColor { return UIColor.white } static var border: UIColor { return UIColor(red: 202/255.0, green: 202/255.0, blue: 202/255.0, alpha: 1) } static var disabled: UIColor { return UIColor(red: 157/255.0, green: 204/255.0, blue: 245/255.0, alpha: 1) } static var enabled: UIColor { return UIColor(red: 62/255.0, green: 154/255.0, blue: 237/255.0, alpha: 1) } static var link: UIColor { return UIColor(red: 62/255.0, green: 154/255.0, blue: 237/255.0, alpha: 1) } } class FacebookButton: UIButton { init() { super.init(frame: .zero) setTitleColor(.blue, for: .normal) titleLabel?.font = UIFont.systemFont(ofSize: 14) setImage(UIImage(named: "the-f"), for: .normal) titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) setTitle("Log In With Facebook", for: .normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class LinkLabel: ActiveLabel { init(title: String, pattern: String, handler: @escaping ((Void) -> Void)) { super.init(frame: .zero) textAlignment = .center textColor = .gray font = UIFont.systemFont(ofSize: 9) text = title let customType = ActiveType.custom(pattern: pattern) enabledTypes = [ customType ] customColor[customType] = .link customSelectedColor[customType] = .link customize { label in self.handleCustomTap(for: customType, handler: { e in handler() }) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class InstagramView: PastelView { override init(frame: CGRect) { super.init(frame: .zero) startPastelPoint = .bottomLeft endPastelPoint = .topRight animationDuration = 3.0 setColors([ UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1.0), UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1.0), UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1.0), UIColor(red: 32/255, green: 76/255, blue: 255/255, alpha: 1.0), UIColor(red: 32/255, green: 158/255, blue: 255/255, alpha: 1.0), UIColor(red: 90/255, green: 120/255, blue: 127/255, alpha: 1.0), UIColor(red: 58/255, green: 255/255, blue: 217/255, alpha: 1.0), ]) let instaImageView = UIImageView(image: UIImage(named: "Instagram Text Logo")) instaImageView.translatesAutoresizingMaskIntoConstraints = false addSubview(instaImageView) instaImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true instaImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true startAnimation() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
52a5ea87aa9dc3451a5f72b7059168b8
39.477273
148
0.607243
4.286402
false
false
false
false
OperatorFoundation/Postcard
Postcard/Postcard/Controllers/KeyController.swift
1
13110
// // KeyController.swift // Postcard // // Created by Adelita Schule on 4/28/16. // Copyright © 2016 operatorfoundation.org. All rights reserved. // import Cocoa import KeychainAccess //import GoogleAPIClientForREST import Sodium //import MessagePack //Key Attachment Keys let userPublicKeyKey = "userPublicKey" let userPrivateKeyKey = "userPrivateKey" let userKeyTimestampKey = "userPublicKeyTimestamp" let keyService = "org.operatorfoundation.Postcard" private var _singletonSharedInstance: KeyController! = KeyController() class KeyController: NSObject { class var sharedInstance: KeyController { if _singletonSharedInstance == nil { _singletonSharedInstance = KeyController() } return _singletonSharedInstance } let keychain = Keychain(service: keyService).synchronizable(true) var mySharedKey: Data? var myPrivateKey: Data? var myKeyTimestamp: NSDate? fileprivate override init() { super.init() //If there is a userID available (i.e. email address) if let emailAddress: String = GlobalVars.currentUser?.emailAddress, !emailAddress.isEmpty { //Check the keychain for the user's keys do { guard let keyData = try keychain.getData(emailAddress) else { //If we do not already have a key pair make one. createAndSaveUserKeys(forUserWithEmail: emailAddress) print("Couldn't find user's Key data. A new key pair will be generated.") print("GET DATA FROM KEYCHAIN ERROR") return } if let userKeyPack = TimestampedUserKeys.init(keyData: keyData) { myPrivateKey = userKeyPack.userPrivateKey mySharedKey = userKeyPack.userPublicKey myKeyTimestamp = NSDate(timeIntervalSince1970: TimeInterval(userKeyPack.userKeyTimestamp)) } else { //If we do not already have a key pair make one. createAndSaveUserKeys(forUserWithEmail: emailAddress) print("Could not unpack user's Key data. A new key pair will be generated.") return } } catch let error { print("Error retreiving data from keychain: \(error.localizedDescription)") } } else { print("REALLY TERRIBLE ERROR: Couldn't find my user id so I don't know what my secret key is!!!!") } } func checkMessagesForCurrentKey() { } func createAndSaveUserKeys(forUserWithEmail email: String) { let newKeyPair = createNewKeyPair() save(privateKey: newKeyPair.secretKey, publicKey: newKeyPair.publicKey, forUserWithEmail: email) } func save(privateKey: Data, publicKey: Data, forUserWithEmail email: String) { //Set the timestamp to now let keyTimestamp = NSDate() let keyTimestampAsInt = Int64(keyTimestamp.timeIntervalSince1970) //Serialize the key information let userKeyPack = TimestampedUserKeys.init(userPublicKey: publicKey, userPrivateKey: privateKey, userKeyTimestamp: keyTimestampAsInt) if let userKeyData: Data = userKeyPack.dataValue() { //Save it to the Keychain do { try keychain .set(userKeyData, key: email) } catch let error { print("Error saving key data to keychain: \(error.localizedDescription)") } } //Save it to the class vars as well myPrivateKey = privateKey mySharedKey = publicKey myKeyTimestamp = keyTimestamp } func deleteInstance() { _singletonSharedInstance = nil } func sendKey(toPenPal penPal: PenPal) { //Send key email to this user let emailAddress = penPal.email let gmailMessage = GTLRGmail_Message() if let keyInvitationEmail = MailController.sharedInstance.generateKeyMessage(forPenPal: penPal) { let rawInvite = emailToRaw(email: keyInvitationEmail) gmailMessage.raw = rawInvite let sendMessageQuery = GTLRGmailQuery_UsersMessagesSend.query(withObject: gmailMessage, userId: "me", uploadParameters: nil) GmailProps.service.executeQuery(sendMessageQuery, completionHandler: { (ticket, maybeResponse, maybeError) in //Update sentKey to "true" penPal.sentKey = true //Save this PenPal to core data do { try penPal.managedObjectContext?.save() print("Sent a key to \(penPal.email).\n") } catch { let saveError = error as NSError print("\(saveError), \(saveError.userInfo)") self.showAlert(String(format: localizedPenPalStatusError, emailAddress)) } }) } } func alertReceivedNewerRecipientKey(from penPal: PenPal, withMessageId messageId: String) { let newKeyAlert = NSAlert() newKeyAlert.messageText = "\(penPal.email) used a newer version of your security settings. Do you want to import these settings to this device?" newKeyAlert.informativeText = "You received a message with newer encryption settings than what this installation of Postcard is using. This may be because you installed postcard on a different device. Do you want to import the newer settings from the other installation? Choose 'No' if you want to keep these settings (This message or invitation will be deleted as it cannot be read)." newKeyAlert.addButton(withTitle: "No") newKeyAlert.addButton(withTitle: "Yes") let response = newKeyAlert.runModal() if response == NSApplication.ModalResponse.alertSecondButtonReturn { //User wants to import settings from other machine ///Show instructions for importing settings here? } else if response == NSApplication.ModalResponse.alertFirstButtonReturn { //User selected No //Delete this message as we will be unable to read it MailController.sharedInstance.trashGmailMessage(withId: messageId) } } func alertReceivedOutdatedRecipientKey(from penPal: PenPal, withMessageId messageId: String) { let oldKeyAlert = NSAlert() oldKeyAlert.messageText = "\(penPal.email) used an older version of your security settings. Send new settings to this contact?" oldKeyAlert.informativeText = "A message or invitation was received that uses your old settings. You will not be able to read any new messages they send until they have your current settings, however this message or invitation will be deleted as it cannot be read." oldKeyAlert.addButton(withTitle: "No") oldKeyAlert.addButton(withTitle: "Yes") let response = oldKeyAlert.runModal() if response == NSApplication.ModalResponse.alertSecondButtonReturn { //User wants to send new key to contact KeyController.sharedInstance.sendKey(toPenPal: penPal) //Delete the message as we will be unable to read it MailController.sharedInstance.trashGmailMessage(withId: messageId) } else { //Do not send newer key ///Show instructions for importing settings here? MailController.sharedInstance.trashGmailMessage(withId: messageId) } } func alertReceivedNewerSenderKey(senderPublicKey: Data, senderKeyTimestamp: Int64, from penPal: PenPal, withMessageId messageId: String) { let newKeyAlert = NSAlert() newKeyAlert.messageText = "Accept PenPal's new encryption settings?" newKeyAlert.informativeText = "It looks like \(penPal.email) reset their encryption. Do you want to accept their new settings? If you do not, this message or invite will be deleted." newKeyAlert.addButton(withTitle: "No") newKeyAlert.addButton(withTitle: "Yes") let response = newKeyAlert.runModal() if response == NSApplication.ModalResponse.alertSecondButtonReturn { //User wants to update penpal key penPal.key = senderPublicKey as NSData? penPal.keyTimestamp = NSDate(timeIntervalSince1970: TimeInterval(senderKeyTimestamp)) //Save this PenPal to core data do { try penPal.managedObjectContext?.save() } catch { let saveError = error as NSError print("\(saveError.localizedDescription)") showAlert("Warning: We could not save this contact's new encryption settings.\n") } } else if response == NSApplication.ModalResponse.alertFirstButtonReturn { //User has chosen to ignore contact's new key, let's delete it so the user does not keep getting these alerts //trashGmailMessage(withId: messageId) } } ///TODO: Approve and localize strings for translation func alertReceivedOutdatedSenderKey(from penPal: PenPal, withMessageId messageId: String) { let oldKeyAlert = NSAlert() oldKeyAlert.messageText = "This email cannot be read. It was encrypted using older settings for: \(penPal.email)" oldKeyAlert.informativeText = "You should let this contact know that they sent you a message using a previous version of their encryption settings." oldKeyAlert.runModal() //trashGmailMessage(withId: messageId) } func compare(recipientKey: Data, andTimestamp timestamp: Int64, withStoredKey recipientStoredKey: Data, andTimestamp storedTimestamp: NSDate, forPenPal thisPenPal: PenPal, andMessageId messageId: String) -> Bool { guard recipientKey == recipientStoredKey else { let recipientStoredTimestamp = Int64(storedTimestamp.timeIntervalSince1970) if recipientStoredTimestamp > timestamp { //Key in the message is older than what the user is currently using alertReceivedOutdatedRecipientKey(from: thisPenPal, withMessageId: messageId) } else if recipientStoredTimestamp < timestamp { //Key in the message is newer than what we are currently using alertReceivedNewerRecipientKey(from: thisPenPal, withMessageId: messageId) print("recipientKey: \(recipientKey), andTimestamp \(timestamp), recipientStoredKey: \(recipientStoredKey), storedTimestamp: \(storedTimestamp), forPenPal \(thisPenPal), andMessageId \(messageId)") } return false } return true } func compare(senderKey: Data, andTimestamp timestamp: Int64, withStoredKey senderStoredKey: NSData, andTimestamp storedTimestamp: NSDate, forPenPal thisPenPal: PenPal, andMessageId messageId: String) -> Bool { //Check to see if the sender's key we received matches what we have stored if senderKey == senderStoredKey as Data { //print("We have the key for \(sender) and it matches the new one we received. Hooray \n") return true } else { let currentSenderKeyTimestamp = Int64(storedTimestamp.timeIntervalSince1970) if currentSenderKeyTimestamp > timestamp { //received key is older alertReceivedOutdatedSenderKey(from: thisPenPal, withMessageId: messageId) } else if currentSenderKeyTimestamp < timestamp { //received key is newer alertReceivedNewerSenderKey(senderPublicKey: senderKey, senderKeyTimestamp: timestamp, from: thisPenPal, withMessageId: messageId) } return false } } fileprivate func createNewKeyPair() -> Box.KeyPair { //Generate a key pair for the user. let mySodium = Sodium() let myKeyPair = mySodium.box.keyPair()! return myKeyPair } //MARK: Helper Methods func showAlert(_ message: String) { let alert = NSAlert() alert.messageText = message alert.addButton(withTitle: localizedOKButtonTitle) alert.runModal() } }
mit
f8f3a14241a9d1bcc0bed7185e47fb17
38.844985
393
0.614234
5.275252
false
false
false
false
qianqian2/ocStudy1
FAQText/FAQText/SectionModel.swift
1
1057
// // SectionModel.swift // FoldTableView // // Created by ShaoFeng on 16/7/29. // Copyright © 2016年 Cocav. All rights reserved. // import UIKit class SectionModel: NSObject { var sectionTitle: String? = nil var isExpanded: Bool? = false var cellModels: [CellModel] = [] var qcontent : String? var faq_no : Int? class func loadData(finish: ([SectionModel]) -> ()) { var array = [SectionModel]() for i in 0..<20 { let sectionModel = SectionModel() sectionModel.isExpanded = false sectionModel.sectionTitle = "第" + String(i + 1) + "组" var cellModels = [CellModel]() // for j in 0..<10 { let cellModel = CellModel() cellModel.cellTitle = "第" + String(i + 1) + "组,第" + String(j + 1) + "行" cellModels.append(cellModel) } //sectionModel.cellModels = cellModels //array.append(sectionModel) } finish(array) } }
apache-2.0
936d70196b183edbfda0e31be18a3f9b
25.717949
87
0.53263
4.184739
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/SieHack/DailyTemperatureViewController.swift
1
4741
// // FirstViewController.swift // Siemens Hackathon2 // // Created by Emre Yigit Alparslan on 10/22/16. // Copyright © 2016 Proxima. All rights reserved. // import UIKit import Charts class DailyTemperatureViewController: UIViewController { @IBOutlet weak var lineChart: LineChartView! @IBOutlet weak var humidityLineChart: LineChartView! @IBOutlet weak var activityIndi: UIActivityIndicatorView! var rasIP = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. lineChart.noDataText = "" humidityLineChart.noDataText = "" if let ri = UserDefaults.standard.value(forKey: "rasPi IP") as? String{ rasIP = ri } getDataFromDatabase() } func setLineChart(element: String, values: [Double]) { var dataEntries: [ChartDataEntry] = [] for i in 0..<values.count { let dataEntry = ChartDataEntry(x: Double(i), y: values[i]) dataEntries.append(dataEntry) } if element == "Humidity"{ let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Humidity") lineChartDataSet.circleRadius = 0.0 lineChartDataSet.setColor(NSUIColor.green) let lineChartData = LineChartData(dataSet: lineChartDataSet) lineChartData.setDrawValues(false) humidityLineChart.data = lineChartData humidityLineChart.setScaleEnabled(true) }else if element == "Temperature"{ let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Temperature") lineChartDataSet.circleRadius = 0.0 lineChartDataSet.setColor(NSUIColor.red) let lineChartData = LineChartData(dataSet: lineChartDataSet) lineChartData.setDrawValues(false) lineChart.data = lineChartData lineChart.setScaleEnabled(true) } } func getDataFromDatabase(){ lineChart.isUserInteractionEnabled = false humidityLineChart.isUserInteractionEnabled = false activityIndi.isHidden = false activityIndi.startAnimating() let url = URL(string: "http://\(rasIP)/daily")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if error == nil{ if let urlContent = data{ do{ let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject var datasetTemp = [Double]() var datasetHumi = [Double]() if let elements = (jsonResult["scores"])! as? NSArray{ var i = 0 while i < elements.count{ if let element = elements[i] as? AnyObject{ datasetTemp.append(element["temperature"] as! Double) datasetHumi.append(element["humidity"] as! Double) i+=1 } } } DispatchQueue.main.sync(execute: { self.setLineChart(element: "Temperature", values: datasetTemp) self.setLineChart(element: "Humidity", values: datasetHumi) self.lineChart.isUserInteractionEnabled = true self.humidityLineChart.isUserInteractionEnabled = true self.activityIndi.isHidden = true self.activityIndi.stopAnimating() }) }catch{ print("Json Process Failling") } } }else{ print(error) } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
2a532e14b2ff91009fe1441298e74c7a
36.03125
165
0.544304
5.880893
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAInstructionStep.swift
1
7658
// // SBAInstructionStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit @objc open class SBAInstructionStep: ORKInstructionStep, SBADirectNavigationRule, SBACustomTypeStep, SBALearnMoreActionStep { /** * For cases where this type of step is created as a placeholder for a custom step. */ open var customTypeIdentifier: String? /** * Pointer to the next step to show after this one. If nil, then the next step * is determined by the navigation rules setup by SBANavigableOrderedTask. */ open var nextStepIdentifier: String? /** * HTML Content for the "learn more" for this step */ @available(*, deprecated, message: "use learnMoreAction: instead") open var learnMoreHTMLContent: String? { guard let learnMore = self.learnMoreAction?.identifier else { return nil } return SBAResourceFinder.shared.html(forResource: learnMore) } /** * Indicates whether or not this step should use the completion step animation. */ open var isCompletionStep: Bool = false /** * The learn more action for this step */ open var learnMoreAction: SBALearnMoreAction? public override init(identifier: String) { super.init(identifier: identifier) } public init(inputItem: SBASurveyItem) { super.init(identifier: inputItem.identifier) self.title = inputItem.stepTitle?.trim() self.text = inputItem.stepText?.trim() self.footnote = inputItem.stepFootnote?.trim() if let directStep = inputItem as? SBADirectNavigationRule { self.nextStepIdentifier = directStep.nextStepIdentifier } if case SBASurveyItemType.custom(let customType) = inputItem.surveyItemType { self.customTypeIdentifier = customType } self.isCompletionStep = (inputItem.surveyItemType == .instruction(.completion)) if let surveyItem = inputItem as? SBAInstructionStepSurveyItem { self.learnMoreAction = surveyItem.learnMoreAction() self.detailText = surveyItem.stepDetail?.trim() self.image = surveyItem.stepImage self.iconImage = surveyItem.iconImage } } open override func stepViewControllerClass() -> AnyClass { // If this is a completion step, then use ORKCompletionStepViewController // unless this is class has an image, in which case ORKCompletionStepViewController // will not display that image so use the super class implementation. if self.isCompletionStep && self.image == nil { return ORKCompletionStepViewController.classForCoder() } else { return SBAInstructionStepViewController.classForCoder() } } override open func instantiateStepViewController(with result: ORKResult) -> ORKStepViewController { let vc = super.instantiateStepViewController(with: result) if let completionVC = vc as? ORKCompletionStepViewController { // By default, override showing the continue button in the nav bar completionVC.shouldShowContinueButton = true } return vc } // MARK: NSCopy override open func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) guard let step = copy as? SBAInstructionStep else { return copy } step.nextStepIdentifier = self.nextStepIdentifier step.learnMoreAction = self.learnMoreAction step.customTypeIdentifier = self.customTypeIdentifier step.isCompletionStep = self.isCompletionStep return step } // MARK: NSCoding required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.nextStepIdentifier = aDecoder.decodeObject(forKey: #keyPath(nextStepIdentifier)) as? String self.learnMoreAction = aDecoder.decodeObject(forKey: #keyPath(learnMoreAction)) as? SBALearnMoreAction self.customTypeIdentifier = aDecoder.decodeObject(forKey: #keyPath(customTypeIdentifier)) as? String self.isCompletionStep = aDecoder.decodeBool(forKey: #keyPath(isCompletionStep)) } override open func encode(with aCoder: NSCoder){ super.encode(with: aCoder) aCoder.encode(self.nextStepIdentifier, forKey: #keyPath(nextStepIdentifier)) aCoder.encode(self.learnMoreAction, forKey: #keyPath(learnMoreAction)) aCoder.encode(self.customTypeIdentifier, forKey: #keyPath(customTypeIdentifier)) aCoder.encode(self.isCompletionStep, forKey: #keyPath(isCompletionStep)) } // MARK: Equality override open func isEqual(_ object: Any?) -> Bool { guard let object = object as? SBAInstructionStep else { return false } return super.isEqual(object) && SBAObjectEquality(self.nextStepIdentifier, object.nextStepIdentifier) && SBAObjectEquality(self.learnMoreAction, object.learnMoreAction) && SBAObjectEquality(self.customTypeIdentifier, object.customTypeIdentifier) && (self.isCompletionStep == object.isCompletionStep) } override open var hash: Int { return super.hash ^ SBAObjectHash(self.nextStepIdentifier) ^ SBAObjectHash(learnMoreAction) ^ SBAObjectHash(self.customTypeIdentifier) ^ self.isCompletionStep.hashValue } } open class SBAInstructionStepViewController: ORKInstructionStepViewController { internal var sbaIntructionStep: SBAInstructionStep? { return self.step as? SBAInstructionStep } override open var learnMoreButtonTitle: String? { get { return sbaIntructionStep?.learnMoreAction?.learnMoreButtonText ?? super.learnMoreButtonTitle } set { super.learnMoreButtonTitle = newValue } } }
bsd-3-clause
a27c7f9dc69e1564c0b3bc413ff9c7f2
40.166667
119
0.693483
5.142377
false
false
false
false
gu704823/DYTV
dytv/dytv/uicollectionbaseview.swift
1
977
// // uicollectionbaseview.swift // dytv // // Created by jason on 2017/3/29. // Copyright © 2017年 jason. All rights reserved. // import UIKit class uicollectionbaseviewcell: UICollectionViewCell { @IBOutlet weak var iconimageview: UIImageView! @IBOutlet weak var nicknamelabel: UILabel! @IBOutlet weak var onlinebtn: UIButton! var anchor:anchormodel?{ didSet{ guard let anchor = anchor else{ return } //取出在线人数 var onlinepeople:String = "" if anchor.online>10000{ onlinepeople = "\(anchor.online/10000)万人在线" }else{ onlinepeople = "\(anchor.online)人在线" } onlinebtn.setTitle(onlinepeople, for: .normal) nicknamelabel.text = anchor.nickname let url = URL(string: anchor.vertical_src) iconimageview.kf.setImage(with: url) } } }
mit
3c4d99cd258ba4342d1b1a466dca52f5
26.882353
59
0.581224
4.213333
false
false
false
false
Eflet/Charts
Charts/Classes/Charts/BarChartView.swift
1
5802
// // BarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// Chart that draws bars. public class BarChartView: BarLineChartViewBase, BarChartDataProvider { /// flag that enables or disables the highlighting arrow private var _drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top private var _drawValueAboveBarEnabled = true /// if set to true, a grey area is drawn behind each bar that indicates the maximum value private var _drawBarShadowEnabled = false internal override func initialize() { super.initialize() renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler) _xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self) self.highlighter = BarChartHighlighter(chart: self) _xAxis._axisMinimum = -0.5 } internal override func calcMinMax() { super.calcMinMax() guard let data = _data else { return } let barData = data as! BarChartData // increase deltax by 1 because the bars have a width of 1 _xAxis.axisRange += 0.5 // extend xDelta to make space for multiple datasets (if ther are one) _xAxis.axisRange *= Double(data.dataSetCount) let groupSpace = barData.groupSpace _xAxis.axisRange += Double(barData.xValCount) * Double(groupSpace) _xAxis._axisMaximum = _xAxis.axisRange - _xAxis._axisMinimum } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart. public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data. public func getBarBounds(e: BarChartDataEntry) -> CGRect { guard let set = _data?.getDataSetForEntry(e) as? IBarChartDataSet else { return CGRectNull } let barspace = set.barSpace let y = CGFloat(e.value) let x = CGFloat(e.xIndex) let barWidth: CGFloat = 0.5 let spaceHalf = barspace / 2.0 let left = x - barWidth + spaceHalf let right = x + barWidth - spaceHalf let top = y >= 0.0 ? y : 0.0 let bottom = y <= 0.0 ? y : 0.0 var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top) getTransformer(set.axisDependency).rectValueToPixel(&bounds) return bounds } public override var lowestVisibleXIndex: Int { let step = CGFloat(_data?.dataSetCount ?? 0) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0) } public override var highestVisibleXIndex: Int { let step = CGFloat(_data?.dataSetCount ?? 0) let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div)) } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return _drawHighlightArrowEnabled; } set { _drawHighlightArrowEnabled = newValue setNeedsDisplay() } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return _drawValueAboveBarEnabled; } set { _drawValueAboveBarEnabled = newValue setNeedsDisplay() } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return _drawBarShadowEnabled; } set { _drawBarShadowEnabled = newValue setNeedsDisplay() } } // MARK: - BarChartDataProbider public var barData: BarChartData? { return _data as? BarChartData } /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled } }
apache-2.0
7cfd7840ebd48e4054be71ba06ae2a1e
33.748503
149
0.628749
4.997416
false
false
false
false
melling/ios_topics
CollectionViewDelegate/CollectionViewDelegate/BasicViewController.swift
1
2559
// // BasicViewController.swift // CollectionViewDelegate // // Created by Michael Mellinger on 5/26/16. // import UIKit class BasicCollectionViewController: UIViewController { private var collectionView:UICollectionView! fileprivate let reuseIdentifier = "Cell" // MARK: - View Management override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.gray let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumInteritemSpacing = 2 flowLayout.minimumLineSpacing = 2 flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 30, bottom: 0, right: 30) // flowLayout.scrollDirection = .horizontal // Default: .vertical collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.dataSource = self collectionView.delegate = self collectionView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(collectionView) NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 5), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor), collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 5), collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -5), ]) collectionView.backgroundColor = UIColor.gray // Register cell classes self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) } } // MARK: - UICollectionViewDataSource extension BasicCollectionViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 150 } } // MARK: - UICollectionViewDelegate extension BasicCollectionViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell let aColor = indexPath.row % 2 == 0 ? UIColor.orange : UIColor.green cell.backgroundColor = aColor return cell } }
cc0-1.0
4d4598ed5560b8eeaf83009d57870454
30.592593
121
0.694021
6.021176
false
false
false
false
AFathi/NotchToolkit
Example/Pods/NotchToolkit/NotchToolkit/NotchBar.swift
1
4150
// // NotchBar.swift // NotchToolbar // // Created by Ahmed Bekhit on 9/23/17. // Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved. // import UIKit public class NotchBar: UIView { /** This allows you to choose between statusBar & noStatusBar modes. */ public var mode:notchMode = .statusBar /** This allows you to set the height of the NotchBar. */ public var height:CGFloat = 250 /** This allows you to set the background color of the NotchBar. */ public var bgColor:UIColor = .black /** This allows you to set the corner radii of the NotchBar. */ public var curve:CGFloat = 35 /** This allows you to initially set the NotchBar visibility. */ public var isVisible:Bool = false /** This allows you to set the animation show/hide & rotation animation time interval of the NotchBar. */ public var animationInterval:TimeInterval = 0.3 override init(frame: CGRect) { super.init(frame: frame) create() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) create() } var scale:CGFloat! var multiplier:CGFloat! func create() { switch mode { case .statusBar: scale = UIScreen.main.portraitNotch.width multiplier = UIScreen.main.multiplier case .noStatusBar: scale = UIScreen.main.widePortraitNotch.width multiplier = UIScreen.main.multiplierWide } self.bounds = CGRect(x: 0, y: 0, width: scale, height: height) self.center = CGPoint(x: UIScreen.main.portraitNotch.origin.x, y: (self.bounds.height/2)) self.backgroundColor = bgColor self.addOvalOrCorner(type: .corner, position: .bottom, curve: curve) self.layer.masksToBounds = true self.alpha = isVisible ? 1 : 0 } /** This function is used to resize the NotchBar when device orientation is changed. */ public func refresh(orientation:deviceOrientation) { let subtrehend = isVisible ? 0 : self.bounds.height switch mode { case .statusBar: scale = UIScreen.main.portraitNotch.width multiplier = UIScreen.main.multiplier case .noStatusBar: scale = UIScreen.main.widePortraitNotch.width multiplier = UIScreen.main.multiplierWide } switch orientation { case .portrait: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.scale, height: self.height) self.center = CGPoint(x: UIScreen.main.portraitNotch.origin.x, y: (self.bounds.height/2) - subtrehend) self.backgroundColor = self.bgColor self.addOvalOrCorner(type: .corner, position: .bottom, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) case .landscapeLeft: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.height, height: self.scale) self.center = CGPoint(x: (self.bounds.height*(self.multiplier*self.height)) - subtrehend, y: UIScreen.main.landscapeLeftNotch.origin.y) self.backgroundColor = self.bgColor self.addOvalOrCorner(type: .corner, position: .right, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) case .landscapeRight: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.height, height: self.scale) self.center = CGPoint(x: (UIScreen.main.bounds.width-self.bounds.height*(self.multiplier*self.height)) + subtrehend, y: UIScreen.main.landscapeRightNotch.origin.y) self.backgroundColor = self.bgColor self.addOvalOrCorner(type: .corner, position: .left, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) } } }
mit
4eb10c95439ec8d672ea41b57280fdc9
37.416667
179
0.612678
4.299482
false
false
false
false
developerY/Swift2_Playgrounds
Start-Dev-iOS-Apps/FoodTracker - Persist Data/FoodTracker/Meal.swift
1
1975
// // Meal.swift // FoodTracker // // Created by Jane Appleseed on 5/26/15. // Copyright © 2015 Apple Inc. All rights reserved. // See LICENSE.txt for this sample’s licensing information. // import UIKit class Meal: NSObject, NSCoding { // MARK: Properties var name: String var photo: UIImage? var rating: Int // MARK: Archiving Paths static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals") // MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" static let ratingKey = "rating" } // MARK: Initialization init?(name: String, photo: UIImage?, rating: Int) { // Initialize stored properties. self.name = name self.photo = photo self.rating = rating super.init() // Initialization should fail if there is no name or if the rating is negative. if name.isEmpty || rating < 0 { return nil } } // MARK: NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: PropertyKey.nameKey) aCoder.encodeObject(photo, forKey: PropertyKey.photoKey) aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String // Because photo is an optional property of Meal, use conditional cast. let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey) // Must call designated initializer. self.init(name: name, photo: photo, rating: rating) } }
mit
0148d90477c239f96dc33370902a8a4f
28.014706
123
0.637424
4.8933
false
false
false
false
zisko/swift
stdlib/public/core/Slice.swift
1
19548
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A view into a subsequence of elements of another collection. /// /// A slice stores a base collection and the start and end indices of the view. /// It does not copy the elements from the collection into separate storage. /// Thus, creating a slice has O(1) complexity. /// /// Slices Share Indices /// -------------------- /// /// Indices of a slice can be used interchangeably with indices of the base /// collection. An element of a slice is located under the same index in the /// slice and in the base collection, as long as neither the collection nor /// the slice has been mutated since the slice was created. /// /// For example, suppose you have an array holding the number of absences from /// each class during a session. /// /// var absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You're tasked with finding the day with the most absences in the second /// half of the session. To find the index of the day in question, follow /// these setps: /// /// 1) Create a slice of the `absences` array that holds the second half of the /// days. /// 2) Use the `max(by:)` method to determine the index of the day with the /// most absences. /// 3) Print the result using the index found in step 2 on the original /// `absences` array. /// /// Here's an implementation of those steps: /// /// let secondHalf = absences.suffix(absences.count / 2) /// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) { /// print("Highest second-half absences: \(absences[i])") /// } /// // Prints "Highest second-half absences: 3" /// /// Slices Inherit Semantics /// ------------------------ /// /// A slice inherits the value or reference semantics of its base collection. /// That is, if a `Slice` instance is wrapped around a mutable collection that /// has value semantics, such as an array, mutating the original collection /// would trigger a copy of that collection, and not affect the base /// collection stored inside of the slice. /// /// For example, if you update the last element of the `absences` array from /// `0` to `2`, the `secondHalf` slice is unchanged. /// /// absences[7] = 2 /// print(absences) /// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]" /// print(secondHalf) /// // Prints "[0, 3, 1, 0]" /// /// Use slices only for transient computation. A slice may hold a reference to /// the entire storage of a larger collection, not just to the portion it /// presents, even after the base collection's lifetime ends. Long-term /// storage of a slice may therefore prolong the lifetime of elements that are /// no longer otherwise accessible, which can erroneously appear to be memory /// leakage. /// /// - Note: Using a `Slice` instance with a mutable collection requires that /// the base collection's `subscript(_: Index)` setter does not invalidate /// indices. If mutations need to invalidate indices in your custom /// collection type, don't use `Slice` as its subsequence type. Instead, /// define your own subsequence type that takes your index invalidation /// requirements into account. @_fixed_layout // FIXME(sil-serialize-all) public struct Slice<Base: Collection> { public var _startIndex: Base.Index public var _endIndex: Base.Index @_versioned // FIXME(sil-serialize-all) internal var _base: Base /// Creates a view into the given collection that allows access to elements /// within the specified range. /// /// It is unusual to need to call this method directly. Instead, create a /// slice of a collection by using the collection's range-based subscript or /// by using methods that return a subsequence. /// /// let singleDigits = 0...9 /// let subSequence = singleDigits.dropFirst(5) /// print(Array(subSequence)) /// // Prints "[5, 6, 7, 8, 9]" /// /// In this example, the expression `singleDigits.dropFirst(5))` is /// equivalent to calling this initializer with `singleDigits` and a /// range covering the last five items of `singleDigits.indices`. /// /// - Parameters: /// - base: The collection to create a view into. /// - bounds: The range of indices to allow access to in the new slice. @_inlineable // FIXME(sil-serialize-all) public init(base: Base, bounds: Range<Base.Index>) { self._base = base self._startIndex = bounds.lowerBound self._endIndex = bounds.upperBound } /// The underlying collection of the slice. /// /// You can use a slice's `base` property to access its base collection. The /// following example declares `singleDigits`, a range of single digit /// integers, and then drops the first element to create a slice of that /// range, `singleNonZeroDigits`. The `base` property of the slice is equal /// to `singleDigits`. /// /// let singleDigits = 0..<10 /// let singleNonZeroDigits = singleDigits.dropFirst() /// // singleNonZeroDigits is a Slice<Range<Int>> /// /// print(singleNonZeroDigits.count) /// // Prints "9" /// prints(singleNonZeroDigits.base.count) /// // Prints "10" /// print(singleDigits == singleNonZeroDigits.base) /// // Prints "true" @_inlineable // FIXME(sil-serialize-all) public var base: Base { return _base } } extension Slice: Collection { public typealias Index = Base.Index public typealias Indices = Base.Indices public typealias Element = Base.Element public typealias SubSequence = Slice<Base> public typealias Iterator = IndexingIterator<Slice<Base>> @_inlineable // FIXME(sil-serialize-all) public var startIndex: Index { return _startIndex } @_inlineable // FIXME(sil-serialize-all) public var endIndex: Index { return _endIndex } @_inlineable // FIXME(sil-serialize-all) public subscript(index: Index) -> Base.Element { get { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) return _base[index] } } @_inlineable // FIXME(sil-serialize-all) public subscript(bounds: Range<Index>) -> Slice<Base> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: _base, bounds: bounds) } } public var indices: Indices { return _base.indices[_startIndex..<_endIndex] } @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(after: i) } @_inlineable // FIXME(sil-serialize-all) public func formIndex(after i: inout Index) { // FIXME: swift-3-indexing-model: range check. _base.formIndex(after: &i) } @_inlineable // FIXME(sil-serialize-all) public func index(_ i: Index, offsetBy n: Int) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(i, offsetBy: n) } @_inlineable // FIXME(sil-serialize-all) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check. return _base.index(i, offsetBy: n, limitedBy: limit) } @_inlineable // FIXME(sil-serialize-all) public func distance(from start: Index, to end: Index) -> Int { // FIXME: swift-3-indexing-model: range check. return _base.distance(from: start, to: end) } @_inlineable // FIXME(sil-serialize-all) public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { _base._failEarlyRangeCheck(index, bounds: bounds) } @_inlineable // FIXME(sil-serialize-all) public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) { _base._failEarlyRangeCheck(range, bounds: bounds) } } extension Slice: BidirectionalCollection where Base: BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _base.index(before: i) } @_inlineable // FIXME(sil-serialize-all) public func formIndex(before i: inout Index) { // FIXME: swift-3-indexing-model: range check. _base.formIndex(before: &i) } } extension Slice: MutableCollection where Base: MutableCollection { @_inlineable // FIXME(sil-serialize-all) public subscript(index: Index) -> Base.Element { get { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) return _base[index] } set { _failEarlyRangeCheck(index, bounds: startIndex..<endIndex) _base[index] = newValue // MutableSlice requires that the underlying collection's subscript // setter does not invalidate indices, so our `startIndex` and `endIndex` // continue to be valid. } } @_inlineable // FIXME(sil-serialize-all) public subscript(bounds: Range<Index>) -> Slice<Base> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: _base, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } extension Slice: RandomAccessCollection where Base: RandomAccessCollection { } extension Slice: RangeReplaceableCollection where Base: RangeReplaceableCollection { @_inlineable // FIXME(sil-serialize-all) public init() { self._base = Base() self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @_inlineable // FIXME(sil-serialize-all) public init(repeating repeatedValue: Base.Element, count: Int) { self._base = Base(repeating: repeatedValue, count: count) self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @_inlineable // FIXME(sil-serialize-all) public init<S>(_ elements: S) where S: Sequence, S.Element == Base.Element { self._base = Base(elements) self._startIndex = _base.startIndex self._endIndex = _base.endIndex } @_inlineable // FIXME(sil-serialize-all) public mutating func replaceSubrange<C>( _ subRange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = _base.distance(from: _startIndex, to: subRange.lowerBound) + _base.distance(from: subRange.upperBound, to: _endIndex) + (numericCast(newElements.count) as Int) _base.replaceSubrange(subRange, with: newElements) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @_inlineable // FIXME(sil-serialize-all) public mutating func insert(_ newElement: Base.Element, at i: Index) { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count + 1 _base.insert(newElement, at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @_inlineable // FIXME(sil-serialize-all) public mutating func insert<S>(contentsOf newElements: S, at i: Index) where S: Collection, S.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count + newElements.count _base.insert(contentsOf: newElements, at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } @_inlineable // FIXME(sil-serialize-all) public mutating func remove(at i: Index) -> Base.Element { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count - 1 let result = _base.remove(at: i) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) return result } @_inlineable // FIXME(sil-serialize-all) public mutating func removeSubrange(_ bounds: Range<Index>) { // FIXME: swift-3-indexing-model: range check. let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex) let newSliceCount = count - distance(from: bounds.lowerBound, to: bounds.upperBound) _base.removeSubrange(bounds) _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset) _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } } extension Slice where Base: RangeReplaceableCollection, Base: BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public mutating func replaceSubrange<C>( _ subRange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. if subRange.lowerBound == _base.startIndex { let newSliceCount = _base.distance(from: _startIndex, to: subRange.lowerBound) + _base.distance(from: subRange.upperBound, to: _endIndex) + (numericCast(newElements.count) as Int) _base.replaceSubrange(subRange, with: newElements) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = subRange.lowerBound == _startIndex let lastValidIndex = _base.index(before: subRange.lowerBound) let newEndIndexOffset = _base.distance(from: subRange.upperBound, to: _endIndex) + (numericCast(newElements.count) as Int) + 1 _base.replaceSubrange(subRange, with: newElements) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @_inlineable // FIXME(sil-serialize-all) public mutating func insert(_ newElement: Base.Element, at i: Index) { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count + 1 _base.insert(newElement, at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) + 2 _base.insert(newElement, at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @_inlineable // FIXME(sil-serialize-all) public mutating func insert<S>(contentsOf newElements: S, at i: Index) where S : Collection, S.Element == Base.Element { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count + numericCast(newElements.count) _base.insert(contentsOf: newElements, at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) + numericCast(newElements.count) + 1 _base.insert(contentsOf: newElements, at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } @_inlineable // FIXME(sil-serialize-all) public mutating func remove(at i: Index) -> Base.Element { // FIXME: swift-3-indexing-model: range check. if i == _base.startIndex { let newSliceCount = count - 1 let result = _base.remove(at: i) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) return result } else { let shouldUpdateStartIndex = i == _startIndex let lastValidIndex = _base.index(before: i) let newEndIndexOffset = _base.distance(from: i, to: _endIndex) let result = _base.remove(at: i) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) return result } } @_inlineable // FIXME(sil-serialize-all) public mutating func removeSubrange(_ bounds: Range<Index>) { // FIXME: swift-3-indexing-model: range check. if bounds.lowerBound == _base.startIndex { let newSliceCount = count - _base.distance(from: bounds.lowerBound, to: bounds.upperBound) _base.removeSubrange(bounds) _startIndex = _base.startIndex _endIndex = _base.index(_startIndex, offsetBy: newSliceCount) } else { let shouldUpdateStartIndex = bounds.lowerBound == _startIndex let lastValidIndex = _base.index(before: bounds.lowerBound) let newEndIndexOffset = _base.distance(from: bounds.lowerBound, to: _endIndex) - _base.distance(from: bounds.lowerBound, to: bounds.upperBound) + 1 _base.removeSubrange(bounds) if shouldUpdateStartIndex { _startIndex = _base.index(after: lastValidIndex) } _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset) } } } @available(*, deprecated, renamed: "Slice") public typealias BidirectionalSlice<T> = Slice<T> where T : BidirectionalCollection @available(*, deprecated, renamed: "Slice") public typealias RandomAccessSlice<T> = Slice<T> where T : RandomAccessCollection @available(*, deprecated, renamed: "Slice") public typealias RangeReplaceableSlice<T> = Slice<T> where T : RangeReplaceableCollection @available(*, deprecated, renamed: "Slice") public typealias RangeReplaceableBidirectionalSlice<T> = Slice<T> where T : RangeReplaceableCollection & BidirectionalCollection @available(*, deprecated, renamed: "Slice") public typealias RangeReplaceableRandomAccessSlice<T> = Slice<T> where T : RangeReplaceableCollection & RandomAccessCollection @available(*, deprecated, renamed: "Slice") public typealias MutableSlice<T> = Slice<T> where T : MutableCollection @available(*, deprecated, renamed: "Slice") public typealias MutableBidirectionalSlice<T> = Slice<T> where T : MutableCollection & BidirectionalCollection @available(*, deprecated, renamed: "Slice") public typealias MutableRandomAccessSlice<T> = Slice<T> where T : MutableCollection & RandomAccessCollection @available(*, deprecated, renamed: "Slice") public typealias MutableRangeReplaceableSlice<T> = Slice<T> where T : MutableCollection & RangeReplaceableCollection @available(*, deprecated, renamed: "Slice") public typealias MutableRangeReplaceableBidirectionalSlice<T> = Slice<T> where T : MutableCollection & RangeReplaceableCollection & BidirectionalCollection @available(*, deprecated, renamed: "Slice") public typealias MutableRangeReplaceableRandomAccessSlice<T> = Slice<T> where T : MutableCollection & RangeReplaceableCollection & RandomAccessCollection
apache-2.0
3cf460cf2d4a702d97a1256ac20e3126
38.651116
155
0.68232
4.123181
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCWalletTransactionTableViewCell.swift
2
3437
// // NCWalletTransactionTableViewCell.swift // Neocom // // Created by Artem Shimanski on 20.06.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import CoreData class NCWalletTransactionTableViewCell: NCTableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var qtyLabel: UILabel! @IBOutlet weak var amountLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! } extension Prototype { enum NCWalletTransactionTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCWalletTransactionTableViewCell") } } protocol NCWalletTransaction { var clientID: Int {get} var date: Date {get} var isBuy: Bool {get} // public var isPersonal: Bool // public var journalRefID: Int64 var locationID: Int64 {get} var quantity: Int {get} // public var transactionID: Int64 var typeID: Int {get} var unitPrice: Double {get} var hashValue: Int {get} } extension ESI.Wallet.Transaction: NCWalletTransaction { } extension ESI.Wallet.CorpTransaction: NCWalletTransaction { } class NCWalletTransactionRow: TreeRow { let transaction: NCWalletTransaction let location: NCLocation? let clientID: NSManagedObjectID? lazy var client: NCContact? = { guard let clientID = clientID else {return nil} return (try? NCCache.sharedCache?.viewContext.existingObject(with: clientID)) as? NCContact }() lazy var type: NCDBInvType? = { return NCDatabase.sharedDatabase?.invTypes[self.transaction.typeID] }() init(transaction: NCWalletTransaction, location: NCLocation?, clientID: NSManagedObjectID?) { self.transaction = transaction self.location = location self.clientID = clientID super.init(prototype: Prototype.NCWalletTransactionTableViewCell.default, route: Router.Database.TypeInfo(transaction.typeID)) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCWalletTransactionTableViewCell else {return} cell.titleLabel.text = type?.typeName ?? NSLocalizedString("Unknown Type", comment: "") cell.subtitleLabel.attributedText = location?.displayName ?? NSLocalizedString("Unknown Location", comment: "") * [NSAttributedStringKey.foregroundColor: UIColor.lightText] cell.iconView.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.priceLabel.text = NCUnitFormatter.localizedString(from: transaction.unitPrice, unit: .isk, style: .full) cell.qtyLabel.text = NCUnitFormatter.localizedString(from: Double(transaction.quantity), unit: .none, style: .full) cell.dateLabel.text = DateFormatter.localizedString(from: transaction.date, dateStyle: .medium, timeStyle: .medium) var s = "\(transaction.isBuy ? "-" : "")\(NCUnitFormatter.localizedString(from: transaction.unitPrice * Double(transaction.quantity), unit: .isk, style: .full))" * [NSAttributedStringKey.foregroundColor: transaction.isBuy ? UIColor.red : UIColor.green] if let client = client?.name { s = s + " \(transaction.isBuy ? NSLocalizedString("to", comment: "") : NSLocalizedString("from", comment: "")) \(client)" } cell.amountLabel.attributedText = s } override var hash: Int { return transaction.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCWalletTransactionRow)?.hashValue == hashValue } }
lgpl-2.1
26692fb329c0ceaeb836a494d6567a90
34.42268
254
0.752619
4.014019
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Differentiator/Sources/Differentiator/IdentifiableValue.swift
17
797
// // IdentifiableValue.swift // RxDataSources // // Created by Krunoslav Zaher on 1/7/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import Foundation public struct IdentifiableValue<Value: Hashable> { public let value: Value } extension IdentifiableValue : IdentifiableType { public typealias Identity = Value public var identity : Identity { return value } } extension IdentifiableValue : Equatable , CustomStringConvertible , CustomDebugStringConvertible { public var description: String { return "\(value)" } public var debugDescription: String { return "\(value)" } } public func == <V>(lhs: IdentifiableValue<V>, rhs: IdentifiableValue<V>) -> Bool { return lhs.value == rhs.value }
mit
623df978c996d5ab8d39f3a0a3270578
18.414634
82
0.672111
4.47191
false
false
false
false
269961541/weibo
xinlangweibo/Class/Message/Controller/XGWMessageController.swift
1
3233
// // XGWMessageController.swift // xinlangweibo // // Created by Mac on 15/10/20. // Copyright © 2015年 Mac. All rights reserved. // import UIKit class XGWMessageController: XGWSuperTableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
7a4308dbd5cd207330578ce74ae10bcd
33
157
0.686997
5.502555
false
false
false
false
argon/mas
MasKit/Commands/Outdated.swift
1
1649
// // Outdated.swift // mas-cli // // Created by Andrew Naylor on 21/08/2015. // Copyright (c) 2015 Andrew Naylor. All rights reserved. // import Commandant import CommerceKit /// Command which displays a list of installed apps which have available updates /// ready to be installed from the Mac App Store. public struct OutdatedCommand: CommandProtocol { public typealias Options = NoOptions<MASError> public let verb = "outdated" public let function = "Lists pending updates from the Mac App Store" private let appLibrary: AppLibrary /// Public initializer. /// - Parameter appLibrary: AppLibrary manager. public init() { self.init(appLibrary: MasAppLibrary()) } /// Internal initializer. /// - Parameter appLibrary: AppLibrary manager. init(appLibrary: AppLibrary = MasAppLibrary()) { self.appLibrary = appLibrary } /// Runs the command. public func run(_: Options) -> Result<(), MASError> { let updateController = CKUpdateController.shared() let updates = updateController?.availableUpdates() for update in updates! { if let installed = appLibrary.installedApp(forBundleId: update.bundleID) { // Display version of installed app compared to available update. print(""" \(update.itemIdentifier) \(update.title) (\(installed.bundleVersion) -> \(update.bundleVersion)) """) } else { print("\(update.itemIdentifier) \(update.title) (unknown -> \(update.bundleVersion))") } } return .success(()) } }
mit
13f1bf29506960e5b248906310e095ac
32.653061
116
0.633111
4.567867
false
false
false
false
mozilla-mobile/firefox-ios
Client/Experiments/Settings/ExperimentsViewController.swift
2
3114
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import MozillaAppServices class ExperimentsViewController: UIViewController { private let experimentsView = ExperimentsTableView() private let experiments: NimbusApi private var availableExperiments: [AvailableExperiment] init(experiments: NimbusApi = Experiments.shared) { self.experiments = experiments self.availableExperiments = experiments.getAvailableExperiments() super.init(nibName: nil, bundle: nil) navigationItem.title = "Experiments" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit) { item in self.showSettings() } NotificationCenter.default.addObserver(forName: .nimbusExperimentsApplied, object: nil, queue: .main) { _ in self.onExperimentsApplied() } } required init?(coder: NSCoder) { fatalError() } override func loadView() { view = experimentsView } override func viewDidLoad() { super.viewDidLoad() experimentsView.delegate = self experimentsView.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) guard let row = experimentsView.indexPathForSelectedRow else { return } experimentsView.deselectRow(at: row, animated: true) } private func showSettings() { let vc = ExperimentsSettingsViewController() navigationController?.pushViewController(vc, animated: true) } @objc private func onExperimentsApplied() { DispatchQueue.main.async { self.availableExperiments = self.experiments.getAvailableExperiments() self.experimentsView.reloadData() } } } extension ExperimentsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availableExperiments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ExperimentsTableView.CellIdentifier, for: indexPath) let experiment = availableExperiments[indexPath.row] let branch = experiments.getExperimentBranch(experimentId: experiment.slug) ?? "Not enrolled" cell.textLabel?.text = experiment.userFacingName cell.detailTextLabel?.numberOfLines = 3 cell.detailTextLabel?.text = experiment.userFacingDescription + "\nEnrolled in: \(branch)" return cell } } extension ExperimentsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let experiment = availableExperiments[indexPath.row] let vc = ExperimentsBranchesViewController(experiment: experiment) navigationController?.pushViewController(vc, animated: true) } }
mpl-2.0
d77143c1d7f56e85146ce3c2177ffd89
35.635294
117
0.70745
5.295918
false
false
false
false
JeffESchmitz/RideNiceRide
Pods/Cent/Sources/Regex.swift
4
5014
// // Regex.swift // Cent // // Created by Ankur Patel on 10/21/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation #if os(Linux) public typealias NSRegularExpression = RegularExpression public typealias NSTextCheckingResult = TextCheckingResult #endif public class Regex { let expression: NSRegularExpression let pattern: String static let RegexEscapePattern = "[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]" static let RegexPatternRegex = Regex(RegexEscapePattern) public init(_ pattern: String) { self.pattern = pattern self.expression = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) } public func matches(testStr: String) -> [NSTextCheckingResult] { let matches = self.expression.matches(in: testStr, options: [], range:NSMakeRange(0, testStr.characters.count)) return matches } public func rangeOfFirstMatch(testStr: String) -> NSRange { return self.expression.rangeOfFirstMatch(in: testStr, options: [], range:NSMakeRange(0, testStr.characters.count)) } public func test(testStr: String) -> Bool { let matches = self.matches(testStr: testStr) return matches.count > 0 } public class func escapeStr(str: String) -> String { let matches = RegexPatternRegex.matches(testStr: str) var charArr = [Character](str.characters) var strBuilder = [Character]() var i = 0 for match in matches { let range = match.range while i < (range.location) + (range.length) { if i == range.location { _ = strBuilder << "\\" } _ = strBuilder << charArr[i] i += 1 } } while i < charArr.count { _ = strBuilder << charArr[i] i += 1 } return String(strBuilder) } } /// Useful regex patterns (mapped from lodash) struct RegexHelper { /// Unicode character classes static let astralRange = "\\ud800-\\udfff" static let comboRange = "\\u0300-\\u036f\\ufe20-\\ufe23" static let dingbatRange = "\\u2700-\\u27bf" static let lowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff" static let mathOpRange = "\\xac\\xb1\\xd7\\xf7" static let nonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf" static let quoteRange = "\\u2018\\u2019\\u201c\\u201d" static let spaceRange = "\\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000" static let upperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde" static let varRange = "\\ufe0e\\ufe0f" static let breakRange = mathOpRange + nonCharRange + quoteRange + spaceRange /// Unicode capture groups static let astral = "[" + astralRange + "]" static let breakGroup = "[" + breakRange + "]" static let combo = "[" + comboRange + "]" static let digits = "\\d+" static let dingbat = "[" + dingbatRange + "]" static let lower = "[" + lowerRange + "]" static let misc = "[^" + astralRange + breakRange + digits + dingbatRange + lowerRange + upperRange + "]" static let modifier = "(?:\\ud83c[\\udffb-\\udfff])" static let nonAstral = "[^" + astralRange + "]" static let regional = "(?:\\ud83c[\\udde6-\\uddff]){2}" static let surrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]" static let upper = "[" + upperRange + "]" static let ZWJ = "\\u200d" /// Unicode regex composers static let lowerMisc = "(?:" + lower + "|" + misc + ")" static let upperMisc = "(?:" + upper + "|" + misc + ")" static let optMod = modifier + "?" static let optVar = "[" + varRange + "]" static let optJoin = "(?:" + ZWJ + "(?:" + [nonAstral, regional, surrPair].joined(separator: "|") + ")" + optVar + optMod + ")*" static let seq = optVar + optMod + optJoin static let emoji = "(?:" + [dingbat, regional, surrPair].joined(separator: "|") + ")" + seq static let symbol = "(?:" + [nonAstral + combo + "?", combo, regional, surrPair, astral].joined(separator: "|") + ")" /// Match non-compound words composed of alphanumeric characters static let basicWord = "[a-zA-Z0-9]+" private static let word1 = upper + "?" + lower + "+(?=" + [breakGroup, upper, "$"].joined(separator: "|") + ")" private static let word2 = upperMisc + "+(?=" + [breakGroup, upper + lowerMisc, "$"].joined(separator: "|") + ")" private static let word3 = upper + "?" + lowerMisc + "+" private static let word4 = digits + "(?:" + lowerMisc + "+)?" private static let word5 = emoji /// Match complex or compound words static let complexWord = [ word1, word2, word3, word4, word5 ].joined(separator: "|") /// Detect strings that need a more robust regexp to match words static let hasComplexWord = "[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]" }
mit
6904869f679e10e39e36418957d836f2
38.793651
185
0.593738
3.665205
false
true
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/DataStructure/Raywenderlich/BitSet.swift
1
6586
// // BitSet.swift // DataStructure // // Created by 朱双泉 on 2018/5/25. // Copyright © 2018 Castie!. All rights reserved. // import Foundation extension BitSet { static func example() { var bits = BitSet(size: 140) bits[2] = true bits[99] = true bits[128] = true print(bits) } } public struct BitSet { private(set) public var size: Int private let N = 64 public typealias Word = UInt64 fileprivate(set) public var words: [Word] private let allOnes = ~Word() public init(size: Int) { precondition(size > 0) self.size = size let n = (size + (N-1)) / N words = [Word](repeating: 0, count: n) } /* Converts a bit index into an array index and a mask inside the word. */ private func indexOf(_ i: Int) -> (Int, Word) { precondition(i >= 0) precondition(i < size) let o = i / N let m = Word(i - o*N) return (o, 1 << m) } /* Returns a mask that has 1s for all bits that are in the last word. */ private func lastWordMask() -> Word { let diff = words.count*N - size if diff > 0 { // Set the highest bit that's still valid. let mask = 1 << Word(63 - diff) // Subtract 1 to turn it into a mask, and add the high bit back in. return (Word)(mask | (mask - 1)) } else { return allOnes } } /* If the size is not a multiple of N, then we have to clear out the bits that we're not using, or bitwise operations between two differently sized BitSets will go wrong. */ fileprivate mutating func clearUnusedBits() { words[words.count - 1] &= lastWordMask() } /* So you can write bitset[99] = ... */ public subscript(i: Int) -> Bool { get { return isSet(i) } set { if newValue { set(i) } else { clear(i) } } } /* Sets the bit at the specified index to 1. */ public mutating func set(_ i: Int) { let (j, m) = indexOf(i) words[j] |= m } /* Sets all the bits to 1. */ public mutating func setAll() { for i in 0..<words.count { words[i] = allOnes } clearUnusedBits() } /* Sets the bit at the specified index to 0. */ public mutating func clear(_ i: Int) { let (j, m) = indexOf(i) words[j] &= ~m } /* Sets all the bits to 0. */ public mutating func clearAll() { for i in 0..<words.count { words[i] = 0 } } /* Changes 0 into 1 and 1 into 0. Returns the new value of the bit. */ public mutating func flip(_ i: Int) -> Bool { let (j, m) = indexOf(i) words[j] ^= m return (words[j] & m) != 0 } /* Determines whether the bit at the specific index is 1 (true) or 0 (false). */ public func isSet(_ i: Int) -> Bool { let (j, m) = indexOf(i) return (words[j] & m) != 0 } /* Returns the number of bits that are 1. Time complexity is O(s) where s is the number of 1-bits. */ public var cardinality: Int { var count = 0 for var x in words { while x != 0 { let y = x & ~(x - 1) // find lowest 1-bit x = x ^ y // and erase it count += 1 } } return count } /* Checks if all the bits are set. */ public func all1() -> Bool { for i in 0..<words.count - 1 { if words[i] != allOnes { return false } } return words[words.count - 1] == lastWordMask() } /* Checks if any of the bits are set. */ public func any1() -> Bool { for x in words { if x != 0 { return true } } return false } /* Checks if none of the bits are set. */ public func all0() -> Bool { for x in words { if x != 0 { return false } } return true } } // MARK: - Equality extension BitSet: Equatable { } public func == (lhs: BitSet, rhs: BitSet) -> Bool { return lhs.words == rhs.words } // MARK: - Hashing extension BitSet: Hashable { /* Based on the hashing code from Java's BitSet. */ public var hashValue: Int { var h = Word(1234) for i in stride(from: words.count, to: 0, by: -1) { h ^= words[i - 1] &* Word(i) } return Int((h >> 32) ^ h) } } // MARK: - Bitwise operations extension BitSet { public static var allZeros: BitSet { return BitSet(size: 64) } } private func copyLargest(_ lhs: BitSet, _ rhs: BitSet) -> BitSet { return (lhs.words.count > rhs.words.count) ? lhs : rhs } /* Note: In all of these bitwise operations, lhs and rhs are allowed to have a different number of bits. The new BitSet always has the larger size. The extra bits that get added to the smaller BitSet are considered to be 0. That will strip off the higher bits from the larger BitSet when doing &. */ public func & (lhs: BitSet, rhs: BitSet) -> BitSet { let m = max(lhs.size, rhs.size) var out = BitSet(size: m) let n = min(lhs.words.count, rhs.words.count) for i in 0..<n { out.words[i] = lhs.words[i] & rhs.words[i] } return out } public func | (lhs: BitSet, rhs: BitSet) -> BitSet { var out = copyLargest(lhs, rhs) let n = min(lhs.words.count, rhs.words.count) for i in 0..<n { out.words[i] = lhs.words[i] | rhs.words[i] } return out } public func ^ (lhs: BitSet, rhs: BitSet) -> BitSet { var out = copyLargest(lhs, rhs) let n = min(lhs.words.count, rhs.words.count) for i in 0..<n { out.words[i] = lhs.words[i] ^ rhs.words[i] } return out } prefix public func ~ (rhs: BitSet) -> BitSet { var out = BitSet(size: rhs.size) for i in 0..<rhs.words.count { out.words[i] = ~rhs.words[i] } out.clearUnusedBits() return out } // MARK: - Debugging extension UInt64 { /* Writes the bits in little-endian order, LSB first. */ public func bitsToString() -> String { var s = "" var n = self for _ in 1...64 { s += ((n & 1 == 1) ? "1" : "0") n >>= 1 } return s } } extension BitSet: CustomStringConvertible { public var description: String { var s = "" for x in words { s += x.bitsToString() + " " } return s } }
mit
d01c5fcc795666e6fc37f94e724cd514
24.901575
84
0.527284
3.665181
false
false
false
false
proxpero/Endgame
Sources/Square.swift
1
5945
// // Square.swift // Endgame // // Created by Todd Olsen on 8/4/16. // // /// A pair of a chess board `File` and `Rank`. public typealias Location = (file: File, rank: Rank) /// A square on the chess board. public enum Square: Int { /// A1 square. case a1 /// B1 square. case b1 /// C1 square. case c1 /// D1 square. case d1 /// E1 square. case e1 /// F1 square. case f1 /// G1 square. case g1 /// H1 square. case h1 /// A2 square. case a2 /// B2 square. case b2 /// C2 square. case c2 /// D2 square. case d2 /// E2 square. case e2 /// F2 square. case f2 /// G2 square. case g2 /// H2 square. case h2 /// A3 square. case a3 /// B3 square. case b3 /// C3 square. case c3 /// D3 square. case d3 /// E3 square. case e3 /// F3 square. case f3 /// G3 square. case g3 /// H3 square. case h3 /// A4 square. case a4 /// B4 square. case b4 /// C4 square. case c4 /// D4 square. case d4 /// E4 square. case e4 /// F4 square. case f4 /// G4 square. case g4 /// H4 square. case h4 /// A5 square. case a5 /// B5 square. case b5 /// C5 square. case c5 /// D5 square. case d5 /// E5 square. case e5 /// F5 square. case f5 /// G5 square. case g5 /// H5 square. case h5 /// A6 square. case a6 /// B6 square. case b6 /// C6 square. case c6 /// D6 square. case d6 /// E6 square. case e6 /// F6 square. case f6 /// G6 square. case g6 /// H6 square. case h6 /// A7 square. case a7 /// B7 square. case b7 /// C7 square. case c7 /// D7 square. case d7 /// E7 square. case e7 /// F7 square. case f7 /// G7 square. case g7 /// H7 square. case h7 /// A8 square. case a8 /// B8 square. case b8 /// C8 square. case c8 /// D8 square. case d8 /// E8 square. case e8 /// F8 square. case f8 /// G8 square. case g8 /// H8 square. case h8 /// Create a square from `file` and `rank`. public init(file: File, rank: Rank) { self.init(rawValue: file.index + (rank.index << 3))! } /// Create a square from `location`. public init(location: Location) { self.init(file: location.file, rank: location.rank) } /// Create a square from `file` and `rank`. Returns `nil` if either is `nil`. public init?(file: File?, rank: Rank?) { guard let file = file, let rank = rank else { return nil } self.init(file: file, rank: rank) } /// Create a square from `string` that is equivalent to the square's description. public init?(_ string: String) { let chars = string.characters guard chars.count == 2 else { return nil } guard let file = File(chars.first!) else { return nil } guard let rank = Int(String(chars.last!)).flatMap({ Rank($0) }) else { return nil } self.init(file: file, rank: rank) } } extension Square: ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public init(stringLiteral value: String) { guard let square = Square(value) else { fatalError("Invalid string for square: \"\(value)\"") } self = square } } extension Square: ExpressibleByUnicodeScalarLiteral { /// Create an instance initialized to `value`. public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } } extension Square: ExpressibleByExtendedGraphemeClusterLiteral { /// Create an instance initialized to `value`. public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } } extension Square: CustomStringConvertible { /// A textual representation of `self`. public var description: String { return "\(file)\(rank)" } } extension Square { /// The file of `self`. public var file: File { get { return File(index: rawValue & 7)! } set(newFile) { self = Square(file: newFile, rank: rank) } } /// The rank of `self`. public var rank: Rank { get { return Rank(index: rawValue >> 3)! } set(newRank) { self = Square(file: file, rank: newRank) } } /// The location of `self`. public var location: Location { get { return (file, rank) } set(newLocation) { self = Square(location: newLocation) } } /// The square's color. public var color: Color { return (file.index & 1 != rank.index & 1) ? .white : .black } } extension Square { /// An array of all squares. static let all: [Square] = (0 ..< 64).flatMap(Square.init(rawValue:)) } extension Sequence where Iterator.Element == Square { /// A bitboard representing the sequence of squares. var bitboard: Bitboard { return self.reduce(0) { $0 | $1.bitboard } } /// Creates an array of moves each having `origin` as the origin square /// and the squares in `self` are mapped to the move's target square. public func moves(from origin: Square) -> [Move] { return self.map { Move(origin: origin, target: $0) } } /// Creates an array of moves, each having `target` as the move's target square /// and the squares in `self` are mapped to the move's origin square. public func moves(to target: Square) -> [Move] { return self.map { Move(origin: $0, target: target) } } }
mit
8ee03f179ac0940723ba5924b68a447f
16.182081
85
0.533894
3.736644
false
false
false
false
farhanpatel/firefox-ios
StorageTests/TestBrowserDB.swift
2
4840
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Storage import XCGLogger import XCTest private let log = XCGLogger.default class TestBrowserDB: XCTestCase { let files = MockFiles() fileprivate func rm(_ path: String) { do { try files.remove(path) } catch { } } override func setUp() { super.setUp() rm("foo.db") rm("foo.db-shm") rm("foo.db-wal") rm("foo.db.bak.1") rm("foo.db.bak.1-shm") rm("foo.db.bak.1-wal") } class MockFailingSchema: Schema { var name: String { return "FAILURE" } var version: Int { return BrowserSchema.DefaultVersion + 1 } func drop(_ db: SQLiteDBConnection) -> Bool { return true } func create(_ db: SQLiteDBConnection) -> Bool { return false } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { return false } } fileprivate class MockListener { var notification: Notification? @objc func onDatabaseWasRecreated(_ notification: Notification) { self.notification = notification } } func testUpgradeV33toV34RemovesLongURLs() { let db = BrowserDB(filename: "v33.db", schema: BrowserSchema(), files: SupportingFiles()) let results = db.runQuery("SELECT bmkUri, title FROM bookmarksLocal WHERE type = 1", args: nil, factory: { row in (row[0] as! String, row[1] as! String) }).value.successValue! // The bookmark with the long URL has been deleted. XCTAssertTrue(results.count == 1) let remaining = results[0]! // This one's title has been truncated to 4096 chars. XCTAssertEqual(remaining.1.characters.count, 4096) XCTAssertEqual(remaining.1.utf8.count, 4096) XCTAssertTrue(remaining.1.hasPrefix("abcdefghijkl")) XCTAssertEqual(remaining.0, "http://example.com/short") } func testMovesDB() { var db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // Grab a pointer to the -shm so we can compare later. let shmAAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationA = shmAAttributes[FileAttributeKey.creationDate] as! Date let inodeA = (shmAAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertFalse(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) let center = NotificationCenter.default let listener = MockListener() center.addObserver(listener, selector: #selector(MockListener.onDatabaseWasRecreated(_:)), name: NotificationDatabaseWasRecreated, object: nil) defer { center.removeObserver(listener) } // It'll still fail, but it moved our old DB. // Our current observation is that closing the DB deletes the .shm file and also // checkpoints the WAL. db.forceClose() db = BrowserDB(filename: "foo.db", schema: MockFailingSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").failed() // This won't actually write since we'll get a failed connection db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // But now it's been reopened, it's not the same -shm! let shmBAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationB = shmBAttributes[FileAttributeKey.creationDate] as! Date let inodeB = (shmBAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertTrue(creationA.compare(creationB) != ComparisonResult.orderedDescending) XCTAssertNotEqual(inodeA, inodeB) XCTAssertTrue(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) // The right notification was issued. XCTAssertEqual("foo.db", (listener.notification?.object as? String)) } }
mpl-2.0
204cad1df80b0214d0280c0888c04532
38.032258
151
0.645248
4.253076
false
false
false
false
insidegui/WWDC
WWDC/CommunityNewsItemViewModel.swift
1
3431
// // CommunityNewsItemViewModel.swift // WWDC // // Created by Guilherme Rambo on 01/06/20. // Copyright © 2020 Guilherme Rambo. All rights reserved. // import Cocoa import ConfCore import RealmSwift struct CommunityTagViewModel: Hashable { let name: String let title: String let order: Int let color: NSColor } struct CommunitySection: Hashable { let tag: CommunityTagViewModel let title: String let color: NSColor let items: [CommunityNewsItemViewModel] } struct CommunityNewsItemViewModel: Hashable { let id: String let title: String let attributedSummary: NSAttributedString? let tag: CommunityTagViewModel let url: URL let date: Date let formattedDate: String let isFeatured: Bool let image: URL? } extension CommunityTagViewModel { init(tag: CommunityTag) { self.init( name: tag.name, title: tag.title, order: tag.order, color: NSColor.fromHexString(hexString: tag.color) ) } } extension CommunitySection { static func sections(from results: Results<CommunityNewsItem>) -> [CommunitySection] { var groups: [CommunityTagViewModel: [CommunityNewsItemViewModel]] = [:] results.forEach { item in guard let rawTag = item.tags.first else { return } let tag = CommunityTagViewModel(tag: rawTag) guard let viewModel = CommunityNewsItemViewModel(item: item) else { assertionFailure("Expected view model creation to succeed") return } if groups[tag] != nil { groups[tag]?.append(viewModel) } else { groups[tag] = [viewModel] } } return groups.keys.sorted(by: { $0.order < $1.order }).map { tag in CommunitySection( tag: tag, title: tag.title, color: tag.color, items: groups[tag] ?? [] ) } } } extension CommunityNewsItemViewModel { private static let dateFormatter: DateFormatter = { let f = DateFormatter() f.dateStyle = .short f.timeStyle = .none f.doesRelativeDateFormatting = true return f }() private static func attributedSummary(from summary: String?) -> NSAttributedString? { guard let summary = summary else { return nil } return NSAttributedString.create( with: summary, font: .systemFont(ofSize: 14), color: .secondaryText, lineHeightMultiple: 1.28 ) } init?(item: CommunityNewsItem) { guard let url = URL(string: item.url) else { assertionFailure("Expected string to be a valid URL: \(item.url)") return nil } guard let rawTag = item.tags.first else { assertionFailure("News item must have at least one tag") return nil } self.init( id: item.id, title: item.title, attributedSummary: Self.attributedSummary(from: item.summary), tag: CommunityTagViewModel(tag: rawTag), url: url, date: item.date, formattedDate: Self.dateFormatter.string(from: item.date), isFeatured: item.isFeatured, image: item.image.flatMap(URL.init) ) } }
bsd-2-clause
e83a403afb54083b3ec285bad098b6be
24.597015
90
0.587755
4.641407
false
false
false
false
ccabanero/MidpointSlider
Pod/Classes/MidpointSlider.swift
1
7691
// // MidpointSlider.swift // Pods // // Created by Clint Cabanero on 1/28/16. // // import UIKit import QuartzCore @IBDesignable public class MidpointSlider: UIControl { // // MARK: - Configurable Slider Properties // // Slider min value @IBInspectable public var minimumValue: Double = -10.0 { didSet { initialize() } } // Slider max value @IBInspectable public var maximumValue: Double = 10.0 { didSet { initialize() } } // Slider current value @IBInspectable public var currentValue: Double = 7.0 { didSet { initialize() } } // the color shown between the midpoint and the slider @IBInspectable public var trackTintColor: UIColor = UIColor(red: 0/255.0, green: 122/255.0, blue: 255/255.0, alpha: 1.0) { didSet { initialize() } } // the color of the track (background) var trackBackgroundColor = UIColor(red: 220/255.0, green: 220/255.0, blue: 220/255.0, alpha: 1.0) // // MARK: - Properties not intended for updating by user // // the inside color of the thumb circle let thumbTintColor = UIColor.whiteColor() // the width of the outline for the thumb circle let thumbOutlineWidth = CGFloat(1.5) let curvaceousness : CGFloat = 1.0 var thumbWidth: CGFloat { return CGFloat(bounds.height) } // for tracking the touch locations var previousLocation = CGPoint() // // Mark: - Component Layers and Properties // // the track of the slider let trackLayer = MidpointSliderTrackLayer() // this layer is for drawing the midpoint of the slider let trackMidpointLayer = MidpointSliderPointLayer() // what user slides/moves along the track to change the currentValue let thumbLayer = MidpointSliderThumbLayer() // // MARK: - UIControl initialization // // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. /* override func drawRect(rect: CGRect) { // Drawing code } */ private func initialize() { // adding layers trackLayer.midpointSlider = self // back reference trackLayer.contentsScale = UIScreen.mainScreen().scale // ensure looks good in retina display layer.addSublayer(trackLayer) trackMidpointLayer.midpointSlider = self // back reference trackMidpointLayer.contentsScale = UIScreen.mainScreen().scale layer.addSublayer(trackMidpointLayer) thumbLayer.midpointSlider = self // back reference thumbLayer.contentsScale = UIScreen.mainScreen().scale // ensure looks good on retina display layer.addSublayer(thumbLayer) } // for supporting initialization programmatically override public init(frame: CGRect) { super.init(frame: frame) self.initialize() } // for supporting use in Storyboard required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } override public var frame: CGRect { didSet { updateLayerFrames() } } override public func layoutSubviews() { super.layoutSubviews() let maximumSliderHeight = 30.0 if (self.frame.size.height > CGFloat(31.0)) { self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: CGFloat(maximumSliderHeight)) } else { self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) } self.setNeedsDisplay() } // utility - positions/fits the control's layers on screen func updateLayerFrames() { // position the track layer trackLayer.frame = bounds.insetBy(dx: 0.0, dy: bounds.height / 2.3) trackLayer.setNeedsDisplay() // position the midpoint layer let midpointLayerPosition = CGFloat(positionForValue((maximumValue + minimumValue) / 2)) trackMidpointLayer.frame = CGRect(x: midpointLayerPosition - thumbWidth / 2.0, y: 0.0, width: thumbWidth, height: thumbWidth) trackMidpointLayer.setNeedsDisplay() // position the thumb layer let thumbLayerPosition = CGFloat(positionForValue(currentValue)) thumbLayer.frame = CGRect(x: thumbLayerPosition - thumbWidth / 2.0, y: 0.0, width: thumbWidth, height: thumbWidth) thumbLayer.setNeedsDisplay() } // utility - For a slider value, provides its position func positionForValue(value: Double) -> Double { return Double(bounds.width - thumbWidth) * (value - minimumValue) / (maximumValue - minimumValue) + Double(thumbWidth / 2.0) } // // MARK: - UIControl Tracking Touch Methods // // For handlinw when user touches the control override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { // translate touch event into control's coordinate space previousLocation = touch.locationInView(self) // evaluate if the touch was inside the thumbLayer's frame, set the thumbLayers highlighted state if thumbLayer.frame.contains(previousLocation) { thumbLayer.highlighted = true } return thumbLayer.highlighted } // Utility for ensuring the slider value is within the control's minimumValue and maxiumValue properties - this also ensures the thumbLayer does not move off slider func boundValue(value: Double, toLowerValue lowerValue: Double, upperValue: Double) -> Double { return min(max(value, lowerValue), upperValue) } // For handling when users 'drags' along the control override public func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { // translate touch event into control's coordinate space let location = touch.locationInView(self) // number of pixels the user's touch travels let deltaLocation = Double(location.x - previousLocation.x) // scaled delta value based on the slider's min/max values let deltaValue = (maximumValue - minimumValue) * deltaLocation / Double(bounds.width - thumbWidth) previousLocation = location // update the value if thumbLayer.highlighted { currentValue += deltaValue currentValue = boundValue(currentValue, toLowerValue: minimumValue, upperValue: maximumValue) } // update the UI CATransaction.begin() CATransaction.setDisableActions(true) updateLayerFrames() CATransaction.commit() // notify any subscribed targets (e.g. any UIViewController that uses this slider) sendActionsForControlEvents(.ValueChanged) return true } // For handling when user is no longer touching and dragging on the control override public func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { thumbLayer.highlighted = false thumbLayer.setNeedsDisplay() } }
mit
a4356787735d9ce1333119ed7e3edaa2
32.008584
168
0.619685
5.154826
false
false
false
false
ahoppen/swift
test/Generics/deduction.swift
2
12928
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Deduction of generic arguments //===----------------------------------------------------------------------===// func identity<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> T { return value } // expected-note@-1 {{'identity2' produces 'Y', not the expected contextual result type 'X'}} func identity2<T>(_ value: T) -> Int { return 0 } // expected-note@-1 {{'identity2' produces 'Int', not the expected contextual result type 'X'}} struct X { } struct Y { } func useIdentity(_ x: Int, y: Float, i32: Int32) { var x2 = identity(x) var y2 = identity(y) // Deduction that involves the result type x2 = identity(17) var i32_2 : Int32 = identity(17) // Deduction where the result type and input type can get different results var xx : X, yy : Y xx = identity(yy) // expected-error{{cannot assign value of type 'Y' to type 'X'}} xx = identity2(yy) // expected-error{{no 'identity2' candidates produce the expected contextual result type 'X'}} } func twoIdentical<T>(_ x: T, _ y: T) -> T {} func useTwoIdentical(_ xi: Int, yi: Float) { var x = xi, y = yi x = twoIdentical(x, x) y = twoIdentical(y, y) x = twoIdentical(x, 1) x = twoIdentical(1, x) y = twoIdentical(1.0, y) y = twoIdentical(y, 1.0) twoIdentical(x, y) // expected-error{{conflicting arguments to generic parameter 'T' ('Int' vs. 'Float')}} } func mySwap<T>(_ x: inout T, _ y: inout T) { let tmp = x x = y y = tmp } func useSwap(_ xi: Int, yi: Float) { var x = xi, y = yi mySwap(&x, &x) mySwap(&y, &y) mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} // expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}} mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func takeTuples<T, U>(_: (T, U), _: (U, T)) { } func useTuples(_ x: Int, y: Float, z: (Float, Int)) { takeTuples((x, y), (y, x)) takeTuples((x, y), (x, y)) // expected-error@-1 {{conflicting arguments to generic parameter 'U' ('Float' vs. 'Int')}} // expected-error@-2 {{conflicting arguments to generic parameter 'T' ('Int' vs. 'Float')}} // FIXME: Use 'z', which requires us to fix our tuple-conversion // representation. } func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {} func passFunction(_ f: (Int) -> Float, x: Int, y: Float) { acceptFunction(f, x, y) acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}} func testReturnTuple(_ x: Int, y: Float) { returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}} var _ : (Int, Float) = returnTuple(x) var _ : (Float, Float) = returnTuple(y) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands var _ : (Int, Float) = returnTuple(y) // expected-error{{conflicting arguments to generic parameter 'T' ('Float' vs. 'Int')}} } func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) { confusingArgAndParam(g, f) confusingArgAndParam(f, g) } func acceptUnaryFn<T, U>(_ f: (T) -> U) { } func acceptUnaryFnSame<T>(_ f: (T) -> T) { } func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { } func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { } func unaryFnIntInt(_: Int) -> Int {} func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}} func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}} // Variable forms of the above functions var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt func passOverloadSet() { // Passing a non-generic function to a generic function acceptUnaryFn(unaryFnIntInt) acceptUnaryFnSame(unaryFnIntInt) // Passing an overloaded function set to a generic function // FIXME: Yet more terrible diagnostics. acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}} acceptUnaryFnSame(unaryFnOvl) // Passing a variable of function type to a generic function acceptUnaryFn(unaryFnIntIntVar) acceptUnaryFnSame(unaryFnIntIntVar) // Passing a variable of function type to a generic function to an inout parameter acceptUnaryFnRef(&unaryFnIntIntVar) acceptUnaryFnSameRef(&unaryFnIntIntVar) acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}} } func acceptFnFloatFloat(_ f: (Float) -> Float) {} func acceptFnDoubleDouble(_ f: (Double) -> Double) {} func passGeneric() { acceptFnFloatFloat(identity) acceptFnFloatFloat(identity2) } //===----------------------------------------------------------------------===// // Simple deduction for generic member functions //===----------------------------------------------------------------------===// struct SomeType { func identity<T>(_ x: T) -> T { return x } func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}} func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}} func returnAs<T>() -> T {} } func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) { var st = sti, i = ii, f = fi i = st.identity(i) f = st.identity(f) i = st.identity2(i) f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}} i = st.returnAs() f = st.returnAs() acceptFnFloatFloat(st.identity) acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}} acceptFnDoubleDouble(st.identity2) } struct StaticFuncs { static func chameleon<T>() -> T {} func chameleon2<T>() -> T {} } struct StaticFuncsGeneric<U> { static func chameleon<T>() -> T {} } func chameleon<T>() -> T {} func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) { var x: Int16 x = StaticFuncs.chameleon() x = sf.chameleon2() x = sfi.chameleon() // expected-error {{static member 'chameleon' cannot be used on instance of type 'StaticFuncsGeneric<Int>'}} typealias SFI = StaticFuncsGeneric<Int> x = SFI.chameleon() _ = x } //===----------------------------------------------------------------------===// // Deduction checking for constraints //===----------------------------------------------------------------------===// protocol IsBefore { func isBefore(_ other: Self) -> Bool } func min2<T : IsBefore>(_ x: T, _ y: T) -> T { // expected-note {{where 'T' = 'Float'}} if y.isBefore(x) { return y } return x } extension Int : IsBefore { func isBefore(_ other: Int) -> Bool { return self < other } } func callMin(_ x: Int, y: Int, a: Float, b: Float) { _ = min2(x, y) min2(a, b) // expected-error{{global function 'min2' requires that 'Float' conform to 'IsBefore'}} } func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} // expected-note {{where 'R.Element' = 'IndexingIterator<[Double]>.Element' (aka 'Double')}} func callRangeOfIsBefore(_ ia: [Int], da: [Double]) { rangeOfIsBefore(ia.makeIterator()) rangeOfIsBefore(da.makeIterator()) // expected-error{{global function 'rangeOfIsBefore' requires that 'IndexingIterator<[Double]>.Element' (aka 'Double') conform to 'IsBefore'}} } func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {} // expected-note@-1 {{where 'A.Element' = 'IndexingIterator<[Int]>.Element' (aka 'Int'), 'B.Element' = 'IndexingIterator<[Double]>.Element' (aka 'Double')}} func compareIterators() { var a: [Int] = [] var b: [Double] = [] testEqualIterElementTypes(a.makeIterator(), b.makeIterator()) // expected-error@-1 {{global function 'testEqualIterElementTypes' requires the types 'IndexingIterator<[Int]>.Element' (aka 'Int') and 'IndexingIterator<[Double]>.Element' (aka 'Double') be equivalent}} } protocol P_GI { associatedtype Y } class C_GI : P_GI { typealias Y = Double } class GI_Diff {} func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {} // expected-note@-1 {{where 'T.Y' = 'C_GI.Y' (aka 'Double')}} genericInheritsA(C_GI()) // expected-error@-1 {{global function 'genericInheritsA' requires that 'C_GI.Y' (aka 'Double') inherit from 'GI_Diff'}} //===----------------------------------------------------------------------===// // Deduction for member operators //===----------------------------------------------------------------------===// protocol Addable { static func +(x: Self, y: Self) -> Self } func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T { u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}} return x+y } //===----------------------------------------------------------------------===// // Deduction for bound generic types //===----------------------------------------------------------------------===// struct MyVector<T> { func size() -> Int {} } func getVectorSize<T>(_ v: MyVector<T>) -> Int { // expected-note {{in call to function 'getVectorSize'}} return v.size() } func ovlVector<T>(_ v: MyVector<T>) -> X {} func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {} func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) { var i : Int i = getVectorSize(vi) i = getVectorSize(vf) getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<T>'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} var x : X, y : Y x = ovlVector(vi) x = ovlVector(vf) var vvi : MyVector<MyVector<Int>> y = ovlVector(vvi) var yy = ovlVector(vvi) yy = y y = yy } // <rdar://problem/15104554> postfix operator <*> protocol MetaFunction { associatedtype Result static postfix func <*> (_: Self) -> Result? } protocol Bool_ {} struct False : Bool_ {} struct True : Bool_ {} postfix func <*> <B>(_: Test<B>) -> Int? { return .none } postfix func <*> (_: Test<True>) -> String? { return .none } class Test<C: Bool_> : MetaFunction { typealias Result = Int } // picks first <*> typealias Inty = Test<True>.Result var iy : Inty = 5 // okay, because we picked the first <*> var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}} // rdar://problem/20577950 class DeducePropertyParams { let badSet: Set = ["Hello"] } // SR-69 struct A {} func foo() { for i in min(1,2) { // expected-error{{for-in loop requires 'Int' to conform to 'Sequence'}} } let j = min(Int(3), Float(2.5)) // expected-error{{conflicting arguments to generic parameter 'T' ('Int' vs. 'Float')}} let k = min(A(), A()) // expected-error{{global function 'min' requires that 'A' conform to 'Comparable'}} let oi : Int? = 5 let l = min(3, oi) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } infix operator +& func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {} // expected-note@-1 {{where 'R.Element' = 'String', 'S.Element' = 'String.Element' (aka 'Character')}} func rdar33477726_1() { var arr: [String] = [] arr +& "hello" // expected-error@-1 {{operator function '+&' requires the types 'String' and 'String.Element' (aka 'Character') be equivalent}} } func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {} rdar33477726_2("answer", 42) // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String.Element' (aka 'Character')}} prefix operator +- prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {} // expected-note@-1 {{where 'T.Element' = 'String.Element' (aka 'Character')}} +-"hello" // expected-error@-1 {{operator function '+-' requires the types 'String.Element' (aka 'Character') and 'Int' be equivalent}} func test_transitive_subtype_deduction_for_generic_params() { class A {} func foo<T: A>(_: [(String, (T) -> Void)]) {} func bar<U>(_: @escaping (U) -> Void) -> (U) -> Void { return { _ in } } // Here we have: // - `W subtype of A` // - `W subtype of U` // // Type variable associated with `U` has to be attempted // first because solver can't infer bindings for `W` transitively // through `U`. func baz<W: A>(_ arr: [(String, (W) -> Void)]) { foo(arr.map { ($0.0, bar($0.1)) }) // Ok } func fiz<T>(_ a: T, _ op: (T, T) -> Bool, _ b: T) {} func biz(_ v: Int32) { fiz(v, !=, -1) // Ok because -1 literal should be inferred as Int32 } }
apache-2.0
afe19e939b2cc268ff8b19b09df0fa29
33.940541
205
0.609298
3.612182
false
false
false
false
Zverik/omim
iphone/Maps/UI/Settings/Cells/SettingsTableViewLinkCell.swift
6
626
@objc final class SettingsTableViewLinkCell: MWMTableViewCell { @IBOutlet fileprivate weak var title: UILabel! @IBOutlet fileprivate weak var info: UILabel! func config(title: String, info: String?) { backgroundColor = UIColor.white() self.title.text = title styleTitle() self.info.text = info self.info.isHidden = info == nil styleInfo() } fileprivate func styleTitle() { title.textColor = UIColor.blackPrimaryText() title.font = UIFont.regular17() } fileprivate func styleInfo() { info.textColor = UIColor.blackSecondaryText() info.font = UIFont.regular17() } }
apache-2.0
dc1fe844ee288ca4e5ab89593a39417e
23.076923
63
0.694888
4.317241
false
false
false
false
mightydeveloper/swift
test/SILGen/dynamic.swift
8
22220
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | FileCheck %s // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify // REQUIRES: objc_interop import Foundation import gizmo class Foo: Proto { // Not objc or dynamic, so only a vtable entry init(native: Int) {} func nativeMethod() {} var nativeProp: Int = 0 subscript(native native: Int) -> Int { get { return native } set {} } // @objc, so it has an ObjC entry point but can also be dispatched // by vtable @objc init(objc: Int) {} @objc func objcMethod() {} @objc var objcProp: Int = 0 @objc subscript(objc objc: AnyObject) -> Int { get { return 0 } set {} } // dynamic, so it has only an ObjC entry point dynamic init(dynamic: Int) {} dynamic func dynamicMethod() {} dynamic var dynamicProp: Int = 0 dynamic subscript(dynamic dynamic: Int) -> Int { get { return dynamic } set {} } func overriddenByDynamic() {} @NSManaged var managedProp: Int } protocol Proto { func nativeMethod() var nativeProp: Int { get set } subscript(native native: Int) -> Int { get set } func objcMethod() var objcProp: Int { get set } subscript(objc objc: AnyObject) -> Int { get set } func dynamicMethod() var dynamicProp: Int { get set } subscript(dynamic dynamic: Int) -> Int { get set } } // ObjC entry points for @objc and dynamic entry points // normal and @objc initializing ctors can be statically dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo10objcMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog8objcPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos8objcPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // TODO: dynamic initializing ctor must be objc dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TTDFC7dynamic3Fooc // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Fooc // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign : // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT7dynamicSi_Si // Protocol witnesses use best appropriate dispatch // Native witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_12nativeMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // @objc witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_10objcMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // Dynamic witnesses use objc dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_13dynamicMethod // CHECK: function_ref @_TTDFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foo13dynamicMethod // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign : // Superclass dispatch class Subclass: Foo { // Native and objc methods can directly reference super members override init(native: Int) { super.init(native: native) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclassC // CHECK: function_ref @_TFC7dynamic8Subclassc override func nativeMethod() { super.nativeMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass12nativeMethod // CHECK: function_ref @_TFC7dynamic3Foo12nativeMethod override var nativeProp: Int { get { return super.nativeProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foog10nativePropSi set { super.nativeProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foos10nativePropSi } override subscript(native native: Int) -> Int { get { return super[native: native] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT6nativeSi_Si set { super[native: native] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT6nativeSi_Si } override init(objc: Int) { super.init(objc: objc) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: function_ref @_TFC7dynamic3Fooc override func objcMethod() { super.objcMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass10objcMethod // CHECK: function_ref @_TFC7dynamic3Foo10objcMethod override var objcProp: Int { get { return super.objcProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foog8objcPropSi set { super.objcProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foos8objcPropSi } override subscript(objc objc: AnyObject) -> Int { get { return super[objc: objc] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si set { super[objc: objc] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si } // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign : override func dynamicMethod() { super.dynamicMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass13dynamicMethod // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign : override var dynamicProp: Int { get { return super.dynamicProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign : set { super.dynamicProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign : } override subscript(dynamic dynamic: Int) -> Int { get { return super[dynamic: dynamic] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign : set { super[dynamic: dynamic] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign : } dynamic override func overriddenByDynamic() {} } // CHECK-LABEL: sil hidden @_TF7dynamic20nativeMethodDispatchFT_T_ : $@convention(thin) () -> () func nativeMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(native: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic18objcMethodDispatchFT_T_ : $@convention(thin) () -> () func objcMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(objc: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[objc: 0 as NSNumber] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[objc: 0 as NSNumber] = y } // CHECK-LABEL: sil hidden @_TF7dynamic21dynamicMethodDispatchFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic15managedDispatchFCS_3FooT_ func managedDispatch(c: Foo) { // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic21foreignMethodDispatchFT_T_ func foreignMethodDispatch() { // CHECK: function_ref @_TFCSo9GuisemeauC let g = Guisemeau() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign g.frob() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign let x = g.count // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign g.count = x // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign let y: AnyObject! = g[0] // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign g[0] = y // CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign _ = g.description } extension Gizmo { // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5Gizmoc // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign convenience init(convenienceInExtension: Int) { self.init(bellsOn: convenienceInExtension) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassFactory x: Int) { self.init(stuff: x) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassExactFactory x: Int) { self.init(exactlyStuff: x) } @objc func foreignObjCExtension() { } dynamic func foreignDynamicExtension() { } } // CHECK-LABEL: sil hidden @_TF7dynamic24foreignExtensionDispatchFCSo5GizmoT_ func foreignExtensionDispatch(g: Gizmo) { // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : Gizmo g.foreignObjCExtension() // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign g.foreignDynamicExtension() } // CHECK-LABEL: sil hidden @_TF7dynamic33nativeMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func nativeMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(native: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic31objcMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func objcMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(objc: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[objc: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[objc: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic34dynamicMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic28managedDispatchFromOtherFileFCS_13FromOtherFileT_ func managedDispatchFromOtherFile(c: FromOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic23dynamicExtensionMethodsFCS_13ObjCOtherFileT_ func dynamicExtensionMethods(obj: ObjCOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign obj.extensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign _ = obj.extensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.extensionClassProp // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign obj.dynExtensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign _ = obj.dynExtensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.dynExtensionClassProp } public class Base { dynamic var x: Bool { return false } } public class Sub : Base { // CHECK-LABEL: sil hidden @_TFC7dynamic3Subg1xSb : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorType) // CHECK: = partial_apply [[AUTOCLOSURE]](%0) // CHECK: return {{%.*}} : $Bool // CHECK: } // CHECK-LABEL: sil shared [transparent] @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorType) { // CHECK: [[SUPER:%.*]] = super_method [volatile] %0 : $Sub, #Base.x!getter.1.foreign : Base -> () -> Bool , $@convention(objc_method) (Base) -> ObjCBool // CHECK: = apply [[SUPER]]({{%.*}}) // CHECK: return {{%.*}} : $Bool // CHECK: } override var x: Bool { return false || super.x } } // Vtable contains entries for native and @objc methods, but not dynamic ones // CHECK-LABEL: sil_vtable Foo { // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.nativeMethod!1: _TFC7dynamic3Foo12nativeMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.getter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.setter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.objcMethod!1: _TFC7dynamic3Foo10objcMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.getter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.setter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-NOT: dynamic.Foo.init (dynamic.Foo.Type)(dynamic : Swift.Int) -> dynamic.Foo // CHECK-NOT: dynamic.Foo.dynamicMethod // CHECK-NOT: dynamic.Foo.subscript.getter (dynamic : Swift.Int) -> Swift.Int // CHECK-NOT: dynamic.Foo.subscript.setter (dynamic : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TFC7dynamic3Foo19overriddenByDynamic // CHECK-LABEL: #Foo.nativeProp!getter.1: _TFC7dynamic3Foog10nativePropSi // dynamic.Foo.nativeProp.getter : Swift.Int // CHECK-LABEL: #Foo.nativeProp!setter.1: _TFC7dynamic3Foos10nativePropSi // dynamic.Foo.nativeProp.setter : Swift.Int // CHECK-LABEL: #Foo.objcProp!getter.1: _TFC7dynamic3Foog8objcPropSi // dynamic.Foo.objcProp.getter : Swift.Int // CHECK-LABEL: #Foo.objcProp!setter.1: _TFC7dynamic3Foos8objcPropSi // dynamic.Foo.objcProp.setter : Swift.Int // CHECK-NOT: dynamic.Foo.dynamicProp.getter // CHECK-NOT: dynamic.Foo.dynamicProp.setter // Vtable uses a dynamic thunk for dynamic overrides // CHECK-LABEL: sil_vtable Subclass { // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TTDFC7dynamic8Subclass19overriddenByDynamic
apache-2.0
68faef0b4468ebbdb874f3c490f76dd0
46.887931
165
0.695275
3.634876
false
false
false
false
mkoehnke/Prototyping
Prototyping.playground/Pages/Networking.xcplaygroundpage/Sources/NetworkClient.swift
1
7523
// // NetworkClient.swift // Concepts inspired by https://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics // import UIKit import Foundation //======================================== // MARK: Response //======================================== private struct Response { let data: NSData var statusCode: Int = 500 init(data: NSData, urlResponse: NSURLResponse) { self.data = data if let httpResponse = urlResponse as? NSHTTPURLResponse { self.statusCode = httpResponse.statusCode } } } public enum Result<A> { case Error(NSError) case Value(A) init(_ error: NSError?, _ value: A) { if let err = error { self = .Error(err) } else { self = .Value(value) } } } private func resultFromOptional<A>(optional: A?, error: NSError!) -> Result<A> { if let a = optional { return .Value(a) } else { return .Error(error) } } //======================================== // MARK: Functional //======================================== infix operator >>> { associativity left precedence 150 } // bind infix operator <^> { associativity left } // Functor's fmap (usually <$>) infix operator <*> { associativity left } // Applicative's apply infix operator <| { associativity left precedence 150 } infix operator <|* { associativity left precedence 150 } /// Takes the value of e.g. Result<Response> and passes it as parameter /// to the right-hand side function of >>> (e.g. parseResponse) public func >>><A, B>(a: Result<A>, f: A -> Result<B>) -> Result<B> { switch a { case let .Value(x): return f(x) case let .Error(error): return .Error(error) } } /// If the value on the left-hand side of >>> is a non-optional, /// it will be passed as parameter to the function on the right- /// hand side public func >>><A, B>(a: A?, f: A -> B?) -> B? { if let x = a { return f(x) } else { return .None } } /// If the value on the right-hand side of <^> is a non-optional, /// it will be passed as parameter to the function on the left- /// hand side public func <^><A, B>(f: A -> B, a: A?) -> B? { if let x = a { return f(x) } else { return .None } } public func <*><A, B>(f: (A -> B)?, a: A?) -> B? { if let x = a { if let fx = f { return fx(x) } } return .None } public func pure<A>(a: A) -> A? { return .Some(a) } public func <|<A>(object: JSONObject, key: String) -> A? { return object[key] >>> _JSONParse } public func <|*<A>(object: JSONObject, key: String) -> A?? { return pure(object[key] >>> _JSONParse) } //======================================== // MARK: JSON //======================================== public typealias JSON = AnyObject public typealias JSONObject = [String:AnyObject] public typealias JSONArray = [AnyObject] public protocol JSONDecodable { static func decode(json: JSON) -> Self? } public func _JSONParse<A>(object: JSON) -> A? { return object as? A } public func decodeJSON(data: NSData) -> Result<JSON> { let jsonOptional: JSON! var __error: NSError! do { jsonOptional = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) } catch let caught as NSError { __error = caught jsonOptional = [] } return resultFromOptional(jsonOptional, error: __error) } public func decodeObject<U: JSONDecodable>(json: JSON) -> Result<U> { let message = "Could not decode json object." return resultFromOptional(U.decode(json), error: NSError(domain: "de.mathiaskoehnke.prototyping", code: 2, userInfo: [NSLocalizedDescriptionKey : message])) } //======================================== // MARK: Perform JSON Requests //======================================== public func performJSONRequest<A: JSONDecodable>(request: NSURLRequest, callback: (Result<A>) -> ()) -> NSURLSessionTask? { let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, urlResponse, error in callback(parseResult(data, urlResponse: urlResponse, error: error)) } task.resume() return task } public func parseResult<A: JSONDecodable>(data: NSData!, urlResponse: NSURLResponse!, error: NSError!) -> Result<A> { let responseResult: Result<Response> = Result(error, Response(data: data, urlResponse: urlResponse)) return responseResult >>> parseResponse >>> decodeJSON >>> decodeObject } private func parseResponse(response: Response) -> Result<NSData> { let successRange = 200..<300 if !successRange.contains(response.statusCode) { let message = "Data could not be loaded." return .Error(NSError(domain: "de.mathiaskoehnke.prototyping", code: 1, userInfo: [NSLocalizedDescriptionKey : message])) } return Result(nil, response.data) } //======================================== // MARK: Perform Batch Requests //======================================== public func performBatchRequest( requests: [NSURLRequest], callback: ([NSURLRequest : Result<NSData>]) -> ()) { let group = dispatch_group_create() var results = [NSURLRequest : Result<NSData>]() for request in requests { dispatch_group_enter(group) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, urlResponse, error in let responseResult: Result<Response> = Result(error, Response(data: data!, urlResponse: urlResponse!)) results[request] = responseResult >>> parseResponse dispatch_group_leave(group) } task.resume() } dispatch_group_notify(group, dispatch_get_main_queue()) { callback(results) } } //======================================== // MARK: Perform Image Requests //======================================== private let __imageCache = NSCache() public func performImageRequest(request: NSURLRequest, callback: (Result<UIImage>, request: NSURLRequest) -> ()) -> NSURLSessionTask? { let cachedImage = fetchCachedImage(request) switch cachedImage { case .Value: callback(cachedImage, request: request) case .Error: return fetchRemoteImage(request, callback: callback) } return nil } private func fetchRemoteImage(request: NSURLRequest, callback: (Result<UIImage>, request: NSURLRequest) -> ()) -> NSURLSessionTask? { let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, urlResponse, error) in let responseResult: Result<Response> = Result(error, Response(data: data!, urlResponse: urlResponse!)) callback(responseResult >>> parseResponse >>> imageFromData(request), request: request) }) task.resume() return task } private func fetchCachedImage(request: NSURLRequest) -> Result<UIImage> { var image : UIImage? if let data = __imageCache.objectForKey(request.URL!.absoluteString) as? NSPurgeableData where data.beginContentAccess() == true { image = UIImage(data: data) data.endContentAccess() } return resultFromOptional(image, error: NSError(domain: "<Your domain>", code: 1, userInfo: nil)) } private func imageFromData(request: NSURLRequest)(data: NSData) -> Result<UIImage> { __imageCache.setObject(NSPurgeableData(data: data), forKey: request.URL!.absoluteString) return resultFromOptional(UIImage(data: data), error: NSError(domain: "<Your domain>", code: 1, userInfo: nil)) }
mit
c9a1af22ef93940a2312401ec1ddeba4
31.708696
160
0.613984
4.221661
false
false
false
false
zisko/swift
stdlib/public/core/StringIndex.swift
1
6114
//===--- StringIndex.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { /// A position of a character or code unit in a string. @_fixed_layout // FIXME(sil-serialize-all) public struct Index { @_versioned // FIXME(sil-serialize-all) internal var _compoundOffset : UInt64 @_versioned internal var _cache: _Cache internal typealias _UTF8Buffer = _ValidUTF8Buffer<UInt64> @_fixed_layout // FIXME(sil-serialize-all) @_versioned internal enum _Cache { case utf16 case utf8(buffer: _UTF8Buffer) case character(stride: UInt16) case unicodeScalar(value: Unicode.Scalar) } } } /// Convenience accessors extension String.Index._Cache { @_inlineable // FIXME(sil-serialize-all) @_versioned internal var utf16: Void? { if case .utf16 = self { return () } else { return nil } } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var utf8: String.Index._UTF8Buffer? { if case .utf8(let r) = self { return r } else { return nil } } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var character: UInt16? { if case .character(let r) = self { return r } else { return nil } } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var unicodeScalar: UnicodeScalar? { if case .unicodeScalar(let r) = self { return r } else { return nil } } } extension String.Index : Equatable { @_inlineable // FIXME(sil-serialize-all) public static func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset == rhs._compoundOffset } } extension String.Index : Comparable { @_inlineable // FIXME(sil-serialize-all) public static func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset < rhs._compoundOffset } } extension String.Index : Hashable { @_inlineable // FIXME(sil-serialize-all) public var hashValue: Int { return _compoundOffset.hashValue } } extension String.Index { internal typealias _Self = String.Index /// Creates a new index at the specified UTF-16 offset. /// /// - Parameter offset: An offset in UTF-16 code units. @_inlineable // FIXME(sil-serialize-all) public init(encodedOffset offset: Int) { _compoundOffset = UInt64(offset << _Self._strideBits) _cache = .utf16 } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(encodedOffset o: Int, transcodedOffset: Int = 0, _ c: _Cache) { _compoundOffset = UInt64(o << _Self._strideBits | transcodedOffset) _cache = c } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _strideBits : Int { return 2 } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _mask : UInt64 { return (1 &<< _Self._strideBits) &- 1 } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal mutating func _setEncodedOffset(_ x: Int) { _compoundOffset = UInt64(x << _Self._strideBits) } /// The offset into a string's UTF-16 encoding for this index. @_inlineable // FIXME(sil-serialize-all) public var encodedOffset : Int { return Int(_compoundOffset >> _Self._strideBits) } /// The offset of this index within whatever encoding this is being viewed as @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _transcodedOffset : Int { get { return Int(_compoundOffset & _Self._mask) } set { let extended = UInt64(newValue) _sanityCheck(extended <= _Self._mask) _compoundOffset &= ~_Self._mask _compoundOffset |= extended } } } // SPI for Foundation extension String.Index { @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_position: Int) { self.init(encodedOffset: _position) } @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_offset: Int) { self.init(encodedOffset: _offset) } @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_base: String.Index, in c: String.CharacterView) { self = _base } /// The integer offset of this index in UTF-16 code units. @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _utf16Index: Int { return self.encodedOffset } /// The integer offset of this index in UTF-16 code units. @_inlineable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _offset: Int { return self.encodedOffset } } // backward compatibility for index interchange. extension Optional where Wrapped == String.Index { @_inlineable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ..<( lhs: String.Index?, rhs: String.Index? ) -> Range<String.Index> { return lhs! ..< rhs! } @_inlineable // FIXME(sil-serialize-all) @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ...( lhs: String.Index?, rhs: String.Index? ) -> ClosedRange<String.Index> { return lhs! ... rhs! } }
apache-2.0
6455c9374a2703d798dc453e40700f97
29.723618
104
0.657671
3.838041
false
false
false
false
ekgorter/MyWikiTravel
MyWikiTravel/MyWikiTravel/Article.swift
1
921
// // Article.swift // MyWikiTravel // // Created by Elias Gorter on 25-06-15. // Copyright (c) 2015 EliasGorter6052274. All rights reserved. // // Description of Article entity in Core Data. import Foundation import CoreData class Article: NSManagedObject { @NSManaged var text: String @NSManaged var title: String @NSManaged var image: NSData @NSManaged var belongsToGuide: Guide // Method allows creation of new article. class func createInManagedObjectContext(moc: NSManagedObjectContext, title: String, text: String, image: NSData, guide: Guide) -> Article { let newArticle = NSEntityDescription.insertNewObjectForEntityForName("Article", inManagedObjectContext: moc) as! Article newArticle.title = title newArticle.text = text newArticle.image = image newArticle.belongsToGuide = guide return newArticle } }
unlicense
947641e2170e521d54c72917bbb7e767
27.78125
143
0.698154
4.559406
false
false
false
false
FengDeng/RXGitHub
RxGitHubAPI/YYTeam.swift
1
497
// // YYTeam.swift // RxGitHub // // Created by 邓锋 on 16/1/27. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYTeam : NSObject{ public var id = 0 public var name = "" public var slug = "" public var _description = "" public var privacy = "" public var permission = "" public static override func mj_replacedKeyFromPropertyName() -> [NSObject : AnyObject]! { return ["_description":"description"] } }
mit
de4dc71b223b26cfd99ac21a4d718456
21.318182
93
0.628571
3.98374
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/menuUI/DZMRMLeftView.swift
1
6957
// // DZMRMLeftView.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/5/15. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMRMLeftView: DZMRMBaseView,DZMSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource { /// topView private(set) var topView:DZMSegmentedControl! /// UITableView private(set) var tableView:UITableView! /// contentView private(set) var contentView:UIView! /// 类型 0: 章节 1: 书签 private var type:NSInteger = 0 override func addSubviews() { super.addSubviews() // contentView contentView = UIView() contentView.backgroundColor = UIColor.black.withAlphaComponent(0.7) addSubview(contentView) // UITableView tableView = UITableView() tableView.backgroundColor = UIColor.clear tableView.separatorStyle = .none tableView.delegate = self tableView.dataSource = self contentView.addSubview(tableView) // topView topView = DZMSegmentedControl() topView.delegate = self topView.normalTitles = ["章节","书签"] topView.selectTitles = ["章节","书签"] topView.horizontalShowTB = false topView.backgroundColor = UIColor.clear topView.normalTitleColor = DZMColor_6 topView.selectTitleColor = DZMColor_2 topView.setup() contentView.addSubview(topView) } // MARK: -- 定位到阅读记录 func scrollReadRecord() { if type == 0 { // 章节 let readChapterModel = readMenu.vc.readModel.readRecordModel.readChapterModel let readChapterListModels = readMenu.vc.readModel.readChapterListModels if readChapterModel != nil && readChapterListModels.count != 0 { DispatchQueue.global().async { [weak self] ()->Void in for i in 0..<readChapterListModels.count { let model = readChapterListModels[i] if model.id == readChapterModel!.id { // 更新UI DispatchQueue.main.async { [weak self] ()->Void in self?.tableView.scrollToRow(at: IndexPath(row: i, section: 0), at: UITableViewScrollPosition.middle, animated: false) } return } } } } } } // MARK: -- DZMSegmentedControlDelegate func segmentedControl(segmentedControl: DZMSegmentedControl, clickButton button: UIButton, index: NSInteger) { type = index tableView.reloadData() scrollReadRecord() } /// 布局 override func layoutSubviews() { super.layoutSubviews() // contentView let contentViewW:CGFloat = width * 0.6 contentView.frame = CGRect(x: -contentViewW, y: 0, width: contentViewW, height: height) // topView let topViewY:CGFloat = isX ? TopLiuHeight : 0 let topViewH:CGFloat = 33 topView.frame = CGRect(x: 0, y: topViewY, width: contentViewW, height: topViewH) // tableView let tableViewY = topView.frame.maxY tableView.frame = CGRect(x: 0, y: tableViewY, width: contentView.width, height: height - tableViewY) } // MARK: -- UITableViewDelegate,UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if type == 0 { // 章节 return (readMenu.vc.readModel != nil ? readMenu.vc.readModel.readChapterListModels.count : 0) }else{ // 书签 return (readMenu.vc.readModel != nil ? readMenu.vc.readModel.readMarkModels.count : 0) } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "DZMRMLeftViewCell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "DZMRMLeftViewCell") cell?.selectionStyle = .none cell?.backgroundColor = UIColor.clear } if type == 0 { // 章节 cell?.textLabel?.text = readMenu.vc.readModel.readChapterListModels[indexPath.row].name cell?.textLabel?.numberOfLines = 1 cell?.textLabel?.font = DZMFont_18 }else{ // 书签 let readMarkModel = readMenu.vc.readModel.readMarkModels[indexPath.row] cell?.textLabel?.text = "\n\(readMarkModel.name!)\n\(GetTimerString(dateFormat: "YYYY-MM-dd HH:mm:ss", date: readMarkModel.time!))\n\(readMarkModel.content!))" cell?.textLabel?.numberOfLines = 0 cell?.textLabel?.font = DZMFont_12 } cell?.textLabel?.textColor = DZMColor_6 return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if type == 0 { // 章节 return 44 }else{ // 书签 return 120 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if type == 0 { // 章节 readMenu.delegate?.readMenuClickChapterList?(readMenu: readMenu, readChapterListModel: readMenu.vc.readModel.readChapterListModels[indexPath.row]) }else{ // 书签 readMenu.delegate?.readMenuClickMarkList?(readMenu: readMenu, readMarkModel: readMenu.vc.readModel.readMarkModels[indexPath.row]) } // 隐藏 readMenu.leftView(isShow: false, complete: nil) } // MARK: -- 删除操作 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if type == 0 { // 章节 return false }else{ // 书签 return true } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let _ = readMenu.vc.readModel.removeMark(readMarkModel: nil, index: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade) } }
apache-2.0
19c97da0917490f4895e58959226c03b
30.823256
171
0.545455
5.086989
false
false
false
false
brentdax/swift
stdlib/public/core/Array.swift
2
71285
//===--- Array.swift ------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `Array<Element>` is like `ContiguousArray<Element>` when `Element` is not // a reference type or an Objective-C existential. Otherwise, it may use // an `NSArray` bridged from Cocoa for storage. // //===----------------------------------------------------------------------===// /// An ordered, random-access collection. /// /// Arrays are one of the most commonly used data types in an app. You use /// arrays to organize your app's data. Specifically, you use the `Array` type /// to hold elements of a single type, the array's `Element` type. An array /// can store any kind of elements---from integers to strings to classes. /// /// Swift makes it easy to create arrays in your code using an array literal: /// simply surround a comma-separated list of values with square brackets. /// Without any other information, Swift creates an array that includes the /// specified values, automatically inferring the array's `Element` type. For /// example: /// /// // An array of 'Int' elements /// let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15] /// /// // An array of 'String' elements /// let streets = ["Albemarle", "Brandywine", "Chesapeake"] /// /// You can create an empty array by specifying the `Element` type of your /// array in the declaration. For example: /// /// // Shortened forms are preferred /// var emptyDoubles: [Double] = [] /// /// // The full type name is also allowed /// var emptyFloats: Array<Float> = Array() /// /// If you need an array that is preinitialized with a fixed number of default /// values, use the `Array(repeating:count:)` initializer. /// /// var digitCounts = Array(repeating: 0, count: 10) /// print(digitCounts) /// // Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" /// /// Accessing Array Values /// ====================== /// /// When you need to perform an operation on all of an array's elements, use a /// `for`-`in` loop to iterate through the array's contents. /// /// for street in streets { /// print("I don't live on \(street).") /// } /// // Prints "I don't live on Albemarle." /// // Prints "I don't live on Brandywine." /// // Prints "I don't live on Chesapeake." /// /// Use the `isEmpty` property to check quickly whether an array has any /// elements, or use the `count` property to find the number of elements in /// the array. /// /// if oddNumbers.isEmpty { /// print("I don't know any odd numbers.") /// } else { /// print("I know \(oddNumbers.count) odd numbers.") /// } /// // Prints "I know 8 odd numbers." /// /// Use the `first` and `last` properties for safe access to the value of the /// array's first and last elements. If the array is empty, these properties /// are `nil`. /// /// if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last { /// print(firstElement, lastElement, separator: ", ") /// } /// // Prints "1, 15" /// /// print(emptyDoubles.first, emptyDoubles.last, separator: ", ") /// // Prints "nil, nil" /// /// You can access individual array elements through a subscript. The first /// element of a nonempty array is always at index zero. You can subscript an /// array with any integer from zero up to, but not including, the count of /// the array. Using a negative number or an index equal to or greater than /// `count` triggers a runtime error. For example: /// /// print(oddNumbers[0], oddNumbers[3], separator: ", ") /// // Prints "1, 7" /// /// print(emptyDoubles[0]) /// // Triggers runtime error: Index out of range /// /// Adding and Removing Elements /// ============================ /// /// Suppose you need to store a list of the names of students that are signed /// up for a class you're teaching. During the registration period, you need /// to add and remove names as students add and drop the class. /// /// var students = ["Ben", "Ivy", "Jordell"] /// /// To add single elements to the end of an array, use the `append(_:)` method. /// Add multiple elements at the same time by passing another array or a /// sequence of any kind to the `append(contentsOf:)` method. /// /// students.append("Maxime") /// students.append(contentsOf: ["Shakia", "William"]) /// // ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"] /// /// You can add new elements in the middle of an array by using the /// `insert(_:at:)` method for single elements and by using /// `insert(contentsOf:at:)` to insert multiple elements from another /// collection or array literal. The elements at that index and later indices /// are shifted back to make room. /// /// students.insert("Liam", at: 3) /// // ["Ben", "Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// To remove elements from an array, use the `remove(at:)`, /// `removeSubrange(_:)`, and `removeLast()` methods. /// /// // Ben's family is moving to another state /// students.remove(at: 0) /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"] /// /// // William is signing up for a different class /// students.removeLast() /// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"] /// /// You can replace an existing element with a new value by assigning the new /// value to the subscript. /// /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// // ["Ivy", "Jordell", "Liam", "Max", "Shakia"] /// /// Growing the Size of an Array /// ---------------------------- /// /// Every array reserves a specific amount of memory to hold its contents. When /// you add elements to an array and that array begins to exceed its reserved /// capacity, the array allocates a larger region of memory and copies its /// elements into the new storage. The new storage is a multiple of the old /// storage's size. This exponential growth strategy means that appending an /// element happens in constant time, averaging the performance of many append /// operations. Append operations that trigger reallocation have a performance /// cost, but they occur less and less often as the array grows larger. /// /// If you know approximately how many elements you will need to store, use the /// `reserveCapacity(_:)` method before appending to the array to avoid /// intermediate reallocations. Use the `capacity` and `count` properties to /// determine how many more elements the array can store without allocating /// larger storage. /// /// For arrays of most `Element` types, this storage is a contiguous block of /// memory. For arrays with an `Element` type that is a class or `@objc` /// protocol type, this storage can be a contiguous block of memory or an /// instance of `NSArray`. Because any arbitrary subclass of `NSArray` can /// become an `Array`, there are no guarantees about representation or /// efficiency in this case. /// /// Modifying Copies of Arrays /// ========================== /// /// Each array has an independent value that includes the values of all of its /// elements. For simple types such as integers and other structures, this /// means that when you change a value in one array, the value of that element /// does not change in any copies of the array. For example: /// /// var numbers = [1, 2, 3, 4, 5] /// var numbersCopy = numbers /// numbers[0] = 100 /// print(numbers) /// // Prints "[100, 2, 3, 4, 5]" /// print(numbersCopy) /// // Prints "[1, 2, 3, 4, 5]" /// /// If the elements in an array are instances of a class, the semantics are the /// same, though they might appear different at first. In this case, the /// values stored in the array are references to objects that live outside the /// array. If you change a reference to an object in one array, only that /// array has a reference to the new object. However, if two arrays contain /// references to the same object, you can observe changes to that object's /// properties from both arrays. For example: /// /// // An integer type with reference semantics /// class IntegerReference { /// var value = 10 /// } /// var firstIntegers = [IntegerReference(), IntegerReference()] /// var secondIntegers = firstIntegers /// /// // Modifications to an instance are visible from either array /// firstIntegers[0].value = 100 /// print(secondIntegers[0].value) /// // Prints "100" /// /// // Replacements, additions, and removals are still visible /// // only in the modified array /// firstIntegers[0] = IntegerReference() /// print(firstIntegers[0].value) /// // Prints "10" /// print(secondIntegers[0].value) /// // Prints "100" /// /// Arrays, like all variable-size collections in the standard library, use /// copy-on-write optimization. Multiple copies of an array share the same /// storage until you modify one of the copies. When that happens, the array /// being modified replaces its storage with a uniquely owned copy of itself, /// which is then modified in place. Optimizations are sometimes applied that /// can reduce the amount of copying. /// /// This means that if an array is sharing storage with other copies, the first /// mutating operation on that array incurs the cost of copying the array. An /// array that is the sole owner of its storage can perform mutating /// operations in place. /// /// In the example below, a `numbers` array is created along with two copies /// that share the same storage. When the original `numbers` array is /// modified, it makes a unique copy of its storage before making the /// modification. Further modifications to `numbers` are made in place, while /// the two copies continue to share the original storage. /// /// var numbers = [1, 2, 3, 4, 5] /// var firstCopy = numbers /// var secondCopy = numbers /// /// // The storage for 'numbers' is copied here /// numbers[0] = 100 /// numbers[1] = 200 /// numbers[2] = 300 /// // 'numbers' is [100, 200, 300, 4, 5] /// // 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5] /// /// Bridging Between Array and NSArray /// ================================== /// /// When you need to access APIs that require data in an `NSArray` instance /// instead of `Array`, use the type-cast operator (`as`) to bridge your /// instance. For bridging to be possible, the `Element` type of your array /// must be a class, an `@objc` protocol (a protocol imported from Objective-C /// or marked with the `@objc` attribute), or a type that bridges to a /// Foundation type. /// /// The following example shows how you can bridge an `Array` instance to /// `NSArray` to use the `write(to:atomically:)` method. In this example, the /// `colors` array can be bridged to `NSArray` because the `colors` array's /// `String` elements bridge to `NSString`. The compiler prevents bridging the /// `moreColors` array, on the other hand, because its `Element` type is /// `Optional<String>`, which does *not* bridge to a Foundation type. /// /// let colors = ["periwinkle", "rose", "moss"] /// let moreColors: [String?] = ["ochre", "pine"] /// /// let url = NSURL(fileURLWithPath: "names.plist") /// (colors as NSArray).write(to: url, atomically: true) /// // true /// /// (moreColors as NSArray).write(to: url, atomically: true) /// // error: cannot convert value of type '[String?]' to type 'NSArray' /// /// Bridging from `Array` to `NSArray` takes O(1) time and O(1) space if the /// array's elements are already instances of a class or an `@objc` protocol; /// otherwise, it takes O(*n*) time and space. /// /// When the destination array's element type is a class or an `@objc` /// protocol, bridging from `NSArray` to `Array` first calls the `copy(with:)` /// (`- copyWithZone:` in Objective-C) method on the array to get an immutable /// copy and then performs additional Swift bookkeeping work that takes O(1) /// time. For instances of `NSArray` that are already immutable, `copy(with:)` /// usually returns the same array in O(1) time; otherwise, the copying /// performance is unspecified. If `copy(with:)` returns the same array, the /// instances of `NSArray` and `Array` share storage using the same /// copy-on-write optimization that is used when two instances of `Array` /// share storage. /// /// When the destination array's element type is a nonclass type that bridges /// to a Foundation type, bridging from `NSArray` to `Array` performs a /// bridging copy of the elements to contiguous storage in O(*n*) time. For /// example, bridging from `NSArray` to `Array<Int>` performs such a copy. No /// further bridging is required when accessing elements of the `Array` /// instance. /// /// - Note: The `ContiguousArray` and `ArraySlice` types are not bridged; /// instances of those types always have a contiguous block of memory as /// their storage. @_fixed_layout public struct Array<Element>: _DestructorSafeContainer { #if _runtime(_ObjC) @usableFromInline internal typealias _Buffer = _ArrayBuffer<Element> #else @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> #endif @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension Array { /// Returns `true` if the array is native and does not need a deferred /// type check. May be hoisted by the optimizer, which means its /// results may be stale by the time they are used if there is an /// inout violation in user code. @inlinable @_semantics("array.props.isNativeTypeChecked") public // @testable func _hoistableIsNativeTypeChecked() -> Bool { return _buffer.arrayPropertyIsNativeTypeChecked } @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.count } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.capacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _buffer = _Buffer(copying: _buffer) } } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _ = _checkSubscript(index, wasNativeTypeChecked: true) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @_semantics("array.check_subscript") public // @testable func _checkSubscript( _ index: Int, wasNativeTypeChecked: Bool ) -> _DependenceToken { #if _runtime(_ObjC) _buffer._checkInoutAndNativeTypeCheckedBounds( index, wasNativeTypeChecked: wasNativeTypeChecked) #else _buffer._checkValidSubscript(index) #endif return _DependenceToken() } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "Array index is out of range") _precondition(index >= startIndex, "Negative Array index is out of range") } @_semantics("array.get_element") @inline(__always) public // @testable func _getElement( _ index: Int, wasNativeTypeChecked: Bool, matchingSubscriptCheck: _DependenceToken ) -> Element { #if _runtime(_ObjC) return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked) #else return _buffer.getElement(index) #endif } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.subscriptBaseAddress + index } } extension Array: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 12 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { @inline(__always) get { return _buffer.owner } } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } } extension Array: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<Array> /// The position of the first element in a nonempty array. /// /// For an instance of `Array`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array or uses a /// bridged `NSArray` instance as its storage, in which case writing is /// O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { // This call may be hoisted or eliminated by the optimizer. If // there is an inout violation, this value may be stale so needs to be // checked again below. let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() // Make sure the index is in range and wasNativeTypeChecked is // still valid. let token = _checkSubscript( index, wasNativeTypeChecked: wasNativeTypeChecked) return _getElement( index, wasNativeTypeChecked: wasNativeTypeChecked, matchingSubscriptCheck: token) } _modify { _makeMutableAndUnique() // makes the array native, too _checkSubscript_native(index) let address = _buffer.subscriptBaseAddress + index yield &address.pointee } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension Array: ExpressibleByArrayLiteral { // Optimized implementation for Array /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler /// when you use an array literal. Instead, create a new array by using an /// array literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding /// only strings. /// /// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self = elements } } extension Array: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = Array( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = Array._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a Array of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct Array with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = Array._allocateBufferUninitialized(minimumCapacity: count) _buffer.count = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a Array of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let result = Array(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } /// Returns an Array of `count` uninitialized elements using the /// given `storage`, and a pointer to uninitialized memory for the /// first element. /// /// - Precondition: `storage is _ContiguousArrayStorage`. @inlinable @_semantics("array.uninitialized") internal static func _adoptStorage( _ storage: __owned _ContiguousArrayStorage<Element>, count: Int ) -> (Array, UnsafeMutablePointer<Element>) { let innerBuffer = _ContiguousArrayBuffer<Element>( count: count, storage: storage) return ( Array( _buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)), innerBuffer.firstElementAddress) } /// Entry point for aborting literal construction: deallocates /// a Array containing only uninitialized elements. @inlinable internal mutating func _deallocateUninitialized() { // Set the count to zero and just release as normal. // Somewhat of a hack. _buffer.count = 0 } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// Calling the `reserveCapacity(_:)` method on an array with bridged storage /// triggers a copy to contiguous storage even if the existing storage /// has room to store `minimumCapacity` elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: minimumCapacity) == nil { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: minimumCapacity) _buffer._copyContents( subRange: _buffer.indices, initializing: newBuffer.firstElementAddress) _buffer = _Buffer( _buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex) } _sanityCheck(capacity >= minimumCapacity) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate(&newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _copyToNewBuffer(oldCount: _buffer.count) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // This is a performance optimization. This code used to be in an || // statement in the _sanityCheck below. // // _sanityCheck(_buffer.capacity == 0 || // _buffer.isMutableAndUniquelyReferenced()) // // SR-6437 let capacity = _buffer.capacity == 0 // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that preceeds this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. _sanityCheck(capacity || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > _buffer.capacity) { _copyToNewBuffer(oldCount: oldCount) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _sanityCheck(_buffer.isMutableAndUniquelyReferenced()) _sanityCheck(_buffer.capacity >= _buffer.count + 1) _buffer.count = oldCount + 1 (_buffer.firstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _getCount() _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { let newElementsCount = newElements.underestimatedCount reserveCapacityForAppend(newElementsCount: newElementsCount) let oldCount = self.count let startNewElements = _buffer.firstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: self.capacity - oldCount) let (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate _buffer.count += writtenCount if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode _buffer._arrayAppendSequence(IteratorSequence(remainder)) } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { let oldCount = self.count let oldCapacity = self.capacity let newCount = oldCount + newElementsCount // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. self.reserveCapacity( newCount > oldCapacity ? Swift.max(newCount, _growArrayCapacity(oldCapacity)) : newCount) } @inlinable public mutating func _customRemoveLast() -> Element? { let newCount = _getCount() - 1 _precondition(newCount >= 0, "Can't removeLast from an empty Array") _makeUniqueAndReserveCapacityIfNotUnique() let pointer = (_buffer.firstElementAddress + newCount) let element = pointer.move() _buffer.count = newCount return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult public mutating func remove(at index: Int) -> Element { _precondition(index < endIndex, "Index out of range") _precondition(index >= startIndex, "Index out of range") _makeUniqueAndReserveCapacityIfNotUnique() let newCount = _getCount() - 1 let pointer = (_buffer.firstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.count = newCount return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(_buffer) } } extension Array: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension Array: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { // Always show sugared representation for Arrays. return _makeCollectionDescription() } } extension Array { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension Array { /// Creates an array with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. /// /// Inside the closure, set the `initializedCount` parameter to the number of /// elements that are initialized by the closure. The memory in the range /// `buffer[0..<initializedCount]` must be initialized at the end of the /// closure's execution, and the memory in the range /// `buffer[initializedCount...]` must be uninitialized. /// /// - Note: While the resulting array may have a capacity larger than the /// requested amount, the buffer passed to the closure will cover exactly /// the requested number of elements. /// /// - Parameters: /// - _unsafeUninitializedCapacity: The number of elements to allocate /// space for in the new array. /// - initializer: A closure that initializes elements and sets the count /// of the new array. /// - Parameters: /// - buffer: A buffer covering uninitialized memory with room for the /// specified number of of elements. /// - initializedCount: The count of initialized elements in the array, /// which begins as zero. Set `initializedCount` to the number of /// elements you initialize. @inlinable public init( _unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { var firstElementAddress: UnsafeMutablePointer<Element> (self, firstElementAddress) = Array._allocateUninitialized(_unsafeUninitializedCapacity) var initializedCount = 0 defer { // Update self.count even if initializer throws an error. _precondition( initializedCount <= _unsafeUninitializedCapacity, "Initialized count set to greater than specified capacity." ) self._buffer.count = initializedCount } var buffer = UnsafeMutableBufferPointer<Element>( start: firstElementAddress, count: _unsafeUninitializedCapacity) try initializer(&buffer, &initializedCount) } /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If no such storage exists, it is created. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { let count = self.count // Ensure unique storage _buffer._outlinedMakeUniqueBuffer(bufferCount: count) // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. // NOTE: The stack promotion optimization that keys of the // "array.withUnsafeMutableBufferPointer" semantics annotation relies on the // array buffer not being able to escape in the closure. It can do this // because we swap the array buffer in self with an empty buffer here. Any // escape via the address of self in the closure will therefore escape the // empty array. var work = Array() (work, self) = (self, work) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.firstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed") (work, self) = (self, work) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension Array { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "Array replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "Array replace: subrange extends past the end") let oldCount = _buffer.count let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: oldCount + growth) != nil { _buffer.replaceSubrange( subrange, with: insertCount, elementsOf: newElements) } else { _buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount) } } } extension Array: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _sanityCheck(lhs.startIndex == 0 && rhs.startIndex == 0) _sanityCheck(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension Array: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension Array { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...] /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } #if _runtime(_ObjC) // We isolate the bridging of the Cocoa Array -> Swift Array here so that // in the future, we can eagerly bridge the Cocoa array. We need this function // to do the bridging in an ABI safe way. Even though this looks useless, // DO NOT DELETE! @usableFromInline internal func _bridgeCocoaArray<T>(_ _immutableCocoaArray: _NSArrayCore) -> Array<T> { return Array(_buffer: _ArrayBuffer(nsArray: _immutableCocoaArray)) } extension Array { @inlinable public // @SPI(Foundation) func _bridgeToObjectiveCImpl() -> AnyObject { return _buffer._asCocoaArray() } /// Tries to downcast the source `NSArray` as our native buffer type. /// If it succeeds, creates a new `Array` around it and returns that. /// Returns `nil` otherwise. // Note: this function exists here so that Foundation doesn't have // to know Array's implementation details. @inlinable public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ source: AnyObject ) -> Array? { // If source is deferred, we indirect to get its native storage let maybeNative = (source as? __SwiftDeferredNSArray)?._nativeStorage ?? source return (maybeNative as? _ContiguousArrayStorage<Element>).map { Array(_ContiguousArrayBuffer($0)) } } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSArray` is immutable; /// * `Element` is bridged verbatim to Objective-C (i.e., /// is a reference type). @inlinable public init(_immutableCocoaArray: _NSArrayCore) { self = _bridgeCocoaArray(_immutableCocoaArray) } } #endif extension Array: _HasCustomAnyHashableRepresentation where Element: Hashable { public __consuming func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _ArrayAnyHashableBox(self)) } } internal protocol _ArrayAnyHashableProtocol: _AnyHashableBox { var count: Int { get } subscript(index: Int) -> AnyHashable { get } } internal struct _ArrayAnyHashableBox<Element: Hashable> : _ArrayAnyHashableProtocol { internal let _value: [Element] internal init(_ value: [Element]) { self._value = value } internal var _base: Any { return _value } internal var count: Int { return _value.count } internal subscript(index: Int) -> AnyHashable { return _value[index] as AnyHashable } func _isEqual(to other: _AnyHashableBox) -> Bool? { guard let other = other as? _ArrayAnyHashableProtocol else { return nil } guard _value.count == other.count else { return false } for i in 0 ..< _value.count { if self[i] != other[i] { return false } } return true } var _hashValue: Int { var hasher = Hasher() _hash(into: &hasher) return hasher.finalize() } func _hash(into hasher: inout Hasher) { hasher.combine(_value.count) // discriminator for i in 0 ..< _value.count { hasher.combine(self[i]) } } func _rawHashValue(_seed: Int) -> Int { var hasher = Hasher(_seed: _seed) self._hash(into: &hasher) return hasher._finalize() } internal func _unbox<T : Hashable>() -> T? { return _value as? T } internal func _downCastConditional<T>( into result: UnsafeMutablePointer<T> ) -> Bool { guard let value = _value as? T else { return false } result.initialize(to: value) return true } }
apache-2.0
f2c4c3f0ea60a5a210c39beea28ddf89
37.716458
101
0.659736
4.324798
false
false
false
false
hectr/swift-idioms
Tests/IdiomsTests/RandomAccessMutableCollectionTests.swift
1
1761
// Copyright (c) 2019 Hèctor Marquès Ranea // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import Idioms class RandomAccessMutableCollectionTests: XCTestCase { func testSubscriptGetter() { let array = [false, true, false] let element = array[(current: 1, previous: nil, next: nil)] let expected = true XCTAssertEqual(element, expected) } func testSubscriptSetter() { var array = [false, false, false] array[(current: 2, previous: nil, next: nil)] = true XCTAssertTrue(array[2]) } static var allTests = [ ("testSubscriptGetter", testSubscriptGetter), ("testSubscriptSetter", testSubscriptSetter), ] }
mit
d38a7e4c7c84129b526e5921b8b3cfa6
39.906977
80
0.722001
4.54522
false
true
false
false
wilfreddekok/Antidote
Antidote/ProfileSettings.swift
1
1603
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import Foundation private struct Constants { static let UnlockPinCodeKey = "UnlockPinCodeKey" static let UseTouchIDKey = "UseTouchIDKey" static let LockTimeoutKey = "LockTimeoutKey" } class ProfileSettings: NSObject, NSCoding { enum LockTimeout: String { case Immediately case Seconds30 case Minute1 case Minute2 case Minute5 } var unlockPinCode: String? var useTouchID: Bool var lockTimeout: LockTimeout required override init() { unlockPinCode = nil useTouchID = false lockTimeout = .Immediately super.init() } required init(coder aDecoder: NSCoder) { unlockPinCode = aDecoder.decodeObjectForKey(Constants.UnlockPinCodeKey) as? String useTouchID = aDecoder.decodeBoolForKey(Constants.UseTouchIDKey) if let rawTimeout = aDecoder.decodeObjectForKey(Constants.LockTimeoutKey) as? String { lockTimeout = LockTimeout(rawValue: rawTimeout) ?? .Immediately } else { lockTimeout = .Immediately } super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(unlockPinCode, forKey: Constants.UnlockPinCodeKey) aCoder.encodeBool(useTouchID, forKey: Constants.UseTouchIDKey) aCoder.encodeObject(lockTimeout.rawValue, forKey: Constants.LockTimeoutKey) } }
mpl-2.0
00bae084e30db6e9a884dd8ab3dacc5c
29.245283
94
0.681223
4.566952
false
false
false
false
ruanjunhao/RJWeiBo
RJWeiBo/Pods/SwiftyJSON/Source/SwiftyJSON.swift
1
44897
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreFoundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 public enum SwiftyJSONError: Error { case empty case errorInvalidJSON(String) } // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The Data used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch { // For now do nothing with the error self.init(NSNull() as Any) } } /** Create a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(string:String) -> JSON { return string.data(using: String.Encoding.utf8).flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: Any) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object } as Any) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary as Any) } /// Private object var rawString: String = "" var rawNumber: NSNumber = 0 var rawNull: NSNull = NSNull() var rawArray: [Any] = [] var rawDictionary: [String : Any] = [:] var rawBool: Bool = false /// Private type var _type: Type = .null /// prviate error var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil #if os(Linux) let (type, value) = self.setObjectHelper(newValue) _type = type switch (type) { case .array: self.rawArray = value as! [Any] case .bool: self.rawBool = value as! Bool if let number = newValue as? NSNumber { self.rawNumber = number } else { self.rawNumber = self.rawBool ? NSNumber(value: 1) : NSNumber(value: 0) } case .dictionary: self.rawDictionary = value as! [String:Any] case .null: break case .number: self.rawNumber = value as! NSNumber case .string: self.rawString = value as! String case .unknown: _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) print("==> error=\(_error). type=\(type(of: newValue))") } #else if type(of: newValue) == Bool.self { _type = .bool self.rawBool = newValue as! Bool } else { switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey as NSObject: "It is a unsupported type"]) } } #endif } } #if os(Linux) private func setObjectHelper(_ newValue: Any) -> (Type, Any) { var type: Type var value: Any if let bool = newValue as? Bool { type = .bool value = bool } else if let number = newValue as? NSNumber { if number.isBool { type = .bool value = number.boolValue } else { type = .number value = number } } else if let number = newValue as? Double { type = .number value = NSNumber(value: number) } else if let number = newValue as? Int { type = .number value = NSNumber(value: number) } else if let string = newValue as? String { type = .string value = string } else if let string = newValue as? NSString { type = .string value = string._bridgeToSwift() } else if newValue is NSNull { type = .null value = "" } else if let array = newValue as? NSArray { type = .array value = array._bridgeToSwift() } else if let array = newValue as? Array<Any> { type = .array value = array } else if let dictionary = newValue as? NSDictionary { type = .dictionary value = dictionary._bridgeToSwift() } else if let dictionary = newValue as? Dictionary<String, Any> { type = .dictionary value = dictionary } else { type = .unknown value = "" } return (type, value) } #endif /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull() as Any) } } #if os(Linux) internal static func stringFromNumber(_ number: NSNumber) -> String { let type = CFNumberGetType(unsafeBitCast(number, to: CFNumber.self)) switch(type) { case kCFNumberFloat32Type: return String(number.floatValue) case kCFNumberFloat64Type: return String(number.doubleValue) default: return String(number.int64Value) } } #endif } // MARK: - CollectionType, SequenceType extension JSON : Collection, Sequence { public typealias Generator = JSONGenerator public typealias Index = JSONIndex public var startIndex: JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.startIndex) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) default: return JSONIndex() } } public var endIndex: JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.endIndex) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) default: return JSONIndex() } } public func index(after i: JSON.Index) -> JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.index(after: i.arrayIndex!)) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.index(after: i.dictionaryIndex!)) default: return JSONIndex() } } public subscript (position: JSON.Index) -> Generator.Element { switch self.type { case .array: return (String(describing: position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) case .dictionary: let (key, value) = self.rawDictionary[position.dictionaryIndex!] return (key, JSON(value)) default: return ("", JSON.null) } } /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`. public var isEmpty: Bool { get { switch self.type { case .array: return self.rawArray.isEmpty case .dictionary: return self.rawDictionary.isEmpty default: return true } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { switch self.type { case .array: return self.rawArray.count case .dictionary: return self.rawDictionary.count default: return 0 } } public func underestimateCount() -> Int { switch self.type { case .array: return self.rawArray.underestimatedCount case .dictionary: return self.rawDictionary.underestimatedCount default: return 0 } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of JSON. */ public func generate() -> Generator { return JSON.Generator(self) } } public struct JSONIndex: _Incrementable, Equatable, Comparable { let arrayIndex: Array<Any>.Index? let dictionaryIndex: DictionaryIndex<String, Any>? let type: Type init(){ self.arrayIndex = nil self.dictionaryIndex = nil self.type = .unknown } init(arrayIndex: Array<Any>.Index) { self.arrayIndex = arrayIndex self.dictionaryIndex = nil self.type = .array } init(dictionaryIndex: DictionaryIndex<String, Any>) { self.arrayIndex = nil self.dictionaryIndex = dictionaryIndex self.type = .dictionary } } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): return lhs.arrayIndex == rhs.arrayIndex case (.dictionary, .dictionary): return lhs.dictionaryIndex == rhs.dictionaryIndex default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public struct JSONGenerator : IteratorProtocol { public typealias Element = (String, JSON) private let type: Type private var dictionayGenerate: DictionaryIterator<String, Any>? private var arrayGenerate: IndexingIterator<[Any]>? private var arrayIndex: Int = 0 init(_ json: JSON) { self.type = json.type if type == .array { self.arrayGenerate = json.rawArray.makeIterator() }else { self.dictionayGenerate = json.rawDictionary.makeIterator() } } public mutating func next() -> JSONGenerator.Element? { switch self.type { case .array: if let o = self.arrayGenerate?.next() { let i = self.arrayIndex self.arrayIndex += 1 return (String(i), JSON(o)) } else { return nil } case .dictionary: guard let (k, v): (String, Any) = self.dictionayGenerate?.next() else { return nil } return (k, JSON(v)) default: return nil } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array" as Any]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null #if os(Linux) r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds" as Any]) #else r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey as AnyObject as! NSObject: "Array[\(index)] is out of bounds" as AnyObject]) #endif return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { #if os(Linux) r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist" as Any]) #else r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey as NSObject: "Dictionary[\"\(key)\"] does not exist" as AnyObject]) #endif } } else { #if os(Linux) r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary" as Any]) #else r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey as NSObject: "Dictionary[\"\(key)\"] failure, It is not an dictionary" as AnyObject]) #endif } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: self.object = newValue.object case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, Any)...) { self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in var d = dictionary d[element.0] = element.1 return d } as Any) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } #if os(Linux) public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard LclJSONSerialization.isValidJSONObject(self.object) else { throw SwiftyJSONError.errorInvalidJSON("JSON is invalid") } return try LclJSONSerialization.data(withJSONObject: self.object, options: opt) } #else public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw SwiftyJSONError.errorInvalidJSON("JSON is invalid") } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } #endif #if os(Linux) public func rawString(encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: do { let data = try self.rawData(options: opt) return String(data: data, encoding: encoding) } catch _ { return nil } case .string: return self.rawString case .number: return JSON.stringFromNumber(self.rawNumber) case .bool: return self.rawBool.description case .null: return "null" default: return nil } } #else public func rawString(encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: do { let data = try self.rawData(options: opt) return String(data: data, encoding: encoding) } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } #endif } // MARK: - Printable, DebugPrintable extension JSON { public var description: String { let prettyString = self.rawString(options:.prettyPrinted) if let string = prettyString { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyType] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, Any)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d } } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : AnyType] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return self.rawString.caseInsensitiveCompare("true") == .orderedSame default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { #if os(Linux) switch self.type { case .string: return self.object as? String ?? "" case .number: return JSON.stringFromNumber(self.object as! NSNumber) case .bool: return String(self.object as! Bool) default: return "" } #else switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } #endif } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: #if os(Linux) if let decimal = Double(self.object as! String) { return NSNumber(value: decimal) } else { // indicates parse error return NSNumber(value: 0.0) } #else let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal #endif case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist{ return false } return true } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .string: guard let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil } return NSURL(string: encodedString_) default: return nil } } set { #if os(Linux) self.object = newValue?.absoluteString._bridgeToObjectiveC() as Any #else self.object = newValue?.absoluteString as Any #endif } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: newValue) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(describing: trueNumber.objCType) private let falseObjCType = String(describing: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { #if os(Linux) let type = CFNumberGetType(unsafeBitCast(self, to: CFNumber.self)) if type == kCFNumberSInt8Type && (self.compare(trueNumber) == ComparisonResult.orderedSame || self.compare(falseNumber) == ComparisonResult.orderedSame){ return true } else { return false } #else let objCType = String(describing: self.objCType) if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ return true } else { return false } #endif } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != ComparisonResult.orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != ComparisonResult.orderedAscending } }
apache-2.0
9493f6424143946ae5885608ec5f80fe
26.748455
264
0.546852
4.680183
false
false
false
false
crossroadlabs/Twist
Sources/Twist/UIView.swift
1
2261
//===--- UIView.swift ----------------------------------------------===// //Copyright (c) 2016 Crossroad Labs s.r.o. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import UIKit import Boilerplate import ExecutionContext import Future extension UIView : ExecutionContextTenantProtocol { public var context: ExecutionContextProtocol { get { return ExecutionContext.main } } } public extension UIView { public class func animate(duration: Timeout, animation: @escaping () -> Void) -> Future<Bool> { let promise = Promise<Bool>() self.animate(withDuration: duration.timeInterval, animations: animation) { finished in try! promise.success(value: finished) } return promise.future } public class func animate(duration: Timeout, delay: Timeout, options: UIViewAnimationOptions = [], animation: @escaping () -> Void) -> Future<Bool> { let promise = Promise<Bool>() self.animate(withDuration: duration.timeInterval, delay: delay.timeInterval, options: options, animations: animation) { finished in try! promise.success(value: finished) } return promise.future } } public extension PropertyDescriptor where Component : UIView { public static var hidden:MutablePropertyDescriptor<Component, MutableObservable<Bool>> { get { return NSPropertyDescriptor(name: #keyPath(UIView.hidden)) } } public static var alpha:MutablePropertyDescriptor<Component, MutableObservable<CGFloat>> { get { return NSPropertyDescriptor(name: #keyPath(UIView.alpha)) } } }
apache-2.0
4eebc42bc2724bc16b00983c0b6d0fa8
35.467742
153
0.653251
4.925926
false
false
false
false
thatseeyou/SpriteKitExamples.playground
Pages/SKShapeNode.xcplaygroundpage/Contents.swift
1
5855
/*: ### UIBezierPath를 이용해서 SKShapeNode를 만들 수 있다. */ import UIKit import SpriteKit class GameScene: SKScene { var contentCreated = false override func didMove(to view: SKView) { if self.contentCreated != true { let shape = SKShapeNode(path: makeBezierPath().cgPath) shape.strokeColor = SKColor.green shape.fillColor = SKColor.red shape.position = CGPoint(x: self.frame.midX, y: self.frame.midY) addChild(shape) self.contentCreated = true } } func makeBezierPath() -> UIBezierPath { //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 26.5, y: 3.5)) bezierPath.addCurve(to: CGPoint(x: 45.5, y: 21.5), controlPoint1: CGPoint(x: 18.21, y: -1.33), controlPoint2: CGPoint(x: 58.09, y: 18.38)) bezierPath.addCurve(to: CGPoint(x: -18.5, y: 39.5), controlPoint1: CGPoint(x: 39.21, y: 23.06), controlPoint2: CGPoint(x: -14.26, y: 38.35)) bezierPath.addCurve(to: CGPoint(x: -18.5, y: 21.5), controlPoint1: CGPoint(x: -37.39, y: 44.62), controlPoint2: CGPoint(x: 5.5, y: 27.5)) bezierPath.addLine(to: CGPoint(x: -50.05, y: 10.11)) bezierPath.addCurve(to: CGPoint(x: -27.34, y: -25.5), controlPoint1: CGPoint(x: -48.7, y: -15.86), controlPoint2: CGPoint(x: -45.79, y: -20.5)) bezierPath.addCurve(to: CGPoint(x: 5.02, y: -33.21), controlPoint1: CGPoint(x: -23.12, y: -26.64), controlPoint2: CGPoint(x: -1.28, y: -31.65)) bezierPath.addCurve(to: CGPoint(x: 50.98, y: -12.45), controlPoint1: CGPoint(x: 27.89, y: -38.88), controlPoint2: CGPoint(x: 42.61, y: -30.3)) bezierPath.addCurve(to: CGPoint(x: 56, y: 3.07), controlPoint1: CGPoint(x: 53.3, y: -7.52), controlPoint2: CGPoint(x: 54.93, y: -2.22)) bezierPath.addCurve(to: CGPoint(x: 56.85, y: 8.19), controlPoint1: CGPoint(x: 56.38, y: 4.92), controlPoint2: CGPoint(x: 56.66, y: 6.64)) bezierPath.addCurve(to: CGPoint(x: 57.01, y: 9.62), controlPoint1: CGPoint(x: 56.92, y: 8.73), controlPoint2: CGPoint(x: 56.97, y: 9.2)) bezierPath.addCurve(to: CGPoint(x: 57.05, y: 10.11), controlPoint1: CGPoint(x: 57.03, y: 9.86), controlPoint2: CGPoint(x: 57.05, y: 10.03)) bezierPath.addCurve(to: CGPoint(x: 57, y: 10.41), controlPoint1: CGPoint(x: 57.05, y: 10.1), controlPoint2: CGPoint(x: 57.03, y: 10.22)) bezierPath.addCurve(to: CGPoint(x: 56.77, y: 11.49), controlPoint1: CGPoint(x: 56.95, y: 10.72), controlPoint2: CGPoint(x: 56.88, y: 11.08)) bezierPath.addCurve(to: CGPoint(x: 55.28, y: 15.41), controlPoint1: CGPoint(x: 56.47, y: 12.67), controlPoint2: CGPoint(x: 55.99, y: 13.99)) bezierPath.addCurve(to: CGPoint(x: -35.5, y: -17.5), controlPoint1: CGPoint(x: 53.26, y: 19.49), controlPoint2: CGPoint(x: -30.41, y: -21.33)) bezierPath.addCurve(to: CGPoint(x: 4.83, y: 42.2), controlPoint1: CGPoint(x: -44.38, y: -10.82), controlPoint2: CGPoint(x: 22.82, y: 39.23)) bezierPath.addCurve(to: CGPoint(x: 26.5, y: -17.5), controlPoint1: CGPoint(x: -13.55, y: 45.23), controlPoint2: CGPoint(x: 35.15, y: -12.72)) bezierPath.addCurve(to: CGPoint(x: -48.22, y: 21.17), controlPoint1: CGPoint(x: 19.52, y: -21.36), controlPoint2: CGPoint(x: -46.12, y: 29.43)) bezierPath.addCurve(to: CGPoint(x: -50.06, y: 10.03), controlPoint1: CGPoint(x: -49.02, y: 18), controlPoint2: CGPoint(x: -49.4, y: 15.52)) bezierPath.addLine(to: CGPoint(x: -51, y: 10.14)) bezierPath.addCurve(to: CGPoint(x: -49.14, y: 21.39), controlPoint1: CGPoint(x: -50.33, y: 15.67), controlPoint2: CGPoint(x: -49.95, y: 18.17)) bezierPath.addCurve(to: CGPoint(x: -35.67, y: 40.07), controlPoint1: CGPoint(x: -46.99, y: 29.88), controlPoint2: CGPoint(x: -42.91, y: 36.07)) bezierPath.addCurve(to: CGPoint(x: 4.98, y: 43.12), controlPoint1: CGPoint(x: -26.81, y: 44.97), controlPoint2: CGPoint(x: -13.58, y: 46.18)) bezierPath.addCurve(to: CGPoint(x: 45.35, y: 28.15), controlPoint1: CGPoint(x: 23.12, y: 40.12), controlPoint2: CGPoint(x: 36.34, y: 34.93)) bezierPath.addCurve(to: CGPoint(x: 56.13, y: 15.82), controlPoint1: CGPoint(x: 50.56, y: 24.23), controlPoint2: CGPoint(x: 54.04, y: 20.03)) bezierPath.addCurve(to: CGPoint(x: 57.69, y: 11.72), controlPoint1: CGPoint(x: 56.87, y: 14.34), controlPoint2: CGPoint(x: 57.37, y: 12.96)) bezierPath.addCurve(to: CGPoint(x: 57.94, y: 10.55), controlPoint1: CGPoint(x: 57.8, y: 11.28), controlPoint2: CGPoint(x: 57.89, y: 10.89)) bezierPath.addCurve(to: CGPoint(x: 58, y: 10.12), controlPoint1: CGPoint(x: 57.97, y: 10.35), controlPoint2: CGPoint(x: 57.99, y: 10.2)) bezierPath.addCurve(to: CGPoint(x: 57.95, y: 9.53), controlPoint1: CGPoint(x: 57.99, y: 9.96), controlPoint2: CGPoint(x: 57.98, y: 9.78)) bezierPath.addCurve(to: CGPoint(x: 57.79, y: 8.07), controlPoint1: CGPoint(x: 57.91, y: 9.11), controlPoint2: CGPoint(x: 57.86, y: 8.62)) bezierPath.addCurve(to: CGPoint(x: 56.93, y: 2.89), controlPoint1: CGPoint(x: 57.59, y: 6.51), controlPoint2: CGPoint(x: 57.31, y: 4.76)) return bezierPath } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsPhysics = true //skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
isc
0087ae428bdc7e49fc1efb1e96317ff5
66.045977
151
0.62815
2.94596
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Charts/CombinedChartView.swift
6
6981
// // CombinedChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. public class CombinedChartView: BarLineChartViewBase, LineChartDataProvider, BarChartDataProvider, ScatterChartDataProvider, CandleChartDataProvider, BubbleChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: ChartFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc public enum CombinedChartDrawOrder: Int { case Bar case Bubble case Line case Candle case Scatter } public override func initialize() { super.initialize() self.highlighter = CombinedHighlighter(chart: self) /// WORKAROUND: Swift 2.0 compiler malfunctions when optimizations are enabled, and assigning directly to _fillFormatter causes a crash with a EXC_BAD_ACCESS. See https://github.com/danielgindi/ios-charts/issues/406 let workaroundFormatter = ChartDefaultFillFormatter() _fillFormatter = workaroundFormatter renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } override func calcMinMax() { super.calcMinMax() guard let data = _data else { return } if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil) { _xAxis._axisMinimum = -0.5 _xAxis._axisMaximum = Double(data.xVals.count) - 0.5 if (self.bubbleData !== nil) { for set in self.bubbleData?.dataSets as! [IBubbleChartDataSet] { let xmin = set.xMin let xmax = set.xMax if (xmin < chartXMin) { _xAxis._axisMinimum = xmin } if (xmax > chartXMax) { _xAxis._axisMaximum = xmax } } } } _xAxis.axisRange = abs(_xAxis._axisMaximum - _xAxis._axisMinimum) if _xAxis.axisRange == 0.0 && self.lineData?.yValCount > 0 { _xAxis.axisRange = 1.0 } } public override var data: ChartData? { get { return super.data } set { super.data = newValue (renderer as! CombinedChartRenderer?)!.createRenderers() } } public var fillFormatter: ChartFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if (_fillFormatter == nil) { _fillFormatter = ChartDefaultFillFormatter() } } } // MARK: - LineChartDataProvider public var lineData: LineChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).lineData } } // MARK: - BarChartDataProvider public var barData: BarChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).barData } } // MARK: - ScatterChartDataProvider public var scatterData: ScatterChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).scatterData } } // MARK: - CandleChartDataProvider public var candleData: CandleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).candleData } } // MARK: - BubbleChartDataProvider public var bubbleData: BubbleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).bubbleData } } // MARK: - Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled } set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue } } /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! } } } }
apache-2.0
6e17789994c9ab1dc10bc9b84209421e
29.356522
223
0.569116
5.453906
false
false
false
false
meteochu/Treble
Treble/MediaPlayer.swift
1
2348
// Copyright © 2020 Andy Liang. All rights reserved. import UIKit struct TrackInfo { var title: String var album: String? = nil var artist: String? = nil var trackNumber: Int = 0 var fileType: String = "Audio File" var subtitleText: String { let subtitle = [album, artist].compactMap { $0 }.joined(separator: " - ") return !subtitle.isEmpty ? subtitle : fileType } static func parsedTrackInfo(from url: URL) -> TrackInfo { let pathExtension = url.pathExtension let fileName = url.deletingPathExtension().lastPathComponent let components = fileName.components(separatedBy: "-") let fileType = "\(pathExtension.uppercased()) File" switch components.count { case 2: if let number = Int(components[0]) { // first element is a track number return TrackInfo(title: components[1], trackNumber: number, fileType: fileType) } else { return TrackInfo(title: components[1], artist: components[0], fileType: fileType) } case 3: if let number = Int(components[0]) { // first element is a track number return TrackInfo( title: components[2], artist: components[1], trackNumber: number, fileType: fileType ) } else { return TrackInfo(title: components[1], artist: components[0], fileType: fileType) } default: return TrackInfo(title: fileName, fileType: fileType) } } } extension TrackInfo { static let defaultItem = TrackInfo( title: "Welcome to Treble", album: "Choose from your Apple Music Library, or select an audio file from your iCloud Drive.") } protocol MediaPlayerDelegate : class { func updatePlaybackProgress(elapsedTime: TimeInterval) func updatePlaybackState(isPlaying: Bool, progress: NowPlayingProgress) func updateTrackInfo(with trackInfo: TrackInfo, artwork: UIImage) } protocol MediaPlayer { var delegate: MediaPlayerDelegate? { get set } var playbackRate: PlaybackRate { get set } func togglePlayback() func play() func pause() func previousTrack() func nextTrack() func seek(to time: TimeInterval, completion: ActionHandler?) }
mit
a9462f1ab8e85f5b37651eba5a052a80
34.029851
104
0.62974
4.770325
false
false
false
false
AceWangLei/BYWeiBo
BYWeiBo/BYVisitorTableViewController.swift
1
1447
// // BYVisitorTableViewController.swift // BYWeiBo // // Created by qingyun on 16/1/26. // Copyright © 2016年 lit. All rights reserved. // import UIKit class BYVisitorTableViewController: UITableViewController { /** Bool 用户是否登陆的开关 */ var userLogin: Bool = BYUserAccountViewModel.sharedViewModel.isLogon var visitorView: BYVisitorView? override func loadView() { // 用户已登录 userLogin ? super.loadView() : setupVisitorView() } private func setupVisitorView() { let v = BYVisitorView() visitorView = v view = v // 设置左右的 item navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: "register") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", target: self, action: "login") // 设置访客视图里面的两个按钮点击事件 v.registerButton.addTarget(self, action: "register", forControlEvents: UIControlEvents.TouchUpInside) v.loginButton.addTarget(self, action: "login", forControlEvents: UIControlEvents.TouchUpInside) } @objc private func register() { print("注册") } @objc private func login() { print("登录") presentViewController(BYNavigationController(rootViewController:BYOAuthViewController()), animated: true, completion: nil) } }
apache-2.0
b96f05668b7d4b86a514a29f74b80990
29.133333
130
0.659292
4.808511
false
false
false
false
libzhu/LearnSwift
基础部分/基础部分.playground/Contents.swift
1
9829
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var a = 1 a = 2; let b = 2 let c = 3.14 var d = 0.618 var welcome : String = "hello world" var red, green, blue: Double red = 2.0 green = 2.11 blue = 14 //类型标注(给常量添加类型标注String) let welcomestr : String welcomestr = "hello baby" /*————————————————————————————常量和变量的命名——————————————————*/ let π = 3.14159 let 你好 = "你好世界" let 🐶 = "🐶" print(🐶) print(你好) print(π) /*————————————————————————————整数范围————————————————————————*/ let minValue = UInt8.min let maxValue = UInt8.max print("最大值",maxValue, "最小值", minValue) //浮点数 //Double :表示64位浮点数。当你需要存储很大或者精度很高的浮点数时请用此类型 //float: 表示32位浮点数。精度要求不高的话可以使用此类型 //数值类字面量可以包括额外的格式来增强可读性。整数和浮点数都可以添加额外的零并且包含下划线,并不会影响字面量: let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1 let three = 3 let pointOneFourOneFiveNine : Float = 0.14159 let pi = Float(3) + pointOneFourOneFiveNine //布尔值 //Swift 有一个基本的布尔(Boolean)类型,叫做Bool。布尔值指逻辑上的值,因为它们只能是真或者假。swift的bool值只有ture 和 false: let trueBoolValue = true let falseBoolValue = false print(trueBoolValue, falseBoolValue) if trueBoolValue { print("正确") }else{ print("错误") } //如果你在需要使用 Bool 类型的地方使用了非布尔值,Swift 的类型安全机制会报错。下面的例子会报告一个编译时错误: let i = 1 // //if i { // // print("此处会报错,不能通过编译") //} if i == 1 { print("正确,通过编译") } //元祖 /*元祖(tuples):把多个值组合成一个复合值。元祖内的值可以是不同类型的值*/ let http404Error = (404, "notFound") //(404, "Not Found") 元组把一个 Int 值和一个 String 值组合起来表示 HTTP 状态码的两个部分:一个数字和一个人类可读的描述。这个元组可以被描述为“一个类型为 (Int, String) 的元组”。 //你可以把任意顺序的类型组合成一个元组,这个元组可以包含所有类型。只要你想,你可以创建一个类型为 (Int, Int, Int) 或者 (String, Bool) 或者其他任何你想要的组合的元组。 //1.元祖的分解. 你可以将一个元组的内容分解(decompose)成单独的常量和变量,然后你就可以正常使用它们了 let (stautCode, statusMessage) = http404Error print("错误码: \(stautCode)") print("错误信息:\(statusMessage)") //2.如果只需要元祖的一部分, 分解的时候可以用(_)忽略不需要的部分 let (_, wantStatusMessage) = http404Error print("错误信息:\(wantStatusMessage)") //3.通过下标来访问元祖信息 let oneStatusCode = http404Error.0 let twoStatusMessage = http404Error.1 //创建元祖的时候可以给元祖中的单个元素命名 let http200Status = (code:200, msg:"返回成功!") print(http200Status) print(http200Status.code, http200Status.msg) //可选类型:使用可选值类型(optionals)来处理可能缺失的情况。可选类型表示:·有值,等于x 或者 · 没有值 let possibleNumber = "123" let convertedNumer = Int(possibleNumber)//let convertedNumer: Int?//返回的是一个可选值类型的Int?而不是Int (问号包含的值是可选类型,也就是说可能包含Int值, 也可能不包含值。不能包含其他任何值比如 Bool 值或者 String 值。只能是 Int 或者什么都没有。) //nil 可以给可变变量赋值为nil 来表示它没有值: var serverResponseCode : Int? = 404;// serverResponseCode 包含一个可选的 Int 值 404 serverResponseCode = nil // serverResponseCode 现在不包含值 //var testValue : Int = 404 // //testValue = nil //注意:nil不能用于非可选的常量和变量。如果你的代码中有常量或者变量需要处理值缺失的情况,请把它们声明成对应的可选类型。 //Swift 的 nil 和 Objective-C 中的 nil 并不一样。在 Objective-C 中,nil 是一个指向不存在对象的指针。在 Swift 中,nil 不是指针——它是一个确定的值,用来表示值缺失。任何类型的可选状态都可以被设置为 nil,不只是对象类型。 var surveyAnswer : String? let otherAnswer : String? var surveyohterAnswer : String? otherAnswer = "hello world" surveyAnswer = "a" surveyAnswer = "b" //if 语句以及强制解析 if convertedNumer != nil { print("convertedNumer contains some integer value \(convertedNumer)") } //当你确定这个可选类型确实包含值之后,你可以在可选测名字后面加一个感叹号( !)来获取这个值。这个感叹号表示“我知道这个可选值有值,请使用它。”这被称为可选值的强制解析 if convertedNumer != nil { print("这个可选值的值:\(convertedNumer!)") } //注意:使用 ! 来获取一个不存在的可选值会导致运行时错误。使用 ! 来强制解析值之前,一定要确定可选包含一个非 nil 的值。 //if serverResponseCode == nil { // print("serverResponseCode 的值:\(serverResponseCode!)") //} //可选绑定 //使用可选绑定(optional binding) 来判断可选类型是否包含值, 入股包含就把值赋给一个临时常量或变量。可选绑定可以用在if 和 while 的语句中 这条语句不仅可以用来判断可选类型中是否有值,同时可以将可选类型中的值赋给一个常量或变量。if 和 while 语句 if let actualNumber = Int(possibleNumber){//这段代码可以被理解为:“如果 Int(possibleNumber) 返回的可选 Int 包含一个值,创建一个叫做 actualNumber 的新常量并将可选包含的值赋给它。”如果转换成功,actualNumber 常量可以在 if 语句的第一个分支中使用。它已经被可选类型 包含的 值初始化过,所以不需要再使用 ! 后缀来获取它的值。在这个例子中,actualNumber 只被用来输出转换结果你可以在可选绑定中使用常量和变量。如果你想在if语句的第一个分支中操作 actualNumber 的值,你可以改成 if var actualNumber,这样可选类型包含的值就会被赋给一个变量而非常量。 print("\'\(possibleNumber)\' 中有一个integer 的值是\(actualNumber)") }else{ print("\'\(possibleNumber)\' 中没有一个integer的值"); } /*隐式解析可选类型 如上所述,可选类型暗示了常量或者变量可以“没有值”。可选可以通过 if 语句来判断是否有值,如果有值的话可以通过可选绑定来解析值。 有时候在程序架构中,第一次被赋值之后,可以确定一个可选类型总会有值。在这种情况下,每次都要判断和解析可选值是非常低效的,因为可以确定它总会有值。 这种类型的可选状态被定义为隐式解析可选类型(implicitly unwrapped optionals)。把想要用作可选的类型的后面的问号(String?)改成感叹号(String!)来声明一个隐式解析可选类型。 当可选类型被第一次赋值之后就可以确定之后一直有值的时候,隐式解析可选类型非常有用。隐式解析可选类型主要被用在 Swift 中类的构造过程中 */ //一个隐式解析可选类型其实就是一个普通的可选类型,但是可以被当做非可选类型来使用,并不需要每次都使用解析来获取可选值。下面的例子展示了可选类型 String 和隐式解析可选类型 String 之间的区别: let possibleString : String? = "hello world"//正常的可选类型 let possibleStringValueStr = possibleString! //非隐式可选类型需要感叹号 来取值 let otherPossibleString : String! = "hello beijin" //隐式解析可选类型 let otherPossibleStringValueStr = otherPossibleString //隐式可选类型 可直接赋值 不用感叹号 /*---------------------正常的可选类型赋值及可选绑定--------------------------------*/ if possibleString != nil { print("\(possibleString!)") } if let optionStr = possibleString { print(optionStr) }else{ print("possibleString 中没有 String 值") } /*-----------------隐式解析可选类型赋值及可选绑定------------*/ if otherPossibleString != nil { print(otherPossibleString) } if let getStr = otherPossibleString { print(getStr) } //注意:如果一个变量之后可能变成nil的话请不要使用隐式解析可选类型。如果你需要在变量的生命周期中判断是否是nil的话,请使用普通可选类型。 /* 使用断言进行调试 断言会在运行时判断一个逻辑条件是否为 true。从字面意思来说,断言“断言”一个条件是否为真。你可以使用断言来保证在运行其他代码之前,某些重要的条件已经被满足。如果条件判断为 true,代码运行会继续进行;如果条件判断为 false,代码执行结束,你的应用被终止。 */ let age = -5 assert(age >= 0, "年龄不能小于0") // 因为 age < 0,所以断言会触发 //在这个例子中,只有 age >= 0 为 true 的时候,即 age 的值非负的时候,代码才会继续执行。如果 age 的值是负数,就像代码中那样,age >= 0 为 false,断言被触发,终止应用。
mit
4966a9fa9b9f0d3691b4de9801263bfc
23.889868
344
0.727611
2.613321
false
false
false
false
cloudant/swift-cloudant
Source/SwiftCloudant/Operations/Query/FindDocumentsOperation.swift
1
9260
// // FindDocumentsOperation.swift // SwiftCloudant // // Created by Rhys Short on 20/04/2016. // Copyright © 2016, 2019 IBM Corp. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // import Foundation /** Specfies how a field should be sorted */ public struct Sort { /** The direction of Sorting */ public enum Direction: String { /** Sort ascending */ case asc = "asc" /** Sort descending */ case desc = "desc" } /** The field on which to sort */ public let field: String /** The direction in which to sort. */ public let sort: Direction? public init(field: String, sort: Direction?) { self.field = field self.sort = sort } } /** Protocol for operations which deal with the Mango API set for CouchDB / Cloudant. */ internal protocol MangoOperation { } internal extension MangoOperation { /** Transform an Array of Sort into a Array in the form of Sort Syntax. */ func transform(sortArray: [Sort]) -> [Any] { var transformed: [Any] = [] for s in sortArray { if let sort = s.sort { let dict = [s.field: sort.rawValue] transformed.append(dict) } else { transformed.append(s.field) } } return transformed } /** Transform an array of TextIndexField into an Array in the form of Lucene field definitions. */ func transform(fields: [TextIndexField]) -> [[String:String]] { var array: [[String:String]] = [] for field in fields { array.append([field.name: field.type.rawValue]) } return array } } /** Usage example: ``` let find = FindDocumentsOperation(selector:["foo":"bar"], databaseName: "exampledb", fields: ["foo"], sort: [Sort(field: "foo", sort: .Desc)], documentFoundHandler: { (document) in // Do something with the document. }) {(response, httpInfo, error) in if let error = error { // handle the error. } else { // do something on success. } } client.add(operation:find) ``` */ public class FindDocumentsOperation: CouchDatabaseOperation, MangoOperation, JSONOperation { /** Creates the operation. - parameter selector: the selector to use to select documents in the database. - parameter databaseName: the name of the database the find operation should be performed on. - parameter fields: the fields of a matching document which should be returned in the repsonse. - parameter limit: the maximium number of documents to be returned. - parameter skip: the number of matching documents to skip before returning matching documents. - parameter sort: how to sort the match documents - parameter bookmark: A bookmark from a previous index query, this is only valid for text indexes. - parameter useIndex: Which index to use when matching documents - parameter r: The read quorum for this request. - parameter documentFoundHandler: a handler to call for each document in the response. - parameter completionHandler: optional handler to call when the operations completes. - warning: `r` is an advanced option and is rarely, if ever, needed. It **will** be detrimental to performance. - remark: The `bookmark` option is only valid for text indexes, a `bookmark` is returned from the server and can be accessed in the completionHandler with the following line: ```` let bookmark = response["bookmark"] ```` - seealso: [Query sort syntax](https://docs.cloudant.com/cloudant_query.html#sort-syntax) - seealso: [Selector syntax](https://docs.cloudant.com/cloudant_query.html#selector-syntax) */ public init(selector: [String: Any], databaseName: String, fields: [String]? = nil, limit: UInt? = nil, skip: UInt? = nil, sort: [Sort]? = nil, bookmark: String? = nil, useIndex:String? = nil, r: UInt? = nil, documentFoundHandler: (([String: Any]) -> Void)? = nil, completionHandler: (([String : Any]?, HTTPInfo?, Error?) -> Void)? = nil) { self.selector = selector self.databaseName = databaseName self.fields = fields self.limit = limit self.skip = skip self.sort = sort self.bookmark = bookmark self.useIndex = useIndex; self.r = r self.documentFoundHandler = documentFoundHandler self.completionHandler = completionHandler } public let completionHandler: (([String : Any]?, HTTPInfo?, Error?) -> Void)? public let databaseName: String /** The selector for the query, as a dictionary representation. See [the Cloudant documentation](https://docs.cloudant.com/cloudant_query.html#selector-syntax) for syntax information. */ public let selector: [String: Any]?; /** The fields to include in the results. */ public let fields: [String]? /** The number maximium number of documents to return. */ public let limit: UInt? /** Skip the first _n_ results, where _n_ is specified by skip. */ public let skip: UInt? /** An array that indicates how to sort the results. */ public let sort: [Sort]? /** A string that enables you to specify which page of results you require. */ public let bookmark: String? /** A specific index to run the query against. */ public let useIndex: String? /** The read quorum for this request. */ public let r: UInt? /** Handler to run for each document retrived from the database matching the query. - parameter document: a document matching the query. */ public let documentFoundHandler: (([String: Any]) -> Void)? private var json: [String: Any]? public var method: String { return "POST" } public var endpoint: String { return "/\(self.databaseName)/_find" } private var jsonData: Data? public var data: Data? { return self.jsonData } public func validate() -> Bool { let jsonObj = createJsonDict() if JSONSerialization.isValidJSONObject(jsonObj) { self.json = jsonObj return true } else { return false; } } private func createJsonDict() -> [String: Any] { // build the body dict, we will store this to save compute cycles. var jsonObj: [String: Any] = [:] if let selector = self.selector { jsonObj["selector"] = selector } if let limit = self.limit { jsonObj["limit"] = limit } if let skip = self.skip { jsonObj["skip"] = skip } if let r = self.r { jsonObj["r"] = r } if let sort = self.sort { jsonObj["sort"] = transform(sortArray: sort) } if let fields = self.fields { jsonObj["fields"] = fields } if let bookmark = self.bookmark { jsonObj["bookmark"] = bookmark } if let useIndex = self.useIndex { jsonObj["use_index"] = useIndex } return jsonObj } internal class func transform(sortArray: [Sort]) -> [Any] { var transfomed: [Any] = [] for s in sortArray { if let sort = s.sort { let dict = [s.field: sort.rawValue] transfomed.append(dict) } else { transfomed.append(s.field) } } return transfomed } public func serialise() throws { if self.json == nil { self.json = createJsonDict() } if let json = self.json { self.jsonData = try JSONSerialization.data(withJSONObject: json) } } public func processResponse(json: Any) { if let json = json as? [String: Any], let docs = json["docs"] as? [[String: Any]] { // Array of [String:Any] for doc: [String: Any] in docs { self.documentFoundHandler?(doc) } } } public func callCompletionHandler(response: Any?, httpInfo: HTTPInfo?, error: Error?) { self.completionHandler?(response as? [String: Any], httpInfo, error) } }
apache-2.0
54c152448a30dddcfdc526673fef8c8c
27.40184
181
0.581812
4.51879
false
false
false
false
adelinofaria/Buildasaur
Buildasaur/LocalSource.swift
2
11165
// // LocalSource.swift // Buildasaur // // Created by Honza Dvorsky on 14/02/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils import XcodeServerSDK public class LocalSource : JSONSerializable { enum AllowedCheckoutTypes: String { case SSH = "SSH" // case HTTPS - not yet supported, right now only SSH is supported // (for bots reasons, will be built in when I have time) // case SVN - not yet supported yet } var url: NSURL { didSet { self.refreshMetadata() } } var preferredTemplateId: String? var githubToken: String? var privateSSHKeyUrl: NSURL? var publicSSHKeyUrl: NSURL? var sshPassphrase: String? var privateSSHKey: String? { return self.getContentsOfKeyAtUrl(self.privateSSHKeyUrl) } var publicSSHKey: String? { return self.getContentsOfKeyAtUrl(self.publicSSHKeyUrl) } var availabilityState: AvailabilityCheckState private(set) var workspaceMetadata: NSDictionary? let forkOriginURL: String? //convenience getters var projectName: String? { get { return self.pullValueForKey("IDESourceControlProjectName") }} var projectPath: String? { get { return self.pullValueForKey("IDESourceControlProjectPath") }} var projectWCCIdentifier: String? { get { return self.pullValueForKey("IDESourceControlProjectWCCIdentifier") }} var projectWCCName: String? { get { if let wccId = self.projectWCCIdentifier { if let wcConfigs = self.workspaceMetadata?["IDESourceControlProjectWCConfigurations"] as? [NSDictionary] { if let foundConfig = wcConfigs.filter({ if let loopWccId = $0.optionalStringForKey("IDESourceControlWCCIdentifierKey") { return loopWccId == wccId } return false }).first { //so much effort for this little key... return foundConfig.optionalStringForKey("IDESourceControlWCCName") } } } return nil } } var projectURL: NSURL? { get { if let urlString = self.pullValueForKey("IDESourceControlProjectURL") { //if we have a fork, chose its URL, otherwise fallback to the loaded URL from the Checkout file var finalUrlString = self.forkOriginURL ?? urlString let type = self.checkoutType! if type == .SSH { if !finalUrlString.hasPrefix("git@") { finalUrlString = "git@\(finalUrlString)" } } return NSURL(string: finalUrlString) } return nil } } var checkoutType: AllowedCheckoutTypes? { get { if let meta = self.workspaceMetadata, let type = LocalSource.parseCheckoutType(meta) { return type } return nil } } private func pullValueForKey(key: String) -> String? { return self.workspaceMetadata?.optionalStringForKey(key) } init?(url: NSURL) { self.forkOriginURL = nil self.url = url self.preferredTemplateId = nil self.githubToken = nil self.availabilityState = .Unchecked self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil let (parsed, error) = self.refreshMetadata() if !parsed { return nil } } private init?(original: LocalSource, forkOriginURL: String) { self.forkOriginURL = forkOriginURL self.url = original.url self.preferredTemplateId = original.preferredTemplateId self.githubToken = original.githubToken self.availabilityState = original.availabilityState self.publicSSHKeyUrl = original.publicSSHKeyUrl self.privateSSHKeyUrl = original.privateSSHKeyUrl self.sshPassphrase = original.sshPassphrase let (parsed, error) = self.refreshMetadata() if !parsed { return nil } } public func duplicateForForkAtOriginURL(forkURL: String) -> LocalSource? { return LocalSource(original: self, forkOriginURL: forkURL) } public class func attemptToParseFromUrl(url: NSURL) -> (Bool, NSDictionary?, NSError?) { let (meta, error) = LocalSource.loadWorkspaceMetadata(url) if let error = error { return (false, nil, error) } //validate allowed remote url if self.parseCheckoutType(meta!) == nil { //disallowed let allowedString = ", ".join([AllowedCheckoutTypes.SSH].map({ $0.rawValue })) let error = Error.withInfo("Disallowed checkout type, the project must be checked out over one of the supported schemes: \(allowedString)") return (false, nil, error) } return (true, meta, nil) } private class func parseCheckoutType(metadata: NSDictionary) -> AllowedCheckoutTypes? { if let urlString = metadata.optionalStringForKey("IDESourceControlProjectURL"), let url = NSURL(string: urlString), let scheme = url.scheme { switch scheme { case "github.com": return AllowedCheckoutTypes.SSH case "https": if urlString.hasSuffix(".git") { //HTTPS git } else { //SVN } Log.error("HTTPS or SVN not yet supported, please create an issue on GitHub if you want it added (czechboy0/Buildasaur)") return nil default: return nil } } else { return nil } } private func refreshMetadata() -> (Bool, NSError?) { let (allowed, meta, error) = LocalSource.attemptToParseFromUrl(self.url) if !allowed { return (false, error) } if let meta = meta { self.workspaceMetadata = meta return (true, nil) } else { return (false, error) } } public required init?(json: NSDictionary) { self.forkOriginURL = nil self.availabilityState = .Unchecked if let urlString = json.optionalStringForKey("url"), let url = NSURL(string: urlString) { self.url = url self.preferredTemplateId = json.optionalStringForKey("preferred_template_id") self.githubToken = json.optionalStringForKey("github_token") if let publicKeyUrl = json.optionalStringForKey("ssh_public_key_url") { self.publicSSHKeyUrl = NSURL(string: publicKeyUrl) } else { self.publicSSHKeyUrl = nil } if let privateKeyUrl = json.optionalStringForKey("ssh_private_key_url") { self.privateSSHKeyUrl = NSURL(string: privateKeyUrl) } else { self.privateSSHKeyUrl = nil } self.sshPassphrase = json.optionalStringForKey("ssh_passphrase") let (success, error) = self.refreshMetadata() if !success { Log.error("Error parsing: \(error)") return nil } } else { self.url = NSURL() self.preferredTemplateId = nil self.githubToken = nil self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil return nil } } public init() { self.forkOriginURL = nil self.availabilityState = .Unchecked self.url = NSURL() self.preferredTemplateId = nil self.githubToken = nil self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil } public func jsonify() -> NSDictionary { var json = NSMutableDictionary() json["url"] = self.url.absoluteString! json.optionallyAddValueForKey(self.preferredTemplateId, key: "preferred_template_id") json.optionallyAddValueForKey(self.githubToken, key: "github_token") json.optionallyAddValueForKey(self.publicSSHKeyUrl?.absoluteString, key: "ssh_public_key_url") json.optionallyAddValueForKey(self.privateSSHKeyUrl?.absoluteString, key: "ssh_private_key_url") json.optionallyAddValueForKey(self.sshPassphrase, key: "ssh_passphrase") return json } public func schemeNames() -> [String] { let schemes = XcodeProjectParser.sharedSchemeUrlsFromProjectOrWorkspaceUrl(self.url) let names = schemes.map { $0.lastPathComponent!.stringByDeletingPathExtension } return names } private class func loadWorkspaceMetadata(url: NSURL) -> (NSDictionary?, NSError?) { return XcodeProjectParser.parseRepoMetadataFromProjectOrWorkspaceURL(url) } public func githubRepoName() -> String? { if let projectUrl = self.projectURL { let originalStringUrl = projectUrl.absoluteString! let stringUrl = originalStringUrl.lowercaseString /* both https and ssh repos on github have a form of: {https://|git@}github.com{:|/}organization/repo.git here I need the organization/repo bit, which I'll do by finding "github.com" and shifting right by one and scan up until ".git" */ if let githubRange = stringUrl.rangeOfString("github.com", options: NSStringCompareOptions.allZeros, range: nil, locale: nil), let dotGitRange = stringUrl.rangeOfString(".git", options: NSStringCompareOptions.BackwardsSearch, range: nil, locale: nil) { let start = advance(githubRange.endIndex, 1) let end = dotGitRange.startIndex let repoName = originalStringUrl.substringWithRange(Range<String.Index>(start: start, end: end)) return repoName } } return nil } private func getContentsOfKeyAtUrl(url: NSURL?) -> String? { if let url = url { var error: NSError? if let key = NSString(contentsOfURL: url, encoding: NSASCIIStringEncoding, error: &error) { return key as String } Log.error("Couldn't load key at url \(url) with error \(error)") return nil } Log.error("Couldn't load key at nil url") return nil } }
mit
ecabdd40c680b5b0e847d303fafaa8c8
34.22082
151
0.570175
5.093522
false
false
false
false
tresorit/ZeroKit-Realm-encrypted-tasks
ios/RealmTasks Shared/NSAttributedString+Strikethrough.swift
1
2325
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif extension NSAttributedString { func strikedAttributedString(fraction: Double = 1) -> NSAttributedString { let range = NSRange(0..<Int(fraction * Double(length))) return strike(with: .styleThick, range: range) } var unstrikedAttributedString: NSAttributedString { return strike(with: .styleNone) } private func strike(with style: NSUnderlineStyle, range: NSRange? = nil) -> NSAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self) let attributeName = NSStrikethroughStyleAttributeName let fullRange = NSRange(0..<length) mutableAttributedString.removeAttribute(attributeName, range: fullRange) mutableAttributedString.addAttribute(attributeName, value: style.rawValue, range: range ?? fullRange) return mutableAttributedString } } #if os(iOS) extension UITextView { func strike(fraction: Double = 1) { attributedText = attributedText?.strikedAttributedString(fraction: fraction) } func unstrike() { attributedText = attributedText?.unstrikedAttributedString } } #elseif os(OSX) extension NSTextField { func strike(fraction: Double = 1) { attributedStringValue = attributedStringValue.strikedAttributedString(fraction: fraction) } func unstrike() { attributedStringValue = attributedStringValue.unstrikedAttributedString } } #endif
bsd-3-clause
ae3ae457f8e73f70e3267bdcdb156495
31.291667
109
0.653763
5.13245
false
false
false
false
andr3a88/TryNetworkLayer
TryNetworkLayer/Models/GHUserDetail.swift
1
2963
// // GHUserDetail.swift // // Created by Andrea Stevanato on 03/09/2017 // Copyright (c) . All rights reserved. // import Foundation import Realm import RealmSwift public final class GHUserDetail: Object, Codable { // MARK: Declaration for string constants to be used to decode and also serialize. enum CodingKeys: String, CodingKey { case publicRepos = "public_repos" case organizationsUrl = "organizations_url" case reposUrl = "repos_url" case starredUrl = "starred_url" case type = "type" case bio = "bio" case gistsUrl = "gists_url" case followersUrl = "followers_url" case id = "id" case blog = "blog" case followers = "followers" case following = "following" case company = "company" case url = "url" case name = "name" case updatedAt = "updated_at" case publicGists = "public_gists" case siteAdmin = "site_admin" case gravatarId = "gravatar_id" case htmlUrl = "html_url" case avatarUrl = "avatar_url" case login = "login" case location = "location" case createdAt = "created_at" case subscriptionsUrl = "subscriptions_url" case followingUrl = "following_url" case receivedEventsUrl = "received_events_url" case eventsUrl = "events_url" } // MARK: Properties @objc dynamic public var publicRepos: Int = 0 @objc dynamic public var organizationsUrl: String? @objc dynamic public var reposUrl: String? @objc dynamic public var starredUrl: String? @objc dynamic public var type: String? @objc dynamic public var bio: String? @objc dynamic public var gistsUrl: String? @objc dynamic public var followersUrl: String? @objc dynamic public var id: Int = 0 @objc dynamic public var blog: String? @objc dynamic public var followers: Int = 0 @objc dynamic public var following: Int = 0 @objc dynamic public var company: String? @objc dynamic public var url: String? @objc dynamic public var name: String? @objc dynamic public var updatedAt: String? @objc dynamic public var publicGists: Int = 0 @objc dynamic public var siteAdmin: Bool = false @objc dynamic public var gravatarId: String? @objc dynamic public var htmlUrl: String? @objc dynamic public var avatarUrl: String? @objc dynamic public var login: String? @objc dynamic public var location: String? @objc dynamic public var createdAt: String? @objc dynamic public var subscriptionsUrl: String? @objc dynamic public var followingUrl: String? @objc dynamic public var receivedEventsUrl: String? @objc dynamic public var eventsUrl: String? // MARK: Primary Key override public static func primaryKey() -> String? { "id" } // MARK: Init required public init() { super.init() } }
mit
011002d735c324fd6c765d8a6d9cff25
32.292135
86
0.646979
4.325547
false
false
false
false
DannyVancura/SwifTrix
SwifTrix/SwifTrixTests/SwifTrixKeychainTests.swift
1
9930
// // SwifTrixKeychainTests.swift // SwifTrix // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Security @testable import SwifTrix class SwifTrixTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /** Creates a prefilled `STKeychainInternetPassword` for testing purposes. */ private func createInternetPassword() -> STKeychainInternetPassword { let internetPassword = STKeychainInternetPassword() internetPassword.label = "internetPassword" internetPassword.server = "www.example.de" internetPassword.data = NSString(string: "password").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) internetPassword.path = "path/to/something/" internetPassword.itemDescription = "A password for www.example.de" internetPassword.account = "[email protected]" return internetPassword } /** If an item already exists in the keychain, this function deletes it (and all values that are stored with it) and creates it with the provided keychainItem (without the attributes that might have been set before) */ private func addObjectToKeychain(keychainItem: STKeychainItem) throws { do { try STKeychain.deleteKeychainItem(keychainItem) try STKeychain.addKeychainItem(keychainItem) } catch STKeychainError.ItemNotFound { try STKeychain.addKeychainItem(keychainItem) } } /** Tests saving and loading of a keychain item with an STKeychainInternetPassword as example */ func testKeychainItemCreation() { do { // Prepare the test object let internetPassword = self.createInternetPassword() try self.addObjectToKeychain(internetPassword) // Search the saved item with the test object's searchAttributes (in this case: label, server, path, account) let dict = try STKeychain.searchKeychainItem(internetPassword) // Array of the keys whose values should be equal in the saved and loaded objects let expectedEqualPairs = [kSecAttrLabel as String, kSecAttrServer as String, kSecValueData as String, kSecAttrPath as String, kSecAttrDescription as String, kSecAttrAccount as String] var equalItems = 0 for key in expectedEqualPairs { XCTAssertFalse(dict!.keys.filter({$0 == key}).isEmpty, "Expected key \(key) in the result's key list") guard let obj1 = dict?[key], obj2 = internetPassword.attributes[key] else { continue } // If objects are comparable (NSObjects are), count the number of equal items if let obj1 = obj1 as? NSObject, obj2 = obj2 as? NSObject { equalItems += 1 XCTAssertEqual(obj1, obj2) } } // Check if all checked attributes were equal, i.e. if the number of equal items == the number of expected equal pairs XCTAssertEqual(equalItems, expectedEqualPairs.count) } catch { print(error) XCTFail("Unexpected error during test") } } func testKeychainItemUpdate() { do { // Create an internet password and a password that contains only changes to this first internet password let internetPassword = self.createInternetPassword() let updatedInternetPassword = STKeychainInternetPassword() // Set the changes on the empty internet password updatedInternetPassword.data = NSString(string: "newPassword").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) updatedInternetPassword.port = 12345 // Add the first internet password (without changes) try self.addObjectToKeychain(internetPassword) // Update this saved internet password (so that it contains the changes) try STKeychain.updateKeychainItem(internetPassword, withNewValuesFrom: updatedInternetPassword) // Fetch the saved values and check if they were updated correctly guard let updatedValues = try STKeychain.searchKeychainItem(updatedInternetPassword) else { XCTFail("Expected to find updated attributes for the updated internet password") return } XCTAssertTrue(updatedValues[kSecAttrPort as String] as? Int == 12345, "Expected the port to be updated to 12345, instead found \(updatedValues[kSecAttrPort as String])") guard let data = updatedValues[kSecValueData as String] as? NSData else { XCTFail("Expected the updated keychain item to contain data for the key kSecValueData") return } guard let str = String(data: data, encoding: NSUTF8StringEncoding) else { XCTFail("Expected the updated data to be parseable to a string") return } XCTAssertEqual(str, "newPassword") } catch { print(error) XCTFail("Unexpected error") } } func testKeychainItemDeletion() { // Prepare the test object let genericPassword = STKeychainGenericPassword() genericPassword.label = "genericPassword" genericPassword.data = NSString(string: "password").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) genericPassword.itemDescription = "A generic password" genericPassword.account = "testuser" genericPassword.generic = NSString(string: "genericData").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { // Add the keychain item to the keychain try STKeychain.addKeychainItem(genericPassword) // Ensure that it is properly saved guard let _ = try STKeychain.searchKeychainItem(genericPassword) else { XCTFail("Expected a keychain item to be added to the keychain") return } // delete it from the keychain try STKeychain.deleteKeychainItem(genericPassword) // Ensure that it is properly deleted do { if let _ = try STKeychain.searchKeychainItem(genericPassword) { XCTFail("Expected the keychain item to be deleted from the keychain") return } } catch STKeychainError.ItemNotFound { // This error is considered a success - we wanted it to be deleted } } catch { switch error { default: XCTFail("Unexpected error: \(error)") } } } /** Keychain operations are expected to throw errors under certain circumstances, such as deleting non-existing items, adding items twice or searching for non-existing items. This test checks, if the right errors are thrown in these cases. */ func testForExpectedErrors() { let internetPassword = self.createInternetPassword() // Add it twice and check if it correctly throws an ItemAlreadyExists error do { try self.addObjectToKeychain(internetPassword) try STKeychain.addKeychainItem(internetPassword) XCTFail("Expected Error while adding an item twice") } catch STKeychainError.ItemAlreadyExists { // O.K. } catch { XCTFail("Unexpected error") } // Delete it twice and check if it correctly throws an ItemNotFound error the second time do { try STKeychain.deleteKeychainItem(internetPassword) } catch { XCTFail("Unexpected error while deleting") } do { try STKeychain.deleteKeychainItem(internetPassword) XCTFail("Expected Error while deleting non-existing item") } catch STKeychainError.ItemNotFound { // O.K. } catch { XCTFail("Unexpected error while deleting the second time") } // Search for a non-existing item do { try STKeychain.searchKeychainItem(internetPassword) XCTFail("Expected Error while searching for non-existing item") } catch STKeychainError.ItemNotFound { // O.K. } catch { XCTFail("Unexpected error while searching for a non-existing item") } } }
mit
9911bbff998d99d9649f85da9bb53cce
43.325893
240
0.63662
5.509989
false
true
false
false
payjp/payjp-ios
Sources/ThreeDSecure/ThreeDSecureSFSafariViewControllerDriver.swift
1
1467
// // ThreeDSecureSFSafariViewControllerDriver.swift // PAYJP // // Created by Tadashi Wakayanagi on 2020/04/06. // Copyright © 2020 PAY, Inc. All rights reserved. // import Foundation import SafariServices /// Web browse driver for SFSafariViewController. public class ThreeDSecureSFSafariViewControllerDriver: NSObject, ThreeDSecureWebDriver { /// Shared instance. public static let shared = ThreeDSecureSFSafariViewControllerDriver() private weak var delegate: ThreeDSecureWebDriverDelegate? public func openWebBrowser(host: UIViewController, url: URL, delegate: ThreeDSecureWebDriverDelegate) { let safariVc = SFSafariViewController(url: url) if #available(iOS 11.0, *) { safariVc.dismissButtonStyle = .close } safariVc.delegate = self self.delegate = delegate host.present(safariVc, animated: true, completion: nil) } public func closeWebBrowser(host: UIViewController?, completion: (() -> Void)?) -> Bool { if host is SFSafariViewController { host?.dismiss(animated: true) { completion?() } return true } return false } } // MARK: SFSafariViewControllerDelegate extension ThreeDSecureSFSafariViewControllerDriver: SFSafariViewControllerDelegate { public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { delegate?.webBrowseDidFinish(self) } }
mit
9191dd6ade989073bf4aa2cb72f15afe
30.191489
107
0.697817
5.003413
false
false
false
false
azukinohiroki/positionmaker2
positionmaker2/RecordPlayController.swift
1
2669
// // RecordPlayController.swift // positionmaker2 // // Created by Hiroki Taoka on 2015/07/02. // Copyright (c) 2015年 azukinohiroki. All rights reserved. // import Foundation import UIKit class RecordPlayObject { var fvs: [FigureView] var ps : [CGPoint] init(figureViews: [FigureView]) { fvs = figureViews ps = [] for fv in fvs { ps.append(fv.center) } } func toDictionary() -> Dictionary<String, Any> { var fv_ids = Array<NSNumber>() for fv in fvs { fv_ids.append(fv.getId()) } return ["fv_ids": fv_ids, "ps": ps] } } class RecordPlayController { static func instance() -> RecordPlayController { return (UIApplication.shared.delegate as! AppDelegate).recordPlayController } private var _recording = false private var _record: [RecordPlayObject] = [] private var _moved: [FigureView] = [] func startRecording(_ figureViews: [FigureView]) { _record.removeAll(keepingCapacity: true) recordLocation(figureViews) _recording = true } func recordLocation(_ figureViews: [FigureView]) { let obj = RecordPlayObject(figureViews: figureViews) _record.append(obj) _moved.removeAll() } func clearRecord() { _record = [] } func toDictionary() -> Dictionary<String, Any> { var arr = Array<Dictionary<String, Any>>() for rec in _record { arr.append(rec.toDictionary()) } return ["recordPlay": arr] } func figureMoved(figureView fv: FigureView) { if let index = _moved.index(of: fv) { _moved.remove(at: index) } _moved.append(fv) } private var _playing = false private var _sleepInternval: UInt32 = 1 func startPlaying(figureViews: [FigureView]) { if _record.count <= 1 || _playing { return; } _recording = false _playing = true UIView.animate(withDuration: 1) { let first = self._record[0] for i in 0 ..< first.fvs.count { let fv = first.fvs[i] let p = first.ps[i] fv.center = p } } DispatchQueue.global(qos: .userInitiated).async { sleep(1) self.startPlayInner() } } private func startPlayInner() { for index in 1 ..< _record.count { DispatchQueue.main.async { UIView.animate(withDuration: 1) { let first = self._record[index] for i in 0 ..< first.fvs.count { let fv = first.fvs[i] let p = first.ps[i] fv.center = p } } } sleep(_sleepInternval) } _playing = false } }
mit
7b3fbc3c5cb7a09929fc51da46ec00e6
19.358779
79
0.577053
3.756338
false
false
false
false
ikergravalos/AppOrganizeYourLife
OrganizeYourLife/OrganizeYourLife/ViewController.swift
1
2215
// // ViewController.swift // OrganizeYourLife // // Created by on 17/12/15. // Copyright © 2015 Ikeres. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { // MARK: - UIOutlets @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var collectionView: UICollectionView! let datos = Datos.sharedInstance let reuseIdentifier = "cell" var menu = Menu() // MARK: - UICollectionViewDataSource implementación del protocolo (interfaz) de la fuente de datos de la colección // Cuantas celdas tiene que tener func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return datos.getMaxTareas() } // Devolver la celda correspondiente a uno de los datos de la colección func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Obtener una referencia a la celda del Storyboard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MiCelda cell.Tarea!.text = datos.getNombreTarea(indexPath.row) // La clase personalizada MiCelda contiene un outlet a la etiqueta del storyboard // Dato return cell } @IBAction func Volver(segue:UIStoryboardSegue) { } @IBAction func Añadir(segue:UIStoryboardSegue) { let itemNuevo = segue.sourceViewController as! NuevaTareaViewController datos.setAnadir(itemNuevo.newItem) collectionView.reloadData() } // MARK: - UICollectionViewDelegate protocol que implementa una delegación func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // Detectar los toques print("You selected cell #\(indexPath.item)!") } }
apache-2.0
3ef02028b6a7a40e5abf3cc090f62985
28.065789
130
0.645088
5.297362
false
false
false
false
dduan/swift
test/IDE/print_type_interface.swift
7
1583
public struct A { public func fa() {} } extension A { public func fea1() {} } extension A { public func fea2() {} } class C1 { func f1() { var abcd : A abcd.fa() var intarr : [Int] intarr.append(1) } } // RUN: %target-swift-ide-test -print-type-interface -pos=13:6 -source-filename %s | FileCheck %s -check-prefix=TYPE1 // TYPE1: public struct A { // TYPE1: public func fa() // TYPE1: public func fea1() // TYPE1: public func fea2() // TYPE1: } public protocol P1 { } public class T1 : P1 { } public class D<T> { public func foo() {}} class C2 { func f() { let D1 = D<T1>() let D2 = D<Int>() D1.foo() D2.foo() } } // RUN: %target-swift-ide-test -print-type-interface -pos=34:6 -source-filename %s | FileCheck %s -check-prefix=TYPE2 // RUN: %target-swift-ide-test -print-type-interface -pos=35:6 -source-filename %s | FileCheck %s -check-prefix=TYPE3 extension D where T : P1 { public func conditionalFunc1() {} public func conditionalFunc2(t : T) -> T {return t} } extension D { public func unconditionalFunc1(){} public func unconditionalFunc2(t : T) -> T {return t} } // TYPE2: public class D<T1> { // TYPE2: public func foo() // TYPE2: public func conditionalFunc1() // TYPE2: public func conditionalFunc2(t: T1) -> T1 // TYPE2: public func unconditionalFunc1() // TYPE2: public func unconditionalFunc2(t: T1) -> T1 // TYPE2: } // TYPE3: public class D<Int> { // TYPE3: public func foo() // TYPE3: public func unconditionalFunc1() // TYPE3: public func unconditionalFunc2(t: Int) -> Int // TYPE3: }
apache-2.0
40baddd6a8c8b0bff53d4770636226ae
23.734375
117
0.637397
2.79682
false
false
false
false
x43x61x69/Swift-UUID
src/Swift UUID/AppDelegate.swift
1
5346
// // AppDelegate.swift // Swift UUID // // Copyright (c) 2014 Cai, Zhi-Wei. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // import Cocoa import IOKit class AppDelegate: NSObject, NSApplicationDelegate { // Xcode 6 beta does not implement #pragma yet. :( // #pragma mark - UI @IBOutlet var window: NSWindow! @IBOutlet var result: NSTextField! @IBOutlet var popUp: NSPopUpButton! // #pragma mark - Basic func applicationDidFinishLaunching(aNotification: NSNotification?) { println("Hello World!"); } func applicationWillTerminate(aNotification: NSNotification?) { // Insert code here to tear down your application } func applicationShouldTerminateAfterLastWindowClosed(theApplication: NSApplication?) -> Bool { return true } // #pragma mark - IBActions @IBAction func generateUUID(sender: AnyObject) { var uuid = "" if uuidGen(popUp.selectedItem.tag, uuid: &uuid) == true { result.stringValue = uuid } } func uuidGen(type: Int, inout uuid: String) -> Bool { // Random UUID. func getUUID(inout uuid: String) -> Bool { var uuidRef: CFUUIDRef? var uuidStringRef: CFStringRef? uuidRef = CFUUIDCreate(kCFAllocatorDefault) uuidStringRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef) if (uuidRef != nil) { uuidRef = nil } if (uuidStringRef != nil) { uuid = uuidStringRef! as NSString return true } return false } // Hardare UUID shows in the system profiler. func getHwUUID(inout uuid: String) -> Bool { var uuidRef: CFUUIDRef? var uuidStringRef: CFStringRef? var uuidBytes: [CUnsignedChar] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] var ts = timespec(tv_sec: 0,tv_nsec: 0) gethostuuid(&uuidBytes, &ts) uuidRef = CFUUIDCreateWithBytes( kCFAllocatorDefault, uuidBytes[0], uuidBytes[1], uuidBytes[2], uuidBytes[3], uuidBytes[4], uuidBytes[5], uuidBytes[6], uuidBytes[7], uuidBytes[8], uuidBytes[9], uuidBytes[10], uuidBytes[11], uuidBytes[12], uuidBytes[13], uuidBytes[14], uuidBytes[15] ) uuidBytes = [] uuidStringRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef) if (uuidRef != nil) { uuidRef = nil } if (uuidStringRef != nil) { uuid = uuidStringRef! as NSString return true } return false } // Hardware serial number shows in "About this Mac" window. func getSystemSerialNumber(inout uuid: String) -> Bool { var ioPlatformExpertDevice: io_service_t? var serialNumber: CFTypeRef? ioPlatformExpertDevice = IOServiceGetMatchingService( kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice").takeUnretainedValue() ) if (ioPlatformExpertDevice != nil) { serialNumber = IORegistryEntryCreateCFProperty( ioPlatformExpertDevice!, "IOPlatformSerialNumber", // println(kIOPlatformSerialNumberKey); kCFAllocatorDefault, 0 ).takeRetainedValue() println(serialNumber); } IOObjectRelease(ioPlatformExpertDevice!) if (serialNumber != nil) { uuid = serialNumber! as NSString return true } return false } var success = false switch type { case 1: success = getHwUUID(&uuid) case 2: success = getSystemSerialNumber(&uuid) default: success = getUUID(&uuid) } return success } }
gpl-3.0
0a299cde82574c64f22c4fe1914eaeed
29.375
98
0.510849
5.277394
false
false
false
false
nicadre/SwiftyProtein
SwiftyProtein/Services/APIRequester.swift
1
1437
// // APIRequester.swift // SwiftyProtein // // Created by Nicolas Chevalier on 19/07/16. // Copyright © 2016 Nicolas CHEVALIER. All rights reserved. // import Alamofire class APIRequester { static let sharedInstance = APIRequester() let baseLigandUrl: String = "http://file.rcsb.org/" let baseLigandInfosUrl: String = "http://www.rcsb.org/" init() { } func request(method: Method, URLString: URLStringConvertible, parameters: [String : AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String : String]? = nil, completionHandler: Response<NSData, NSError> -> Void) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true Alamofire.request(method, URLString, parameters: parameters, encoding: encoding, headers: headers).responseData { (response) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false completionHandler(response) } } func requestLigand(ligandName: String, completionHandler: Response<NSData, NSError> -> Void) { self.request(.GET, URLString: "\(self.baseLigandUrl)ligands/download/\(ligandName)_model.pdb", completionHandler: completionHandler) } func requestInfoLigand(ligandName: String, completionHandler: Response<NSData, NSError> -> Void) { self.request(.GET, URLString: "\(self.baseLigandInfosUrl)pdb/rest/describeHet?chemicalID=\(ligandName)", completionHandler: completionHandler) } }
gpl-3.0
e38058d2186f00625c0c83b8aba86920
34.02439
230
0.743036
3.977839
false
false
false
false
mownier/photostream
Photostream/UI/Comment Writer/CommentWriterViewController.swift
1
1833
// // CommentWriterViewController.swift // Photostream // // Created by Mounir Ybanez on 30/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit class CommentWriterViewController: UIViewController { var presenter: CommentWriterModuleInterface! var commentWriterView: CommentWriterView! { return view as! CommentWriterView } override func loadView() { let width: CGFloat = UIScreen.main.bounds.size.width let height: CGFloat = 44 let size = CGSize(width: width, height: height) let customView = CommentWriterView() customView.delegate = self customView.frame.size = size preferredContentSize = size view = customView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.addKeyboardObserver() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) presenter.removeKeyboardObserver() } } extension CommentWriterViewController: CommentWriterScene { var controller: UIViewController? { return self } func didWrite(with error: String?) { commentWriterView.isSending = false } func keyboardWillMove(with handler: inout KeyboardHandler) { handler.handle(using: view) } } extension CommentWriterViewController: CommentWriterViewDelegate { func willSend(with content: String?, view: CommentWriterView) { guard let comment = content?.trimmingCharacters(in: .whitespacesAndNewlines), !comment.isEmpty else { didWrite(with: "Comment is emtpy") return } presenter.writeComment(with: comment) } }
mit
d96cce818417b1c9f212037de04a3cf7
24.802817
85
0.646834
5.249284
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Axis/ChartAxisValuesGenerator.swift
1
8563
// // ChartAxisValuesGenerator.swift // swift_charts // // Created by ischuetz on 12/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public typealias ChartAxisValueGenerator = (Double) -> ChartAxisValue /// Dynamic axis values generation public struct ChartAxisValuesGenerator { /** Calculates the axis values that bound some chart points along the X axis Think of a segment as the "space" between two axis values. - parameter chartPoints: The chart points to bound. - parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict. - parameter maxSegmentCount: The maximum number of segments in the range of axis values. - parameter multiple: The desired width of each segment between axis values. - parameter axisValueGenerator: Function that converts a scalar value to an axis value. - parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values. - returns: An array of axis values. */ public static func generateXAxisValuesWithChartPoints(_ chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.x}) } /** Calculates the axis values that bound some chart points along the Y axis Think of a segment as the "space" between two axis values. - parameter chartPoints: The chart points to bound. - parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict. - parameter maxSegmentCount: The maximum number of segments in the range of axis values. - parameter multiple: The desired width of each segment between axis values. - parameter axisValueGenerator: Function that converts a scalar value to an axis value. - parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values. - returns: An array of axis values. */ public static func generateYAxisValuesWithChartPoints(_ chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.y}) } /** Calculates the axis values that bound some chart points along a particular axis dimension. Think of a segment as the "space" between two axis values. - parameter chartPoints: The chart points to bound. - parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict. - parameter maxSegmentCount: The maximum number of segments in the range of axis values. - parameter multiple: The desired width of each segment between axis values. - parameter axisValueGenerator: Function that converts a scalar value to an axis value. - parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last chart points fall exactly on the axis values. - parameter axisPicker: A function that maps a chart point to its value for a particular axis. - returns: An array of axis values. */ fileprivate static func generateAxisValuesWithChartPoints(_ chartPoints: [ChartPoint], minSegmentCount: Double, maxSegmentCount: Double, multiple: Double = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool, axisPicker: (ChartPoint) -> ChartAxisValue) -> [ChartAxisValue] { let sortedChartPoints = chartPoints.sorted {(obj1, obj2) in return axisPicker(obj1).scalar < axisPicker(obj2).scalar } if let first = sortedChartPoints.first, let last = sortedChartPoints.last { return self.generateAxisValuesWithChartPoints(axisPicker(first).scalar, last: axisPicker(last).scalar, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge) } else { print("Trying to generate Y axis without datapoints, returning empty array") return [] } } /** Calculates the axis values that bound two values and have an optimal number of segments between them. Think of a segment as the "space" between two axis values. - parameter first: The first scalar value to bound. - parameter last: The last scalar value to bound. - parameter minSegmentCount: The minimum number of segments in the range of axis values. This value is prioritized over the maximum in order to prevent a conflict. - parameter maxSegmentCount: The maximum number of segments in the range of axis values. - parameter multiple: The desired width of each segment between axis values. - parameter axisValueGenerator: Function that converts a scalar value to an axis value. - parameter addPaddingSegmentIfEdge: Whether or not to add an extra value to the start and end if the first and last scalar values fall exactly on the axis values. - returns: An array of axis values */ fileprivate static func generateAxisValuesWithChartPoints(_ first: Double, last lastPar: Double, minSegmentCount: Double, maxSegmentCount: Double, multiple: Double, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { guard lastPar >= first else {fatalError("Invalid range generating axis values")} let last = lastPar == first ? lastPar + 1 : lastPar // The first axis value will be less than or equal to the first scalar value, aligned with the desired multiple var firstValue = first - (first.truncatingRemainder(dividingBy: multiple)) // The last axis value will be greater than or equal to the first scalar value, aligned with the desired multiple var lastValue = last + (abs(multiple - last).truncatingRemainder(dividingBy: multiple)) var segmentSize = multiple // If there should be a padding segment added when a scalar value falls on the first or last axis value, adjust the first and last axis values if firstValue == first && addPaddingSegmentIfEdge { firstValue = firstValue - segmentSize } if lastValue == last && addPaddingSegmentIfEdge { lastValue = lastValue + segmentSize } let distance = lastValue - firstValue var currentMultiple = multiple var segmentCount = distance / currentMultiple // Find the optimal number of segments and segment width // If the number of segments is greater than desired, make each segment wider while segmentCount > maxSegmentCount { currentMultiple *= 2 segmentCount = distance / currentMultiple } segmentCount = ceil(segmentCount) // Increase the number of segments until there are enough as desired while segmentCount < minSegmentCount { segmentCount += 1 } segmentSize = currentMultiple // Generate axis values from the first value, segment size and number of segments let offset = firstValue return (0...Int(segmentCount)).map {segment in let scalar = offset + (Double(segment) * segmentSize) return axisValueGenerator(scalar) } } }
mit
7839a8abd8ca544d39cab7908b1756ca
58.465278
305
0.708747
5.62615
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartGuideLinesLayer.swift
1
8182
// // ChartGuideLinesLayer.swift // SwiftCharts // // Created by ischuetz on 26/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit open class ChartGuideLinesLayerSettings { let linesColor: UIColor let linesWidth: CGFloat public init(linesColor: UIColor = UIColor.gray, linesWidth: CGFloat = 0.3) { self.linesColor = linesColor self.linesWidth = linesWidth } } open class ChartGuideLinesDottedLayerSettings: ChartGuideLinesLayerSettings { let dotWidth: CGFloat let dotSpacing: CGFloat public init(linesColor: UIColor, linesWidth: CGFloat, dotWidth: CGFloat = 2, dotSpacing: CGFloat = 2) { self.dotWidth = dotWidth self.dotSpacing = dotSpacing super.init(linesColor: linesColor, linesWidth: linesWidth) } } public enum ChartGuideLinesLayerAxis { case x, y, xAndY } open class ChartGuideLinesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer { fileprivate let settings: T fileprivate let onlyVisibleX: Bool fileprivate let onlyVisibleY: Bool fileprivate let axis: ChartGuideLinesLayerAxis public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: T, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { self.settings = settings self.onlyVisibleX = onlyVisibleX self.onlyVisibleY = onlyVisibleY self.axis = axis super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { fatalError("override") } override open func chartViewDrawing(context: CGContext, chart: Chart) { let originScreenLoc = self.innerFrame.origin let xScreenLocs = onlyVisibleX ? self.xAxis.visibleAxisValuesScreenLocs : self.xAxis.axisValuesScreenLocs let yScreenLocs = onlyVisibleY ? self.yAxis.visibleAxisValuesScreenLocs : self.yAxis.axisValuesScreenLocs if self.axis == .x || self.axis == .xAndY { for xScreenLoc in xScreenLocs { let x1 = xScreenLoc let y1 = originScreenLoc.y let x2 = x1 let y2 = originScreenLoc.y + self.innerFrame.height self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } if self.axis == .y || self.axis == .xAndY { for yScreenLoc in yScreenLocs { let x1 = originScreenLoc.x let y1 = yScreenLoc let x2 = originScreenLoc.x + self.innerFrame.width let y2 = y1 self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } } } public typealias ChartGuideLinesLayer = ChartGuideLinesLayer_<Any> open class ChartGuideLinesLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesLayerSettings> { override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: ChartGuideLinesLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY) } override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor) } } public typealias ChartGuideLinesDottedLayer = ChartGuideLinesDottedLayer_<Any> open class ChartGuideLinesDottedLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesDottedLayerSettings> { override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: ChartGuideLinesDottedLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY) } override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing) } } open class ChartGuideLinesForValuesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer { fileprivate let settings: T fileprivate let axisValuesX: [ChartAxisValue] fileprivate let axisValuesY: [ChartAxisValue] public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: T, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { self.settings = settings self.axisValuesX = axisValuesX self.axisValuesY = axisValuesY super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } fileprivate func drawGuideline(_ context: CGContext, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint, dotWidth: CGFloat, dotSpacing: CGFloat) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: width, color: color, dotWidth: dotWidth, dotSpacing: dotSpacing) } fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { fatalError("override") } override open func chartViewDrawing(context: CGContext, chart: Chart) { let originScreenLoc = self.innerFrame.origin for axisValue in self.axisValuesX { let screenLoc = self.xAxis.screenLocForScalar(axisValue.scalar) let x1 = screenLoc let y1 = originScreenLoc.y let x2 = x1 let y2 = originScreenLoc.y + self.innerFrame.height self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } for axisValue in self.axisValuesY { let screenLoc = self.yAxis.screenLocForScalar(axisValue.scalar) let x1 = originScreenLoc.x let y1 = screenLoc let x2 = originScreenLoc.x + self.innerFrame.width let y2 = y1 self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2)) } } } public typealias ChartGuideLinesForValuesLayer = ChartGuideLinesForValuesLayer_<Any> open class ChartGuideLinesForValuesLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesLayerSettings> { public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY) } override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor) } } public typealias ChartGuideLinesForValuesDottedLayer = ChartGuideLinesForValuesDottedLayer_<Any> open class ChartGuideLinesForValuesDottedLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesDottedLayerSettings> { public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesDottedLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) { super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY) } override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) { ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing) } }
mit
d6324947e0eae790438520a3e3736884
45.225989
235
0.70154
4.297269
false
false
false
false
mojio/mojio-ios-sdk
MojioSDK/Models/VinDetails/Engine.swift
1
1063
// // Engine.swift // MojioSDK // // Created by Ashish Agarwal on 2016-02-26. // Copyright © 2016 Mojio. All rights reserved. // import UIKit import ObjectMapper public class Engine: Mappable { public dynamic var Name : String? = nil public dynamic var Cylinders : String? = nil public dynamic var Displacement : Float = 0 public dynamic var FuelInduction : String? = nil public dynamic var FuelQuality : String? = nil public dynamic var FuelType : String? = nil public dynamic var MaxHp : String? = nil public dynamic var MaxHpAt : String? = nil public required convenience init?(_ map: Map) { self.init(); } public required init() { } public func mapping(map: Map) { Name <- map["Name"] Cylinders <- map["Cylinders"] Displacement <- map["Displacement"] FuelInduction <- map["FuelInduction"] FuelQuality <- map["FuelQuality"] FuelType <- map["FuelType"] MaxHp <- map["MaxHp"] MaxHpAt <- map["MaxHpAt"] } }
mit
d7a15f956e86cfccbad60f9059f86d7c
24.902439
52
0.613936
3.933333
false
false
false
false
kay-kim/stitch-examples
todo/ios/Pods/FacebookCore/Sources/Core/UserProfile/UserProfile.PictureView.swift
19
3257
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import UIKit import FBSDKCoreKit.FBSDKProfilePictureView extension UserProfile { /// A view to display a profile picture. public final class PictureView: UIView { fileprivate let sdkProfilePictureView = FBSDKProfilePictureView(frame: .zero) /// The aspect ratio of the source image of the profile picture. public var pictureAspectRatio = UserProfile.PictureAspectRatio.square { didSet { sdkProfilePictureView.pictureMode = pictureAspectRatio.sdkPictureMode } } /// The user id to show the picture for. public var userId = "me" { didSet { sdkProfilePictureView.profileID = userId } } /** Create a new instance of `UserProfilePictureView`. - parameter frame: Optional frame rectangle for the view, measured in points. - parameter profile: Optional profile to display a picture for. Default: `UserProfile.current`. */ public init(frame: CGRect = .zero, profile: UserProfile? = nil) { super.init(frame: frame) if let profile = profile { userId = profile.userId } setupSDKProfilePictureView() } /** Create a new instance of `UserProfilePictureView` from an encoded interface file. - parameter decoder: The coder to initialize from. */ public required init?(coder decoder: NSCoder) { super.init(coder: decoder) setupSDKProfilePictureView() } /** Explicitly marks the receiver as needing to update the image. This method is called whenever any properties that affect the source image are modified, but this can also be used to trigger a manual update of the image if it needs to be re-downloaded. */ public func setNeedsImageUpdate() { sdkProfilePictureView.setNeedsImageUpdate() } } } extension UserProfile.PictureView { fileprivate func setupSDKProfilePictureView() { sdkProfilePictureView.frame = bounds sdkProfilePictureView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(sdkProfilePictureView) setNeedsImageUpdate() // Trigger the update to refresh the image, just in case. } }
apache-2.0
1853cfd5c34dbe1501d51306a506cbd9
35.188889
103
0.724593
4.782673
false
false
false
false
gregomni/swift
benchmark/single-source/SIMDReduceInteger.swift
2
7085
//===--- SIMDReduceInteger.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = [ BenchmarkInfo( name: "SIMDReduce.Int32", runFunction: run_SIMDReduceInt32x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Initializer", runFunction: run_SIMDReduceInt32x4_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Cast", runFunction: run_SIMDReduceInt32x4_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Initializer", runFunction: run_SIMDReduceInt32x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Cast", runFunction: run_SIMDReduceInt32x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8", runFunction: run_SIMDReduceInt8x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Initializer", runFunction: run_SIMDReduceInt8x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Cast", runFunction: run_SIMDReduceInt8x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Initializer", runFunction: run_SIMDReduceInt8x64_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Cast", runFunction: run_SIMDReduceInt8x64_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ) ] // TODO: use 100 for Onone? let scale = 1000 let int32Data: UnsafeBufferPointer<Int32> = { let count = 256 // Allocate memory for `count` Int32s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int32>.size * count, alignment: 16 ) // Initialize the memory as Int32 and fill with random values. let typed = untyped.initializeMemory(as: Int32.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt32x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int32 = 0 for v in int32Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt32x4_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for i in stride(from: 0, to: int32Data.count, by: 4) { let v = SIMD4(int32Data[i ..< i+4]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x4_cast(_ n: Int) { // Morally it seems like we "should" be able to use withMemoryRebound // to SIMD4<Int32>, but that function requries that the sizes match in // debug builds, so this is pretty ugly. The following "works" for now, // but is probably in violation of the formal model (the exact rules // for "assumingMemoryBound" are not clearly documented). We need a // better solution. let vecs = UnsafeBufferPointer<SIMD4<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD4<Int32>.self), count: int32Data.count / 4 ) for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for i in stride(from: 0, to: int32Data.count, by: 16) { let v = SIMD16(int32Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int32>.self), count: int32Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } let int8Data: UnsafeBufferPointer<Int8> = { let count = 1024 // Allocate memory for `count` Int8s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int8>.size * count, alignment: 16 ) // Initialize the memory as Int8 and fill with random values. let typed = untyped.initializeMemory(as: Int8.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt8x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int8 = 0 for v in int8Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt8x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for i in stride(from: 0, to: int8Data.count, by: 16) { let v = SIMD16(int8Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int8>.self), count: int8Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for i in stride(from: 0, to: int8Data.count, by: 64) { let v = SIMD64(int8Data[i ..< i+64]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD64<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD64<Int8>.self), count: int8Data.count / 64 ) for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } }
apache-2.0
f3dd7846f367ef96bad929a4a852a173
27.684211
96
0.642343
3.40625
false
false
false
false
dracrowa-kaz/DeveloperNews
DeveloperNews/MainTabViewController.swift
1
1108
// // MainTabViewController.swift // DeveloperNews // // Created by 佐藤和希 on 1/15/17. // Copyright © 2017 kaz. All rights reserved. // import UIKit import XLPagerTabStrip import KRProgressHUD class MainTabViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let storyboard = UIStoryboard(name: "Main", bundle: nil) let firstView = storyboard.instantiateViewController(withIdentifier: "MainButtonBarPagerViewController") as! MainButtonBarPagerViewController let secondView = UIViewController() firstView.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.bookmarks, tag: 1) secondView.tabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.favorites, tag: 2) let myTabs = NSArray(objects: firstView, secondView) self.setViewControllers(myTabs as? [UIViewController], animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f3aa7aad4ceb77906f35a87afe1f068b
31.323529
149
0.713376
5.111628
false
false
false
false
gugutech/gugutech_else_ios
ELSE/ELSE/RootViewController.swift
1
2265
// // RootViewController.swift // ELSE // // Created by Luliang on 15/7/17. // Copyright © 2015年 GuGu. All rights reserved. // import UIKit class RootViewController: RESideMenu, RESideMenuDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.navigationBarHidden = true } override func awakeFromNib() { self.menuPreferredStatusBarStyle = .LightContent self.contentViewShadowColor = UIColor.blackColor() self.contentViewShadowOffset = CGSizeMake(0, 0) self.contentViewShadowOpacity = 0.6 self.contentViewShadowRadius = 12 self.contentViewShadowEnabled = true self.panGestureEnabled = false self.contentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("HomeVC") self.rightMenuViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RightMenuVC") self.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.backgroundImage = UIImage(named: "Stars") } } //----- MARK: RESideMenu Delegate extension RootViewController { func sideMenu(sideMenu: RESideMenu!, willShowMenuViewController menuViewController: UIViewController!) { print("willShowMenuViewController: \(NSStringFromClass(menuViewController.classForCoder))", appendNewline: true) } func sideMenu(sideMenu: RESideMenu!, didShowMenuViewController menuViewController: UIViewController!) { print("didShowMenuViewController: \(NSStringFromClass(menuViewController.classForCoder))", appendNewline: true) } func sideMenu(sideMenu: RESideMenu!, willHideMenuViewController menuViewController: UIViewController!) { print("willHideMenuViewController: \(NSStringFromClass(menuViewController.classForCoder))", appendNewline: true) } func sideMenu(sideMenu: RESideMenu!, didHideMenuViewController menuViewController: UIViewController!) { print("didHideMenuViewController: \(NSStringFromClass(menuViewController.classForCoder))", appendNewline: true) } }
mit
60d20757e2a0dfc9d6f80a92d6d68388
34.904762
120
0.714854
5.875325
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/Validator/Rules/ValidationRuleLength.swift
1
1772
/* ValidationRuleLength.swift Validator Created by @adamwaite. Copyright (c) 2015 Adam Waite. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public struct ValidationRuleLength: ValidationRule { public typealias InputType = String public let min: Int public let max: Int public var failureError: ValidationErrorType public init(min: Int = 0, max: Int = Int.max, failureError: ValidationErrorType) { self.min = min self.max = max self.failureError = failureError } public func validateInput(input: String?) -> Bool { guard let input = input else { return false } return input.characters.count >= min && input.characters.count <= max } }
gpl-3.0
f351a88a8f5a07f53ab06c57ddd4fbf8
33.745098
86
0.739842
4.737968
false
false
false
false
weareopensource/Sample-iOS_Swift_2_GetStarted
StepOne/SearchResultsViewController.swift
1
6436
// // ViewController.swift // StepOne // // Created by WeAreOpenSource.me on 24/04/2015. // Copyright (c) 2015 WeAreOpenSource.me rights reserved. // // tuto : http://jamesonquave.com/blog/developing-ios-8-apps-using-swift-animations-audio-and-custom-table-view-cells/ import UIKit class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol { /*************************************************/ // Main /*************************************************/ // Boulet /*************************/ @IBOutlet weak var appsTableView: UITableView! @IBOutlet weak var mytable: UITableView! // Var /*************************/ var albums = [Album]() var imageCache = [String:UIImage]() var api : APIController! let kCellIdentifier: String = "SearchResultCell" var refreshControl:UIRefreshControl! // Base /*************************/ override func viewDidLoad() { super.viewDidLoad() // custom // --------------------- self.mytable.rowHeight = 70 self.mytable.backgroundView = UIImageView(image: UIImage(named: "home.jpg")) // --------------------- // get data api = APIController(delegate: self) UIApplication.sharedApplication().networkActivityIndicatorVisible = true api.searchItunesFor("Beatles") //Pull to refresh self.refreshControl = UIRefreshControl() self.refreshControl.tintColor = UIColor.whiteColor() self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.mytable.addSubview(refreshControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // TableView /*************************/ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier, forIndexPath: indexPath) let album = self.albums[indexPath.row] // Get the formatted price string for display in the subtitle cell.detailTextLabel?.text = album.price // Update the textLabel text to use the title from the Album model cell.textLabel?.text = album.title // Start by setting the cell's image to a static file // Without this, we will end up without an image view! cell.imageView?.image = UIImage(named: "Blank52") let thumbnailURLString = album.thumbnailImageURL let thumbnailURL = NSURL(string: thumbnailURLString)! // If this image is already cached, don't re-download if let img = imageCache[thumbnailURLString] { cell.imageView?.image = img } else { // The image isn't cached, download the img data // We should perform this in a background thread let request: NSURLRequest = NSURLRequest(URL: thumbnailURL) let mainQueue = NSOperationQueue.mainQueue() NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in if error == nil { // Convert the downloaded data in to a UIImage object let image = UIImage(data: data!) // Store the image in to our cache self.imageCache[thumbnailURLString] = image // Update the cell dispatch_async(dispatch_get_main_queue(), { if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) { cellToUpdate.imageView?.image = image } }) } else { print("Error: \(error!.localizedDescription)") } }) } // custom // --------------------- cell.detailTextLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0) cell.detailTextLabel?.textColor = UIColor.whiteColor().colorWithAlphaComponent(0.7) cell.textLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0) cell.textLabel?.textColor = UIColor.whiteColor() cell.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.25) let customColorView = UIView() customColorView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.1) cell.selectedBackgroundView = customColorView // --------------------- return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1) UIView.animateWithDuration(0.25, animations: { cell.layer.transform = CATransform3DMakeScale(1,1,1) }) } // Segue /*************************/ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let detailsViewController: DetailsViewController = segue.destinationViewController as? DetailsViewController { let albumIndex = appsTableView!.indexPathForSelectedRow!.row let selectedAlbum = self.albums[albumIndex] detailsViewController.album = selectedAlbum } } /*************************************************/ // Functions /*************************************************/ func refresh(sender:AnyObject) { // get data api = APIController(delegate: self) UIApplication.sharedApplication().networkActivityIndicatorVisible = true api.searchItunesFor("Beatles") } func didReceiveAPIResults(results: NSArray) { dispatch_async(dispatch_get_main_queue(), { self.albums = Album.albumsWithJSON(results) self.appsTableView!.reloadData() self.refreshControl.endRefreshing() UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) } }
mit
2a35837e4aa3093adb20210fdfd1f9d6
38.728395
134
0.594158
5.741302
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Data/Networking/Auth/Jwt/SecKeyUtils.swift
1
10149
import Foundation import Security public extension RSAKey { enum KeyUtilError: Swift.Error { case notStringReadable case badPEMArmor case notBase64Readable case badKeyFormat } @discardableResult public static func registerOrUpdateKey(_ keyData: Data, tag: String) throws -> RSAKey { let key: SecKey? = try { if let existingData = try getKeyData(tag) { let newData = keyData.dataByStrippingX509Header() if existingData != newData { try updateKey(tag, data: newData) } return try getKey(tag) } else { return try addKey(tag, data: keyData.dataByStrippingX509Header()) } }() if let result = key { return RSAKey(secKey: result) } else { throw KeyUtilError.badKeyFormat } } @discardableResult public static func registerOrUpdateKey(modulus: Data, exponent: Data, tag: String) throws -> RSAKey { let combinedData = Data(modulus: modulus, exponent: exponent) return try RSAKey.registerOrUpdateKey(combinedData, tag: tag) } @discardableResult public static func registerOrUpdatePublicPEMKey(_ keyData: Data, tag: String) throws -> RSAKey { guard let stringValue = String(data: keyData, encoding: String.Encoding.utf8) else { throw KeyUtilError.notStringReadable } let base64Content: String = try { //remove ----BEGIN and ----END let scanner = Scanner(string: stringValue) scanner.charactersToBeSkipped = CharacterSet.whitespacesAndNewlines if scanner.scanString("-----BEGIN", into: nil) { scanner.scanUpTo("KEY-----", into: nil) guard scanner.scanString("KEY-----", into: nil) else { throw KeyUtilError.badPEMArmor } var content: NSString? = nil scanner.scanUpTo("-----END", into: &content) guard scanner.scanString("-----END", into: nil) else { throw KeyUtilError.badPEMArmor } return content?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } return nil }() ?? stringValue guard let decodedKeyData = Data(base64Encoded: base64Content, options: [.ignoreUnknownCharacters]) else { throw KeyUtilError.notBase64Readable } return try RSAKey.registerOrUpdateKey(decodedKeyData, tag: tag) } static func registeredKeyWithTag(_ tag: String) -> RSAKey? { return ((try? getKey(tag)) ?? nil).map(RSAKey.init) } static func removeKeyWithTag(_ tag: String) { do { try deleteKey(tag) } catch { } } } private func getKey(_ tag: String) throws -> SecKey? { var keyRef: AnyObject? var query = matchQueryWithTag(tag) query[kSecReturnRef as String] = kCFBooleanTrue let status = SecItemCopyMatching(query as CFDictionary, &keyRef) switch status { case errSecSuccess: if keyRef != nil { return (keyRef as! SecKey) } else { return nil } case errSecItemNotFound: return nil default: throw RSAKey.Error.securityError(status) } } internal func getKeyData(_ tag: String) throws -> Data? { var query = matchQueryWithTag(tag) query[kSecReturnData as String] = kCFBooleanTrue var result: AnyObject? = nil let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: return (result as! Data) case errSecItemNotFound: return nil default: throw RSAKey.Error.securityError(status) } } private func updateKey(_ tag: String, data: Data) throws { let query = matchQueryWithTag(tag) let updateParam = [kSecValueData as String: data] let status = SecItemUpdate(query as CFDictionary, updateParam as CFDictionary) guard status == errSecSuccess else { throw RSAKey.Error.securityError(status) } } private func deleteKey(_ tag: String) throws { let query = matchQueryWithTag(tag) let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess { throw RSAKey.Error.securityError(status) } } private func matchQueryWithTag(_ tag: String) -> Dictionary<String, Any> { return [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag, ] } private func addKey(_ tag: String, data: Data) throws -> SecKey? { var publicAttributes = Dictionary<String, Any>() publicAttributes[kSecAttrKeyType as String] = kSecAttrKeyTypeRSA publicAttributes[kSecClass as String] = kSecClassKey publicAttributes[kSecAttrApplicationTag as String] = tag as CFString publicAttributes[kSecValueData as String] = data as CFData publicAttributes[kSecReturnPersistentRef as String] = kCFBooleanTrue var persistentRef: CFTypeRef? let status = SecItemAdd(publicAttributes as CFDictionary, &persistentRef) if status == noErr || status == errSecDuplicateItem { return try getKey(tag) } throw RSAKey.Error.securityError(status) } /// /// Encoding/Decoding lengths as octets /// private extension NSInteger { func encodedOctets() -> [CUnsignedChar] { // Short form if self < 128 { return [CUnsignedChar(self)]; } // Long form let i = (self / 256) + 1 var len = self var result: [CUnsignedChar] = [CUnsignedChar(i + 0x80)] for _ in 0..<i { result.insert(CUnsignedChar(len & 0xFF), at: 1) len = len >> 8 } return result } init?(octetBytes: [CUnsignedChar], startIdx: inout NSInteger) { if octetBytes[startIdx] < 128 { // Short form self.init(octetBytes[startIdx]) startIdx += 1 } else { // Long form let octets = NSInteger(octetBytes[startIdx] - CUnsignedChar(128)) if octets > octetBytes.count - startIdx { self.init(0) return nil } var result = UInt64(0) for j in 1...octets { result = (result << 8) result = result + UInt64(octetBytes[startIdx + j]) } startIdx += 1 + octets self.init(result) } } } /// /// Manipulating data /// private extension Data { init(modulus: Data, exponent: Data) { // Make sure neither the modulus nor the exponent start with a null byte var modulusBytes = [CUnsignedChar](UnsafeBufferPointer<CUnsignedChar>(start: (modulus as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: modulus.count), count: modulus.count / MemoryLayout<CUnsignedChar>.size)) let exponentBytes = [CUnsignedChar](UnsafeBufferPointer<CUnsignedChar>(start: (exponent as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: exponent.count), count: exponent.count / MemoryLayout<CUnsignedChar>.size)) // Make sure modulus starts with a 0x00 if let prefix = modulusBytes.first, prefix != 0x00 { modulusBytes.insert(0x00, at: 0) } // Lengths let modulusLengthOctets = modulusBytes.count.encodedOctets() let exponentLengthOctets = exponentBytes.count.encodedOctets() // Total length is the sum of components + types let totalLengthOctets = (modulusLengthOctets.count + modulusBytes.count + exponentLengthOctets.count + exponentBytes.count + 2).encodedOctets() // Combine the two sets of data into a single container var builder: [CUnsignedChar] = [] let data = NSMutableData() // Container type and size builder.append(0x30) builder.append(contentsOf: totalLengthOctets) data.append(builder, length: builder.count) builder.removeAll(keepingCapacity: false) // Modulus builder.append(0x02) builder.append(contentsOf: modulusLengthOctets) data.append(builder, length: builder.count) builder.removeAll(keepingCapacity: false) data.append(modulusBytes, length: modulusBytes.count) // Exponent builder.append(0x02) builder.append(contentsOf: exponentLengthOctets) data.append(builder, length: builder.count) data.append(exponentBytes, length: exponentBytes.count) self = Data(referencing: data) } func dataByStrippingX509Header() -> Data { var bytes = [CUnsignedChar](repeating: 0, count: self.count) (self as NSData).getBytes(&bytes, length: self.count) var range = NSRange(location: 0, length: self.count) var offset = 0 // ASN.1 Sequence if bytes[offset] == 0x30 { offset += 1 // Skip over length let _ = NSInteger(octetBytes: bytes, startIdx: &offset) let OID: [CUnsignedChar] = [0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00] let slice: [CUnsignedChar] = Array(bytes[offset..<(offset + OID.count)]) if slice == OID { offset += OID.count // Type if bytes[offset] != 0x03 { return self } offset += 1 // Skip over the contents length field let _ = NSInteger(octetBytes: bytes, startIdx: &offset) // Contents should be separated by a null from the header if bytes[offset] != 0x00 { return self } offset += 1 range.location += offset range.length -= offset } else { return self } } return self.subdata(in: range.toRange()!) } }
gpl-3.0
6c0a12d3abad3798a686a7a79acce1ce
31.84466
233
0.60203
4.685596
false
false
false
false
daodaoliang/actor-platform
actor-apps/app-ios/ActorSwift/Views.swift
5
949
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation extension UIView { func hideView() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.alpha = 0 }) } func showView() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.alpha = 1 }) } } class UIViewMeasure { class func measureText(text: String, width: CGFloat, fontSize: CGFloat) -> CGFloat { var style = NSMutableParagraphStyle(); style.lineBreakMode = NSLineBreakMode.ByWordWrapping; var rect = text.boundingRectWithSize(CGSize(width: width - 2, height: 10000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(fontSize), NSParagraphStyleAttributeName: style], context: nil); return CGFloat(ceil(rect.height)) } }
mit
32ca02aaf9c603de22d92e4b7dbc9b15
29.645161
119
0.631191
4.721393
false
false
false
false
ivanbruel/SwipeIt
SwipeIt/Models/Enums/SubredditType.swift
1
421
// // SubredditType.swift // Reddit // // Created by Ivan Bruel on 26/04/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation enum SubredditType: String { case Public = "public" case Private = "private" case Restricted = "restricted" case GoldRestricted = "gold_restricted" case GoldOnly = "gold_only" case Archived = "archived" case EmployeesOnly = "employees_only" }
mit
11fac8a546cc832e65ba5fdb249a3a84
19
57
0.695238
3.5
false
false
false
false
ShengHuaWu/StompClient
StompClient/StompClient.swift
1
6841
// // StompClient.swift // Surveillance // // Created by ShengHua Wu on 3/23/16. // Copyright © 2016 nogle. All rights reserved. // import UIKit import Starscream public protocol StompClientDelegate: NSObjectProtocol { func stompClientDidConnected(_ client: StompClient) func stompClient(_ client: StompClient, didErrorOccurred error: NSError) func stompClient(_ client: StompClient, didReceivedData data: Data, fromDestination destination: String) } public final class StompClient { // MARK: - Public Properties public weak var delegate: StompClientDelegate? public var isConnected: Bool { return socket.isConnected } // MARK: - Private Properties private var socket: WebSocketProtocol // MARK: - Designated Initializer init(socket: WebSocketProtocol) { self.socket = socket self.socket.delegate = self } // MARK: - Convenience Initializer public convenience init(url: URL) { let socket = WebSocket(url: url) self.init(socket: socket) } // MARK: - Public Methods public func setValue(_ value: String, forHeaderField field: String) { socket.headers[field] = value } public func connect() { socket.connect() } public func disconnect() { sendDisconnect() socket.disconnect(0.0) } public func subscribe(_ destination: String, parameters: [String : String]? = nil) -> String { let id = "sub-" + Int(arc4random_uniform(1000)).description var headers: Set<StompHeader> = [.destinationId(id: id), .destination(path: destination)] if let params = parameters , !params.isEmpty { for (key, value) in params { headers.insert(.custom(key: key, value: value)) } } let frame = StompFrame(command: .subscribe, headers: headers) sendFrame(frame) return id } public func unsubscribe(_ destination: String, destinationId: String) { let headers: Set<StompHeader> = [.destinationId(id: destinationId), .destination(path: destination)] let frame = StompFrame(command: .unsubscribe, headers: headers) sendFrame(frame) } // MARK: - Private Methods fileprivate func sendConnect() { let headers: Set<StompHeader> = [.acceptVersion(version: "1.1"), .heartBeat(value: "10000,10000")] let frame = StompFrame(command: .connect, headers: headers) sendFrame(frame) } private func sendDisconnect() { let frame = StompFrame(command: .disconnect) sendFrame(frame) } private func sendFrame(_ frame: StompFrame) { let data = try! JSONSerialization.data(withJSONObject: [frame.description], options: JSONSerialization.WritingOptions(rawValue: 0)) let string = String(data: data, encoding: String.Encoding.utf8)! // Because STOMP is a message convey protocol, // only -websocketDidReceiveMessage method will be called, // and we MUST use -writeString method to pass messages. socket.writeString(string) } } // MARK: - Websocket Delegate extension StompClient: WebSocketDelegate { public func websocketDidConnect(socket: WebSocket) { // We should wait for server response an open type frame. } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { if let error = error { delegate?.stompClient(self, didErrorOccurred: error) } } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { var mutableText = text let firstCharacter = mutableText.remove(at: mutableText.startIndex) do { // Parse response type from the first character let type = try StompResponseType(character: firstCharacter) if type == .Open { sendConnect() return } else if type == .HeartBeat { // TODO: Send heart-beat back to server. return } // Parse frame from the remaining text let frame = try StompFrame(text: mutableText) switch frame.command { case .connected: delegate?.stompClientDidConnected(self) case .message: guard let data = frame.body?.data(using: String.Encoding.utf8) else { return } delegate?.stompClient(self, didReceivedData: data, fromDestination: frame.destination) case .error: let error = NSError(domain: "com.shenghuawu.error", code: 999, userInfo: [NSLocalizedDescriptionKey : frame.message]) delegate?.stompClient(self, didErrorOccurred: error) default: break } } catch let error as NSError { delegate?.stompClient(self, didErrorOccurred: error) } } public func websocketDidReceiveData(socket: WebSocket, data: Data) { // This delegate will NOT be called, since STOMP is a message convey protocol. } } // MARK: - Extensions extension URL { func appendServerIdAndSessionId() -> URL { let serverId = Int(arc4random_uniform(1000)).description let sessionId = String.randomAlphaNumericString(8) var path = (serverId as NSString).appendingPathComponent(sessionId) path = (path as NSString).appendingPathComponent("websocket") return self.appendingPathComponent(path) } } extension String { static func randomAlphaNumericString(_ length: Int) -> String { let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let allowedCharsCount = UInt32(allowedChars.characters.count) var randomString = "" for _ in (0 ..< length) { let randomNum = Int(arc4random_uniform(allowedCharsCount)) let newCharacter = allowedChars[allowedChars.characters.index(allowedChars.startIndex, offsetBy: randomNum)] randomString += String(newCharacter) } return randomString } } public protocol WebSocketProtocol { weak var delegate: WebSocketDelegate? { get set } var headers: [String : String] { get set } var isConnected: Bool { get } func connect() func disconnect(_ forceTimeout: TimeInterval?) func writeString(_ str: String) } extension WebSocket: WebSocketProtocol { public func disconnect(_ forceTimeout: TimeInterval?) { disconnect(forceTimeout: forceTimeout) } public func writeString(_ str: String) { write(string: str, completion: nil) } }
mit
720acb32419d0ed6f68a1303bdc150df
31.884615
139
0.625146
4.810127
false
false
false
false
kkapitan/CappsoftKit
CappsoftKit/Classes/Provider.swift
1
1565
// // Provider.swift // Pods // // Created by Krzysztof Kapitan on 23.12.2016. // // import Foundation public class Provider<Fetcher : DataFetchable> : DataProvidable { public typealias Element = Fetcher.Element fileprivate(set) public var items: [Element]? let fetcher: Fetcher public init(fetcher: Fetcher) { self.items = [] self.fetcher = fetcher } public func loadItems(completion: @escaping (ItemsFetchingResult<Element>) -> ()) { fetcher.fetchItems { [weak self] result in if case .success(let newItems) = result { guard let items = self?.items else { return } self?.items = Array(items.dropLast(newItems.count)) self?.items?.append(contentsOf: newItems) } completion(result) } } } public extension Provider where Fetcher: PagedDataFetchable { func loadMore(completion: @escaping ItemsFetchingCompletion<Element>) { fetcher.fetchNext { [weak self] result in if case .success(let newItems) = result { self?.items?.append(contentsOf: newItems) } completion(result) } } func loadFirst(completion: @escaping ItemsFetchingCompletion<Element>) { fetcher.fetchFirst { [weak self] result in if case .success(let newItems) = result { self?.items = newItems } completion(result) } } }
mit
2fe0281bcae3f28c04715eda8add5585
26.45614
87
0.567412
4.771341
false
false
false
false
SD10/SwifterSwift
Tests/SwifterSwiftTests/CocoaExtensionsTests/CLLocationExtensionsTests.swift
2
1192
// // CLLocationExtensionsTests.swift // SwifterSwift // // Created by Luciano Almeida on 21/04/17. // Copyright © 2017 omaralbeik. All rights reserved. // import XCTest import CoreLocation class CLLocationExtensionsTests: XCTestCase { func testMidLocation() { let a = CLLocation(latitude: -15.822877, longitude: -47.941839) let b = CLLocation(latitude: -15.692030, longitude: -47.594397) let mid = CLLocation.midLocation(start: a, end: b) XCTAssertEqualWithAccuracy(mid.coordinate.latitude, -15.7575223324019, accuracy: 0.0000000000001) XCTAssertEqualWithAccuracy(mid.coordinate.longitude, -47.7680620274339, accuracy: 0.0000000000001) XCTAssertEqualWithAccuracy(a.midLocation(to: b).coordinate.latitude, -15.7575223324019, accuracy: 0.0000000000001) XCTAssertEqualWithAccuracy(a.midLocation(to: b).coordinate.longitude, -47.7680620274339, accuracy: 0.0000000000001) } func testBearing() { let a = CLLocation(latitude: 38.6318909290283, longitude: -90.2828979492187) let b = CLLocation(latitude: 38.5352759115441, longitude: -89.8448181152343) let bearing = a.bearing(to: b) XCTAssertEqualWithAccuracy(bearing, 105.619, accuracy: 0.001) } }
mit
c02bb5e2d3cdb3e893edd3fdbace3ed4
33.028571
117
0.759026
3.402857
false
true
false
false
Stamates/30-Days-of-Swift
src/Day 20 - Scroll View/Day 20 - Scroll View/ViewController.swift
2
2269
// // ViewController.swift // Day 20 - Scroll View // // Created by Justin Mitchel on 11/25/14. // Copyright (c) 2014 Coding For Entrepreneurs. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label1 = UILabel(frame: CGRectMake(10, 50, self.view.frame.width-20, 50)) label1.text = "Hi there" label1.backgroundColor = UIColor.blackColor() label1.textColor = UIColor.whiteColor() let label2 = UILabel(frame: CGRectMake(10, 120, self.view.frame.width-20, 50)) label2.text = "Label 2" label2.backgroundColor = UIColor.blackColor() label2.textColor = UIColor.whiteColor() let label3 = UILabel(frame: CGRectMake(10, 920, self.view.frame.width-20, 50)) label3.text = "Label 2" label3.backgroundColor = UIColor.blackColor() label3.textColor = UIColor.whiteColor() let scrollView2 = UIScrollView(frame: CGRectMake(0, 970, self.view.frame.width, 100)) let label4 = UILabel(frame: CGRectMake(10, 200, self.view.frame.width-20, 50)) label4.text = "Hello there again" label4.backgroundColor = UIColor.blackColor() label4.textColor = UIColor.whiteColor() scrollView2.contentSize = CGSize(width: self.view.frame.width, height: 300) scrollView2.backgroundColor = UIColor.greenColor() scrollView2.addSubview(label4) let scrollView = UIScrollView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)) scrollView.addSubview(label2) scrollView.addSubview(label1) scrollView.addSubview(label3) scrollView.addSubview(scrollView2) scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height * 2.0) // self.view.addSubview(label1) self.view.addSubview(scrollView) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
a6e5db2df44ebe6c8f06306aa81f4db3
33.907692
109
0.642574
4.265038
false
false
false
false
kkapitan/CappsoftKit
CappsoftKit/Classes/Page.swift
1
856
// // Page.swift // Pods // // Created by Krzysztof Kapitan on 23.12.2016. // // import Foundation public protocol PageDescriptor: Equatable { var index: Int { get } var limit: Int { get } static var next: (Self) -> Self { get } static var first: (Self) -> Self { get } } public struct Page: PageDescriptor { public let index: Int public let limit: Int public static var next = { (page: Page) in return Page(index: page.index + 1, limit: page.limit) } public static var first = { (page: Page) in return Page(index: 1, limit: page.limit) } public init(index: Int, limit: Int) { self.index = index self.limit = limit } } extension Page: Equatable { public static func == (lhs: Page, rhs: Page) -> Bool { return lhs.index == rhs.index; } }
mit
08369c7b084dc96d8e8283b6113f3926
19.878049
61
0.586449
3.551867
false
false
false
false
eoger/firefox-ios
XCUITests/PrivateBrowsingTest.swift
2
11303
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest let url1 = "www.mozilla.org" let url2 = "www.facebook.com" let url1Label = "Internet for people, not profit — Mozilla" let url2Label = "Facebook - Log In or Sign Up" class PrivateBrowsingTest: BaseTestCase { func testPrivateTabDoesNotTrackHistory() { navigator.openURL(url1) navigator.goto(BrowserTabMenu) // Go to History screen waitforExistence(app.tables.cells["History"]) app.tables.cells["History"].tap() navigator.nowAt(BrowserTab) waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) // History without counting Recently Closed and Synced devices let history = app.tables["History List"].cells.count - 2 XCTAssertEqual(history, 1, "History entries in regular browsing do not match") // Go to Private browsing to open a website and check if it appears on History navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url2) waitForValueContains(app.textFields["url"], value: "facebook") navigator.goto(BrowserTabMenu) waitforExistence(app.tables.cells["History"]) app.tables.cells["History"].tap() waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) XCTAssertFalse(app.tables["History List"].staticTexts[url2Label].exists) // Open one tab in private browsing and check the total number of tabs let privateHistory = app.tables["History List"].cells.count - 2 XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match") } func testTabCountShowsOnlyNormalOrPrivateTabCount() { // Open two tabs in normal browsing and check the number of tabs open navigator.openNewURL(urlString: url1) waitUntilPageLoad() navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url1Label]) let numTabs = userState.numTabs XCTAssertEqual(numTabs, 2, "The number of regular tabs is not correct") // Open one tab in private browsing and check the total number of tabs navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.goto(URLBarOpen) waitUntilPageLoad() navigator.openURL(url2) waitForValueContains(app.textFields["url"], value: "facebook") navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url2Label]) let numPrivTabs = userState.numTabs XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct") // Go back to regular mode and check the total number of tabs navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode) waitforExistence(app.collectionViews.cells[url1Label]) waitforNoExistence(app.collectionViews.cells[url2Label]) let numRegularTabs = userState.numTabs XCTAssertEqual(numRegularTabs, 2, "The number of regular tabs is not correct") } func testClosePrivateTabsOptionClosesPrivateTabs() { // Check that Close Private Tabs when closing the Private Browsing Button is off by default navigator.goto(SettingsScreen) let settingsTableView = app.tables["AppSettingsTableViewController.tableView"] while settingsTableView.staticTexts["Close Private Tabs"].exists == false { settingsTableView.swipeUp() } let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"] XCTAssertFalse(closePrivateTabsSwitch.isSelected) // Open a Private tab navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url1) // Go back to regular browser navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode) // Go back to private browsing and check that the tab has not been closed navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) waitforExistence(app.collectionViews.cells[url1Label]) checkOpenTabsBeforeClosingPrivateMode() // Now the enable the Close Private Tabs when closing the Private Browsing Button app.collectionViews.cells[url1Label].tap() navigator.nowAt(BrowserTab) navigator.goto(SettingsScreen) closePrivateTabsSwitch.tap() navigator.goto(BrowserTab) // Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) waitforNoExistence(app.collectionViews.cells[url1Label]) checkOpenTabsAfterClosingPrivateMode() } private func checkOpenTabsBeforeClosingPrivateMode() { let numPrivTabs = userState.numTabs XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed") } private func checkOpenTabsAfterClosingPrivateMode() { let numPrivTabsAfterClosing = userState.numTabs XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed") XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") } private func enableClosePrivateBrowsingOptionWhenLeaving() { navigator.goto(SettingsScreen) print(app.debugDescription) let settingsTableView = app.tables["AppSettingsTableViewController.tableView"] while settingsTableView.staticTexts["Close Private Tabs"].exists == false { settingsTableView.swipeUp() } let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"] closePrivateTabsSwitch.tap() } // This test is only enabled for iPad. Shortcut does not exists on iPhone func testClosePrivateTabsOptionClosesPrivateTabsShortCutiPad() { navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) navigator.openURL(url1) enableClosePrivateBrowsingOptionWhenLeaving() // Leave PM by tapping on PM shourt cut navigator.goto(NewTabScreen) navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) checkOpenTabsAfterClosingPrivateMode() } func testClosePrivateTabsOptionClosesPrivateTabsDirectlyFromTabTray() { // See scenario described in bug 1434545 for more info about this scenario enableClosePrivateBrowsingOptionWhenLeaving() navigator.openURL(urlExample) app.webViews.links.staticTexts["More information..."].press(forDuration: 3) app.buttons["Open in New Private Tab"].tap() waitUntilPageLoad() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) // Check there is one tab navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode) checkOpenTabsBeforeClosingPrivateMode() navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) checkOpenTabsAfterClosingPrivateMode() } func testPrivateBrowserPanelView() { // If no private tabs are open, there should be a initial screen with label Private Browsing navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") let numPrivTabsFirstTime = userState.numTabs XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet") // If a private tab is open Private Browsing screen is not shown anymore navigator.goto(BrowserTab) //Wait until the page loads and go to regular browser waitUntilPageLoad() navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateMode) // Go back to private browsing navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) waitforNoExistence(app.staticTexts["Private Browsing"]) XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is shown") let numPrivTabsOpen = userState.numTabs XCTAssertEqual(numPrivTabsOpen, 1, "The number of tabs is not correct, there should be one private tab") } func testiPadDirectAccessPrivateMode() { navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) // A Tab opens directly in HomePanels view XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") // Open website and check it does not appear under history once going back to regular mode navigator.openURL("http://example.com") waitUntilPageLoad() // This action to enable private mode is defined on HomePanel Screen that is why we need to open a new tab and be sure we are on that screen to use the correct action navigator.goto(NewTabScreen) navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel) navigator.goto(HomePanel_History) waitforExistence(app.tables["History List"]) // History without counting Recently Closed and Synced devices let history = app.tables["History List"].cells.count - 2 XCTAssertEqual(history, 0, "History list should be empty") } func testiPadDirectAccessPrivateModeBrowserTab() { navigator.openURL("www.mozilla.org") navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab) // A Tab opens directly in HomePanels view XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") // Open website and check it does not appear under history once going back to regular mode navigator.openURL("http://example.com") navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab) navigator.browserPerformAction(.openHistoryOption) waitforExistence(app.tables["History List"]) // History without counting Recently Closed and Synced devices let history = app.tables["History List"].cells.count - 2 XCTAssertEqual(history, 1, "There should be one entry in History") let savedToHistory = app.tables["History List"].cells.staticTexts[url1Label] waitforExistence(savedToHistory) XCTAssertTrue(savedToHistory.exists) } }
mpl-2.0
f9d4062064c04243b48060ea7d9fba54
47.089362
175
0.723122
5.186324
false
true
false
false
dbahat/conventions-ios
Conventions/Conventions/externals/CardView/CardView.swift
1
1978
// // The MIT License (MIT) // // Copyright (c) 2014 Andrew Clissold // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit @IBDesignable class CardView: UIView { @IBInspectable var cornerRadius: CGFloat = 2 @IBInspectable var shadowOffsetWidth: Int = 0 @IBInspectable var shadowOffsetHeight: Int = 3 @IBInspectable var shadowColor: UIColor? = UIColor.black @IBInspectable var shadowOpacity: Float = 0.5 override func layoutSubviews() { layer.cornerRadius = cornerRadius let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) layer.masksToBounds = false layer.shadowColor = shadowColor?.cgColor layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight); layer.shadowOpacity = shadowOpacity layer.shadowPath = shadowPath.cgPath } }
apache-2.0
4a3083e1b22c7c054dc9e431ef0e7cec
41.085106
90
0.714863
4.82439
false
false
false
false
TBXark/TKSwitcherCollection
TKSwitcherCollection/TKSmileSwitch.swift
1
6054
// // SmileSwitch.swift // SwitcherCollection // // Created by Tbxark on 15/10/25. // Copyright © 2015年 TBXark. All rights reserved. // import UIKit // Dedign by Oleg Frolov //https://dribbble.com/shots/2011284-Switcher-ll open class TKSmileSwitch: TKBaseSwitch { // MARK: - Poperty private var smileFace: TKSmileFaceView? // MARK: - Init override internal func setUpView() { super.setUpView() let frame = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height) smileFace = TKSmileFaceView(frame: frame) addSubview(smileFace!) } override open func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() let lineWidth = 10 * sizeScale let path = UIBezierPath(roundedRect: rect.insetBy(dx: lineWidth, dy: lineWidth), cornerRadius: rect.width/2) ctx?.setLineWidth(lineWidth*2) ctx?.addPath(path.cgPath) UIColor(white: 0.9, alpha: 1).setStroke() ctx?.strokePath() } override func changeValueAnimate(_ value: Bool, duration: Double) { let x = value ? 0 : (bounds.width - bounds.height) let frame = CGRect(x: x, y: 0, width: bounds.height, height: bounds.height) self.smileFace!.faceType = value ? TKSmileFaceView.FaceType.happy : TKSmileFaceView.FaceType.sad self.smileFace?.rotation(animateDuration, count: 2, clockwise: !isOn) UIView.animate(withDuration: duration, animations: { () -> Void in self.smileFace?.frame = frame }, completion: { (complete) -> Void in if complete { self.smileFace?.eyeWinkAnimate(duration/2) } }) } } // 脸 private class TKSmileFaceView: UIView { enum FaceType { case happy case sad func toColor() -> UIColor { switch self { case .happy: return UIColor(red: 0.388, green: 0.839, blue: 0.608, alpha: 1.000) case .sad: return UIColor(red: 0.843, green: 0.369, blue: 0.373, alpha: 1) } } } // MARK: - Property let rightEye: CAShapeLayer = CAShapeLayer() let leftEye: CAShapeLayer = CAShapeLayer() let mouth: CAShapeLayer = CAShapeLayer() let face: CAShapeLayer = CAShapeLayer() var faceType: FaceType = .happy { didSet { let position: CGFloat = isHappy ? 20 * sizeScale : 35 * sizeScale mouth.path = mouthPath.cgPath mouth.frame = CGRect(x: 0, y: position, width: 60 * sizeScale, height: 20 * sizeScale) face.fillColor = faceType.toColor().cgColor } } // MARK: - Getter var isHappy: Bool { return (faceType == .happy) } var sizeScale: CGFloat { return min(self.bounds.width, self.bounds.height)/100.0 } var mouthPath: UIBezierPath { get { let point: CGFloat = isHappy ? 70 * sizeScale : 10 let path = UIBezierPath() path.move(to: CGPoint(x: 30 * sizeScale, y: 40 * sizeScale)) path.addCurve(to: CGPoint(x: 70 * sizeScale, y: 40 * sizeScale), controlPoint1: CGPoint(x: 30 * sizeScale, y: 40 * sizeScale), controlPoint2: CGPoint(x: 50 * sizeScale, y: point)) path.lineCapStyle = .round return path } } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) self.setupLayers() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupLayers() } // MARK: - Private Func private func setupLayers() { let facePath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100 * sizeScale, height: 100 * sizeScale)) let eyePath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 20 * sizeScale, height: 20 * sizeScale)) face.frame = CGRect(x: 0, y: 0, width: 100 * sizeScale, height: 100 * sizeScale) face.path = facePath.cgPath face.fillColor = faceType.toColor().cgColor layer.addSublayer(face) leftEye.frame = CGRect(x: 20 * sizeScale, y: 28 * sizeScale, width: 10 * sizeScale, height: 10 * sizeScale) leftEye.path = eyePath.cgPath leftEye.fillColor = UIColor.white.cgColor layer.addSublayer(leftEye) rightEye.frame = CGRect(x: 60 * sizeScale, y: 28 * sizeScale, width: 10 * sizeScale, height: 10 * sizeScale) rightEye.path = eyePath.cgPath rightEye.fillColor = UIColor.white.cgColor layer.addSublayer(rightEye) mouth.path = mouthPath.cgPath mouth.strokeColor = UIColor.white.cgColor mouth.fillColor = UIColor.clear.cgColor mouth.lineCap = "round" mouth.lineWidth = 10 * sizeScale layer.addSublayer(mouth) faceType = .happy } // MARK: - Animate func eyeWinkAnimate(_ duration: Double) { let eyeleftTransformAnim = CAKeyframeAnimation(keyPath: "transform") eyeleftTransformAnim.values = [NSValue(caTransform3D: CATransform3DIdentity), NSValue(caTransform3D: CATransform3DMakeScale(1, 0.1, 1)), NSValue(caTransform3D: CATransform3DIdentity) ] eyeleftTransformAnim.keyTimes = [0, 0.5, 1] eyeleftTransformAnim.duration = duration leftEye.add(eyeleftTransformAnim, forKey: "Wink") rightEye.add(eyeleftTransformAnim, forKey: "Wink") } func rotation(_ duration: Double, count: Int, clockwise: Bool) { let rotationTransformAnim = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotationTransformAnim.values = [0, 180 * CGFloat.pi/180 * CGFloat(count) * (clockwise ? 1 : -1)] rotationTransformAnim.keyTimes = [0, 1] rotationTransformAnim.isRemovedOnCompletion = false rotationTransformAnim.duration = duration layer.add(rotationTransformAnim, forKey: "Rotation") } }
mit
d84670304c7fd7b4d9f1b6980d988af4
34.582353
191
0.607704
4.14599
false
false
false
false
blokadaorg/blokada
ios/App/Service/PersistenceService.swift
1
6314
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Kar // import Foundation import Combine protocol PersistenceService { func getString(forKey: String) -> AnyPublisher<String, Error> func setString(_ value: String, forKey: String) -> AnyPublisher<Ignored, Error> func delete(forKey: String) -> AnyPublisher<Ignored, Error> func getBool(forKey: String) -> AnyPublisher<Bool, Error> func setBool(_ value: Bool, forKey: String) -> AnyPublisher<Ignored, Error> } class LocalStoragePersistenceService: PersistenceService { private let localStorage = UserDefaults.standard func getString(forKey: String) -> AnyPublisher<String, Error> { return Just(true) .tryMap { _ in guard let it = self.localStorage.string(forKey: forKey) else { throw CommonError.emptyResult } return it } .eraseToAnyPublisher() } func setString(_ value: String, forKey: String) -> AnyPublisher<Ignored, Error> { return Just(value) .tryMap { value in self.localStorage.set(value, forKey: forKey) } .map { _ in true } .eraseToAnyPublisher() } func delete(forKey: String) -> AnyPublisher<Ignored, Error> { return Just(true) .tryMap { value in self.localStorage.removeObject(forKey: forKey) } .map { _ in true } .eraseToAnyPublisher() } func getBool(forKey: String) -> AnyPublisher<Bool, Error> { return Just(true) .tryMap { _ in self.localStorage.bool(forKey: forKey) } .eraseToAnyPublisher() } func setBool(_ value: Bool, forKey: String) -> AnyPublisher<Ignored, Error> { return Just(value) .tryMap { value in self.localStorage.set(value, forKey: forKey) } .map { _ in true } .eraseToAnyPublisher() } } class ICloudPersistenceService: PersistenceService { private let iCloud = NSUbiquitousKeyValueStore() func getString(forKey: String) -> AnyPublisher<String, Error> { return Just(true) .tryMap { _ in guard let it = self.iCloud.string(forKey: forKey) else { throw CommonError.emptyResult } return it } .eraseToAnyPublisher() } func setString(_ value: String, forKey: String) -> AnyPublisher<Ignored, Error> { return Just(value) .tryMap { value in self.iCloud.set(value, forKey: forKey) self.iCloud.synchronize() } .map { _ in true } .eraseToAnyPublisher() } func delete(forKey: String) -> AnyPublisher<Ignored, Error> { return Just(true) .tryMap { value in self.iCloud.removeObject(forKey: forKey) self.iCloud.synchronize() } .map { _ in true } .eraseToAnyPublisher() } func getBool(forKey: String) -> AnyPublisher<Bool, Error> { return Just(true) .tryMap { _ in self.iCloud.bool(forKey: forKey) } .eraseToAnyPublisher() } func setBool(_ value: Bool, forKey: String) -> AnyPublisher<Ignored, Error> { return Just(value) .tryMap { value in self.iCloud.set(value, forKey: forKey) self.iCloud.synchronize() } .map { _ in true } .eraseToAnyPublisher() } } class KeychainPersistenceService: PersistenceService { private let keychain = KeychainSwift() init() { keychain.synchronizable = true } func getString(forKey: String) -> AnyPublisher<String, Error> { return Just(true) .tryMap { _ in guard let it = self.keychain.get(forKey) else { throw CommonError.emptyResult } return it } .eraseToAnyPublisher() } func setString(_ value: String, forKey: String) -> AnyPublisher<Ignored, Error> { return Fail(error: "KeychainPersistenceService is a legacy persistence, do not save to it") .eraseToAnyPublisher() } func delete(forKey: String) -> AnyPublisher<Ignored, Error> { return Fail(error: "KeychainPersistenceService is a legacy persistence, do not delete from it") .eraseToAnyPublisher() } func getBool(forKey: String) -> AnyPublisher<Bool, Error> { return Fail(error: "KeychainPersistenceService is a legacy persistence, does not read booleans") .eraseToAnyPublisher() } func setBool(_ value: Bool, forKey: String) -> AnyPublisher<Ignored, Error> { return Fail(error: "KeychainPersistenceService is a legacy persistence, does not save booleans") .eraseToAnyPublisher() } } class PersistenceServiceMock: PersistenceService { var mockGetString: (String) -> AnyPublisher<String, Error> = { forKey in return Fail<String, Error>(error: CommonError.emptyResult) .eraseToAnyPublisher() } func getString(forKey: String) -> AnyPublisher<String, Error> { return mockGetString(forKey) } func setString(_ value: String, forKey: String) -> AnyPublisher<Ignored, Error> { return Deferred { () -> AnyPublisher<Ignored, Error> in return Just(true).setFailureType(to: Error.self).eraseToAnyPublisher() } .eraseToAnyPublisher() } func delete(forKey: String) -> AnyPublisher<Ignored, Error> { return Deferred { () -> AnyPublisher<Ignored, Error> in return Just(true).setFailureType(to: Error.self).eraseToAnyPublisher() } .eraseToAnyPublisher() } func getBool(forKey: String) -> AnyPublisher<Bool, Error> { return Fail<Bool, Error>(error: CommonError.emptyResult) .eraseToAnyPublisher() } func setBool(_ value: Bool, forKey: String) -> AnyPublisher<Ignored, Error> { return Deferred { () -> AnyPublisher<Ignored, Error> in return Just(true).setFailureType(to: Error.self).eraseToAnyPublisher() } .eraseToAnyPublisher() } }
mpl-2.0
2842ef62474e01fb6ad97c57343ab824
30.723618
104
0.621575
4.544996
false
false
false
false
luispadron/GradePoint
GradePoint/Controllers/Settings/GradePointPremium/GPPPageViewController.swift
1
4249
// // GPPPageViewController.swift // GradePoint // // Created by Luis Padron on 1/31/18. // Copyright © 2018 Luis Padron. All rights reserved. // import UIKit class GPPPageViewController: UIPageViewController { private(set) lazy var onboardControllers: [UIViewController] = { return [ self.newOnboardingControlled(named: "GPPOnboarding1"), self.newOnboardingControlled(named: "GPPOnboarding3"), self.newOnboardingControlled(named: "GPPOnboarding4"), self.newOnboardingControlled(named: "GPPOnboarding5"), ] }() private var oldBackgroundColor: UIColor? private var backgroundColor: UIColor? { didSet { self.oldBackgroundColor = oldValue self.view.backgroundColor = self.backgroundColor } } // MARK: View controller life cycle override func viewDidLoad() { super.viewDidLoad() self.dataSource = self self.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let firstVc = self.onboardControllers.first { self.setViewControllers([firstVc], direction: .forward, animated: true, completion: nil) self.view.backgroundColor = firstVc.view.backgroundColor?.lighter(by: 10) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.setNeedsStatusBarAppearanceUpdate() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: Helpers private func newOnboardingControlled(named: String) -> UIViewController { return UIStoryboard(name: "GradePointPremium", bundle: nil).instantiateViewController(withIdentifier: named) } } // MARK: PageViewController DataSource & Delegate extension GPPPageViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = onboardControllers.firstIndex(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0, onboardControllers.count > previousIndex else { return nil } return onboardControllers[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = onboardControllers.firstIndex(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 guard onboardControllers.count != nextIndex, onboardControllers.count > nextIndex else { return nil } return onboardControllers[nextIndex] } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard let toVc = pendingViewControllers.first else { return } UIView.animate(withDuration: 0.2) { self.backgroundColor = toVc.view.backgroundColor?.lighter(by: 10) } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if finished && !completed { UIView.animate(withDuration: 0.15) { self.backgroundColor = self.oldBackgroundColor } } } func pageViewControllerSupportedInterfaceOrientations(_ pageViewController: UIPageViewController) -> UIInterfaceOrientationMask { return .portrait } func presentationCount(for pageViewController: UIPageViewController) -> Int { return self.onboardControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let firstVc = self.onboardControllers.first, let firstIndex = self.onboardControllers.firstIndex(of: firstVc) else { return 0 } return firstIndex } }
apache-2.0
0760e45baa94600defc8bc7af521e846
33.819672
149
0.695386
5.560209
false
false
false
false
frootloops/swift
test/Parse/errors.swift
3
5258
// RUN: %target-typecheck-verify-swift enum MSV : Error { case Foo, Bar, Baz case CarriesInt(Int) var _domain: String { return "" } var _code: Int { return 0 } } func opaque_error() -> Error { return MSV.Foo } func one() { do { true ? () : throw opaque_error() // expected-error {{expected expression after '? ... :' in ternary expression}} } catch _ { } do { } catch { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } do { } catch where true { // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} let error2 = error } catch { } // <rdar://problem/20985280> QoI: improve diagnostic on improper pattern match on type do { throw opaque_error() } catch MSV { // expected-error {{'is' keyword required to pattern match against type name}} {{11-11=is }} } catch { } do { throw opaque_error() } catch is Error { // expected-warning {{'is' test is always true}} } func foo() throws {} do { #if false try foo() #endif } catch { // don't warn, #if code should be scanned. } do { #if false throw opaque_error() #endif } catch { // don't warn, #if code should be scanned. } } func takesAutoclosure(_ fn : @autoclosure () -> Int) {} func takesThrowingAutoclosure(_ fn : @autoclosure () throws -> Int) {} func genError() throws -> Int { throw MSV.Foo } func genNoError() -> Int { return 0 } func testAutoclosures() throws { takesAutoclosure(genError()) // expected-error {{call can throw, but it is not marked with 'try' and it is executed in a non-throwing autoclosure}} takesAutoclosure(genNoError()) try takesAutoclosure(genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} try takesAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesAutoclosure(try genError()) // expected-error {{call can throw, but it is executed in a non-throwing autoclosure}} takesAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(try genError()) takesThrowingAutoclosure(try genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} try takesThrowingAutoclosure(genError()) try takesThrowingAutoclosure(genNoError()) // expected-warning {{no calls to throwing functions occur within 'try' expression}} takesThrowingAutoclosure(genError()) // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{28-28=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{28-28=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{28-28=try! }} takesThrowingAutoclosure(genNoError()) } struct IllegalContext { var x: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} func foo(_ x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}} func catcher() throws { do { _ = try genError() } catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}} } catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} } } } func illformed() throws { do { _ = try genError() } catch MSV.CarriesInt(let i) where i == genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} expected-error {{expected '{'}} } } func postThrows() -> Int throws { // expected-error{{'throws' may only occur before '->'}}{{19-19=throws }}{{25-32=}} return 5 } func postThrows2() -> throws Int { // expected-error{{'throws' may only occur before '->'}}{{20-22=throws}}{{23-29=->}} return try postThrows() } func postRethrows(_ f: () throws -> Int) -> Int rethrows { // expected-error{{'rethrows' may only occur before '->'}}{{42-42=rethrows }}{{48-57=}} return try f() } func postRethrows2(_ f: () throws -> Int) -> rethrows Int { // expected-error{{'rethrows' may only occur before '->'}}{{43-45=rethrows}}{{46-54=->}} return try f() } func incompleteThrowType() { // FIXME: Bad recovery for incomplete function type. let _: () throws // expected-error @-1 {{consecutive statements on a line must be separated by ';'}} // expected-error @-2 {{expected expression}} } // rdar://21328447 func fixitThrow0() throw {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow1() throw -> Int {} // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{20-25=throws}} func fixitThrow2() throws { var _: (Int) throw MSV.Foo var _: (Int) throw -> Int // expected-error{{expected throwing specifier; did you mean 'throws'?}} {{16-21=throws}} }
apache-2.0
e86aa9708750c76da91fbf84633fbfe2
36.29078
188
0.6531
4.111024
false
false
false
false
seuzl/iHerald
Herald/SRTPViewController.swift
1
5182
// // SRTPViewController.swift // 先声 // // Created by Wangshuo on 14-9-4. // Copyright (c) 2014年 WangShuo. All rights reserved. // import UIKit class SRTPViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,APIGetter { @IBOutlet var stuIDLabel: UILabel! @IBOutlet var totalCreditLabel: UILabel! @IBOutlet var levelLabel: UILabel! @IBOutlet var tableView: UITableView! var dataList:NSArray = [] var API = HeraldAPI() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationItem.title = "SRTP详情" let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: Selector("refreshData")) self.navigationItem.rightBarButtonItem = refreshButton let initResult = Tool.initNavigationAPI(self) if initResult{ Tool.showProgressHUD("正在查询SRTP信息") self.API.delegate = self API.sendAPI("srtp") } } override func viewWillDisappear(animated: Bool) { Tool.dismissHUD() API.cancelAllRequest() } func getResult(APIName: String, results: JSON) { Tool.showSuccessHUD("获取成功") self.dataList = results["content"].arrayObject ?? [] self.stuIDLabel.text = results["content"][0]["card number"].stringValue self.totalCreditLabel.text = results["content"][0]["total"].stringValue self.levelLabel.text = results["content"][0]["score"].stringValue self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } func getError(APIName: String, statusCode: Int) { Tool.showErrorHUD("获取数据失败") } func refreshData() { Tool.showProgressHUD("正在更新SRTP信息") API.sendAPI("srtp") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 75 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.dataList == [] { return 0 } else { return self.dataList.count - 1 } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRectMake(0, 0, 320, 30)) headerView.backgroundColor = UIColor(patternImage: UIImage(named: "SRTP_header.jpg")!) let creditLabel = UILabel(frame: CGRectMake(15, 0, 40, 30)) creditLabel.textColor = UIColor.darkGrayColor() creditLabel.font = UIFont(name: "System", size: 13) creditLabel.text = "学分" let projectLabel = UILabel(frame: CGRectMake(135, 0, 80, 30)) projectLabel.textColor = UIColor.darkGrayColor() projectLabel.font = UIFont(name: "System", size: 13) projectLabel.text = "项目" let propertyLabel = UILabel(frame: CGRectMake(255, 0, 40, 30)) propertyLabel.textColor = UIColor.darkGrayColor() propertyLabel.font = UIFont(name: "System", size: 13) propertyLabel.text = "性质" headerView.addSubview(creditLabel) headerView.addSubview(projectLabel) headerView.addSubview(propertyLabel) return headerView } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier:String = "SRTPTableViewCell" var cell: SRTPTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? SRTPTableViewCell if nil == cell { let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("SRTPTableViewCell", owner: self, options: nil) cell = nibArray.objectAtIndex(0) as? SRTPTableViewCell } let row = indexPath.row let credit = self.dataList[row+1]["credit"] as! NSString if credit.isEqualToString("") { cell?.creditLabel.text = "0.0" } else { cell?.creditLabel.text = self.dataList[row+1]["credit"] as! NSString as String } cell?.projectLabel.text = self.dataList[row+1]["project"] as? NSString as? String cell?.dateLabel.text = self.dataList[row+1]["date"] as? NSString as? String cell?.propertyLabel.text = self.dataList[row+1]["type"] as? NSString as? String cell?.projectLabel.numberOfLines = 0 cell?.projectLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping return cell! } }
mit
8ea90ed69d7398cc7d6620d09d12c88a
29.819277
142
0.609851
4.844697
false
false
false
false
dobriy-eeh/omim
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RouteManager/RouteManagerTransitioningManager.swift
1
1775
@objc(MWMRouteManagerTransitioningManager) final class RouteManagerTransitioningManager: NSObject, UIViewControllerTransitioningDelegate { private var popoverSourceView: UIView! private var permittedArrowDirections: UIPopoverArrowDirection! override init() { super.init() } init(popoverSourceView: UIView, permittedArrowDirections: UIPopoverArrowDirection) { self.popoverSourceView = popoverSourceView self.permittedArrowDirections = permittedArrowDirections super.init() } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return alternative(iPhone: { () -> UIPresentationController in return RouteManageriPhonePresentationController(presentedViewController: presented, presenting: presenting) }, iPad: { () -> UIPresentationController in let popover = RouteManageriPadPresentationController(presentedViewController: presented, presenting: presenting) popover.sourceView = self.popoverSourceView popover.sourceRect = self.popoverSourceView.bounds popover.permittedArrowDirections = self.permittedArrowDirections return popover })() } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return RouteManagerTransitioning(isPresentation: true) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return RouteManagerTransitioning(isPresentation: false) } }
apache-2.0
99d66e54e48992aeb252d37acb0867f8
45.710526
168
0.741972
6.988189
false
false
false
false
JGiola/swift-corelibs-foundation
Foundation/NSData.swift
1
43896
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif #if DEPLOYMENT_ENABLE_LIBDISPATCH import Dispatch #endif extension NSData { public struct ReadingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let mappedIfSafe = ReadingOptions(rawValue: UInt(1 << 0)) public static let uncached = ReadingOptions(rawValue: UInt(1 << 1)) public static let alwaysMapped = ReadingOptions(rawValue: UInt(1 << 2)) } public struct WritingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let atomic = WritingOptions(rawValue: UInt(1 << 0)) public static let withoutOverwriting = WritingOptions(rawValue: UInt(1 << 1)) } public struct SearchOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let backwards = SearchOptions(rawValue: UInt(1 << 0)) public static let anchored = SearchOptions(rawValue: UInt(1 << 1)) } public struct Base64EncodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let lineLength64Characters = Base64EncodingOptions(rawValue: UInt(1 << 0)) public static let lineLength76Characters = Base64EncodingOptions(rawValue: UInt(1 << 1)) public static let endLineWithCarriageReturn = Base64EncodingOptions(rawValue: UInt(1 << 4)) public static let endLineWithLineFeed = Base64EncodingOptions(rawValue: UInt(1 << 5)) } public struct Base64DecodingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ignoreUnknownCharacters = Base64DecodingOptions(rawValue: UInt(1 << 0)) } } private final class _NSDataDeallocator { var handler: (UnsafeMutableRawPointer, Int) -> Void = {_,_ in } } private let __kCFMutable: CFOptionFlags = 0x01 private let __kCFGrowable: CFOptionFlags = 0x02 private let __kCFBytesInline: CFOptionFlags = 2 private let __kCFUseAllocator: CFOptionFlags = 3 private let __kCFDontDeallocate: CFOptionFlags = 4 open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { typealias CFType = CFData private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 private var _deallocator: UnsafeMutableRawPointer? = nil // for CF only private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift private var _bytes: UnsafeMutablePointer<UInt8>? = nil internal var _cfObject: CFType { if type(of: self) === NSData.self || type(of: self) === NSMutableData.self { return unsafeBitCast(self, to: CFType.self) } else { let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) return CFDataCreate(kCFAllocatorSystemDefault, bytePtr, self.length) } } internal func _providesConcreteBacking() -> Bool { return type(of: self) === NSData.self || type(of: self) === NSMutableData.self } override open var _cfTypeID: CFTypeID { return CFDataGetTypeID() } // NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional private func _init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) { let options : CFOptionFlags = (type(of: self) == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0 let bytePtr = bytes?.bindMemory(to: UInt8.self, capacity: length) if copy { _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, bytePtr, length, false) if let handler = deallocator { handler(bytes!, length) } } else { if let handler = deallocator { _deallocHandler!.handler = handler } // The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, bytePtr, length, true) } } fileprivate init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) { super.init() _init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } public override init() { super.init() _init(bytes: nil, length: 0) } /// Initializes a data object filled with a given number of bytes copied from a given buffer. public init(bytes: UnsafeRawPointer?, length: Int) { super.init() _init(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true) } /// Initializes a data object filled with a given number of bytes of data from a given buffer. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int) { super.init() _init(bytes: bytes, length: length) } /// Initializes a data object filled with a given number of bytes of data from a given buffer. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, freeWhenDone: Bool) { super.init() _init(bytes: bytes, length: length, copy: false) { buffer, length in if freeWhenDone { free(buffer) } } } /// Initializes a data object filled with a given number of bytes of data from a given buffer, with a custom deallocator block. /// NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional public init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) { super.init() _init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } /// Initializes a data object with the contents of the file at a given path. public init(contentsOfFile path: String, options readOptionsMask: ReadingOptions = []) throws { super.init() let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask) _init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } /// Initializes a data object with the contents of the file at a given path. public init?(contentsOfFile path: String) { do { super.init() let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: []) _init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } catch { return nil } } /// Initializes a data object with the contents of another data object. public init(data: Data) { super.init() _init(bytes: UnsafeMutableRawPointer(mutating: data._nsObject.bytes), length: data.count, copy: true) } /// Initializes a data object with the data from the location specified by a given URL. public init(contentsOf url: URL, options readOptionsMask: ReadingOptions = []) throws { super.init() let (data, _) = try NSData.contentsOf(url: url, options: readOptionsMask) _init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true) } /// Initializes a data object with the data from the location specified by a given URL. public init?(contentsOf url: URL) { super.init() do { let (data, _) = try NSData.contentsOf(url: url) _init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true) } catch { return nil } } internal static func contentsOf(url: URL, options readOptionsMask: ReadingOptions = []) throws -> (NSData, URLResponse?) { let readResult: NSData var urlResponse: URLResponse? if url.isFileURL { let data = try NSData.readBytesFromFileWithExtendedAttributes(url.path, options: readOptionsMask) readResult = data.toNSData() } else { let session = URLSession(configuration: URLSessionConfiguration.default) let cond = NSCondition() cond.lock() var resError: Error? var resData: Data? var taskFinished = false let task = session.dataTask(with: url, completionHandler: { data, response, error in cond.lock() resData = data urlResponse = response resError = error taskFinished = true cond.signal() cond.unlock() }) task.resume() while taskFinished == false { cond.wait() } cond.unlock() guard let data = resData else { throw resError! } readResult = NSData(bytes: UnsafeMutableRawPointer(mutating: data._nsObject.bytes), length: data.count) } return (readResult, urlResponse) } /// Initializes a data object with the given Base64 encoded string. public init?(base64Encoded base64String: String, options: Base64DecodingOptions = []) { let encodedBytes = Array(base64String.utf8) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } super.init() _init(bytes: UnsafeMutableRawPointer(mutating: decodedBytes), length: decodedBytes.count, copy: true) } /// Initializes a data object with the given Base64 encoded data. public init?(base64Encoded base64Data: Data, options: Base64DecodingOptions = []) { var encodedBytes = [UInt8](repeating: 0, count: base64Data.count) base64Data._nsObject.getBytes(&encodedBytes, length: encodedBytes.count) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } super.init() _init(bytes: UnsafeMutableRawPointer(mutating: decodedBytes), length: decodedBytes.count, copy: true) } deinit { if let allocatedBytes = _bytes { _deallocHandler?.handler(allocatedBytes, _length) } if type(of: self) === NSData.self || type(of: self) === NSMutableData.self { _CFDeinit(self._cfObject) } } // MARK: - Funnel methods /// The number of bytes contained by the data object. open var length: Int { return CFDataGetLength(_cfObject) } /// A pointer to the data object's contents. open var bytes: UnsafeRawPointer { guard let bytePtr = CFDataGetBytePtr(_cfObject) else { //This could occure on empty data being encoded. //TODO: switch with nil when signature is fixed return UnsafeRawPointer(bitPattern: 0x7f00dead)! //would not result in 'nil unwrapped optional' } return UnsafeRawPointer(bytePtr) } // MARK: - NSObject methods open override var hash: Int { return Int(bitPattern: _CFNonObjCHash(_cfObject)) } /// Returns a Boolean value indicating whether this data object is the same as another. open override func isEqual(_ value: Any?) -> Bool { if let data = value as? Data { return isEqual(to: data) } else if let data = value as? NSData { return isEqual(to: data._swiftObject) } #if DEPLOYMENT_ENABLE_LIBDISPATCH if let data = value as? DispatchData { if data.count != length { return false } return data.withUnsafeBytes { (bytes2: UnsafePointer<UInt8>) -> Bool in let bytes1 = bytes return memcmp(bytes1, bytes2, length) == 0 } } #endif return false } open func isEqual(to other: Data) -> Bool { if length != other.count { return false } return other.withUnsafeBytes { (bytes2: UnsafePointer<UInt8>) -> Bool in let bytes1 = bytes return memcmp(bytes1, bytes2, length) == 0 } } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil) } private func byteDescription(limit: Int? = nil) -> String { var s = "" var i = 0 while i < self.length { if i > 0 && i % 4 == 0 { // if there's a limit, and we're at the barrier where we'd add the ellipses, don't add a space. if let limit = limit, self.length > limit && i == self.length - (limit / 2) { /* do nothing */ } else { s += " " } } let byte = bytes.load(fromByteOffset: i, as: UInt8.self) var byteStr = String(byte, radix: 16, uppercase: false) if byte <= 0xf { byteStr = "0\(byteStr)" } s += byteStr // if we've hit the midpoint of the limit, skip to the last (limit / 2) bytes. if let limit = limit, self.length > limit && i == (limit / 2) - 1 { s += " ... " i = self.length - (limit / 2) } else { i += 1 } } return s } override open var debugDescription: String { return "<\(byteDescription(limit: 1024))>" } /// A string that contains a hexadecimal representation of the data object’s contents in a property list format. override open var description: String { return "<\(byteDescription())>" } // MARK: - NSCoding methods open func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.data") } else { let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) aCoder.encodeBytes(bytePtr, length: self.length) } } public required init?(coder aDecoder: NSCoder) { super.init() guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.data") { guard let data = aDecoder._decodePropertyListForKey("NS.data") as? NSData else { return nil } _init(bytes: UnsafeMutableRawPointer(mutating: data.bytes), length: data.length, copy: true) } else { let result : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") { guard let buffer = $0 else { return nil } return Data(buffer: buffer) } guard let r = result else { return nil } _init(bytes: UnsafeMutableRawPointer(mutating: r._nsObject.bytes), length: r.count, copy: true) } } public static var supportsSecureCoding: Bool { return true } // MARK: - IO internal struct NSDataReadResult { var bytes: UnsafeMutableRawPointer? var length: Int var deallocator: ((_ buffer: UnsafeMutableRawPointer, _ length: Int) -> Void)! func toNSData() -> NSData { if bytes == nil { return NSData() } return NSData(bytesNoCopy: bytes!, length: length, deallocator: deallocator) } func toData() -> Data { guard let bytes = bytes else { return Data() } return Data(bytesNoCopy: bytes, count: length, deallocator: Data.Deallocator.custom(deallocator)) } } internal static func readBytesFromFileWithExtendedAttributes(_ path: String, options: ReadingOptions) throws -> NSDataReadResult { guard let handle = FileHandle(path: path, flags: O_RDONLY, createMode: 0) else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let result = try handle._readDataOfLength(Int.max, untilEOF: true) return result } internal func makeTemporaryFile(inDirectory dirPath: String) throws -> (Int32, String) { let template = dirPath._nsObject.appendingPathComponent("tmp.XXXXXX") let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: maxLength) let _ = template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dirPath) } let pathResult = FileManager.default.string(withFileSystemRepresentation:buf, length: Int(strlen(buf))) return (fd, pathResult) } internal class func write(toFileDescriptor fd: Int32, path: String? = nil, buf: UnsafeRawPointer, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int repeat { #if os(macOS) || os(iOS) bytesWritten = Darwin.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #elseif os(Linux) || os(Android) || CYGWIN bytesWritten = Glibc.write(fd, buf.advanced(by: length - bytesRemaining), bytesRemaining) #endif } while (bytesWritten < 0 && errno == EINTR) if bytesWritten <= 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else { bytesRemaining -= bytesWritten } } } /// Writes the data object's bytes to the file specified by a given path. open func write(toFile path: String, options writeOptionsMask: WritingOptions = []) throws { let fm = FileManager.default try fm._fileSystemRepresentation(withPath: path, { pathFsRep in var fd : Int32 var mode : mode_t? = nil let useAuxiliaryFile = writeOptionsMask.contains(.atomic) var auxFilePath : String? = nil if useAuxiliaryFile { // Preserve permissions. var info = stat() if lstat(pathFsRep, &info) == 0 { let mode = mode_t(info.st_mode) } else if errno != ENOENT && errno != ENAMETOOLONG { throw _NSErrorWithErrno(errno, reading: false, path: path) } let (newFD, path) = try self.makeTemporaryFile(inDirectory: path._nsObject.deletingLastPathComponent) fd = newFD auxFilePath = path fchmod(fd, 0o666) } else { var flags = O_WRONLY | O_CREAT | O_TRUNC if writeOptionsMask.contains(.withoutOverwriting) { flags |= O_EXCL } fd = _CFOpenFileWithMode(path, flags, 0o666) } if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } defer { close(fd) } try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in if range.length > 0 { do { try NSData.write(toFileDescriptor: fd, path: path, buf: buf, length: range.length) if fsync(fd) < 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } catch { if let auxFilePath = auxFilePath { try? FileManager.default.removeItem(atPath: auxFilePath) } throw error } } } if let auxFilePath = auxFilePath { try fm._fileSystemRepresentation(withPath: auxFilePath, { auxFilePathFsRep in if rename(auxFilePathFsRep, pathFsRep) != 0 { try? FileManager.default.removeItem(atPath: auxFilePath) throw _NSErrorWithErrno(errno, reading: false, path: path) } if let mode = mode { chmod(pathFsRep, mode) } }) } }) } /// Writes the data object's bytes to the file specified by a given path. /// NOTE: the 'atomically' flag is ignored if the url is not of a type the supports atomic writes open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { do { try write(toFile: path, options: useAuxiliaryFile ? .atomic : []) } catch { return false } return true } /// Writes the data object's bytes to the location specified by a given URL. /// NOTE: the 'atomically' flag is ignored if the url is not of a type the supports atomic writes open func write(to url: URL, atomically: Bool) -> Bool { if url.isFileURL { return write(toFile: url.path, atomically: atomically) } return false } /// Writes the data object's bytes to the location specified by a given URL. /// /// - parameter url: The location to which the data objects's contents will be written. /// - parameter writeOptionsMask: An option set specifying file writing options. /// /// - throws: This method returns Void and is marked with the `throws` keyword to indicate that it throws an error in the event of failure. /// /// This method is invoked in a `try` expression and the caller is responsible for handling any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42) in [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097) and [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) in [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216). open func write(to url: URL, options writeOptionsMask: WritingOptions = []) throws { guard url.isFileURL else { let userInfo = [NSLocalizedDescriptionKey : "The folder at “\(url)” does not exist or is not a file URL.", // NSLocalizedString() not yet available NSURLErrorKey : url.absoluteString] as Dictionary<String, Any> throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: userInfo) } try write(toFile: url.path, options: writeOptionsMask) } // MARK: - Bytes /// Copies a number of bytes from the start of the data object into a given buffer. open func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) { let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: length) CFDataGetBytes(_cfObject, CFRangeMake(0, length), bytePtr) } /// Copies a range of bytes from the data object into a given buffer. open func getBytes(_ buffer: UnsafeMutableRawPointer, range: NSRange) { let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: range.length) CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), bytePtr) } /// Returns a new data object containing the data object's bytes that fall within the limits specified by a given range. open func subdata(with range: NSRange) -> Data { if range.length == 0 { return Data() } if range.location == 0 && range.length == self.length { return Data(referencing: self) } let p = self.bytes.advanced(by: range.location).bindMemory(to: UInt8.self, capacity: range.length) return Data(bytes: p, count: range.length) } /// Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options. open func range(of dataToFind: Data, options mask: SearchOptions = [], in searchRange: NSRange) -> NSRange { let dataToFind = dataToFind._nsObject guard dataToFind.length > 0 else {return NSRange(location: NSNotFound, length: 0)} guard let searchRange = Range(searchRange) else {fatalError("invalid range")} precondition(searchRange.upperBound <= self.length, "range outside the bounds of data") let basePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) let baseData = UnsafeBufferPointer<UInt8>(start: basePtr, count: self.length)[searchRange] let searchPtr = dataToFind.bytes.bindMemory(to: UInt8.self, capacity: dataToFind.length) let search = UnsafeBufferPointer<UInt8>(start: searchPtr, count: dataToFind.length) let location : Int? let anchored = mask.contains(.anchored) if mask.contains(.backwards) { location = NSData.searchSubSequence(search.reversed(), inSequence: baseData.reversed(),anchored : anchored).map {$0.base-search.count} } else { location = NSData.searchSubSequence(search, inSequence: baseData,anchored : anchored) } return location.map {NSRange(location: $0, length: search.count)} ?? NSRange(location: NSNotFound, length: 0) } private static func searchSubSequence<T : Collection, T2 : Sequence>(_ subSequence : T2, inSequence seq: T,anchored : Bool) -> T.Index? where T.Iterator.Element : Equatable, T.Iterator.Element == T2.Iterator.Element { for index in seq.indices { if seq.suffix(from: index).starts(with: subSequence) { return index } if anchored {return nil} } return nil } internal func enumerateByteRangesUsingBlockRethrows(_ block: (UnsafeRawPointer, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws { var err : Swift.Error? = nil self.enumerateBytes() { (buf, range, stop) -> Void in do { try block(buf, range, stop) } catch { err = error } } if let err = err { throw err } } /// Enumerates each range of bytes in the data object using a block. /// 'block' is called once for each contiguous region of memory in the data object (once total for contiguous NSDatas), /// until either all bytes have been enumerated, or the 'stop' parameter is set to true. open func enumerateBytes(_ block: (UnsafeRawPointer, NSRange, UnsafeMutablePointer<Bool>) -> Void) { var stop = false withUnsafeMutablePointer(to: &stop) { stopPointer in if (stopPointer.pointee) { return } block(bytes, NSRange(location: 0, length: length), stopPointer) } } // MARK: - Base64 Methods /// Creates a Base64 encoded String from the data object using the given options. open func base64EncodedString(options: Base64EncodingOptions = []) -> String { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) let characters = encodedBytes.map { Character(UnicodeScalar($0)) } return String(characters) } /// Creates a Base64, UTF-8 encoded Data from the data object using the given options. open func base64EncodedData(options: Base64EncodingOptions = []) -> Data { var decodedBytes = [UInt8](repeating: 0, count: self.length) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) return Data(bytes: encodedBytes, count: encodedBytes.count) } /// The ranges of ASCII characters that are used to encode data in Base64. private static let base64ByteMappings: [Range<UInt8>] = [ 65 ..< 91, // A-Z 97 ..< 123, // a-z 48 ..< 58, // 0-9 43 ..< 44, // + 47 ..< 48, // / ] /** Padding character used when the number of bytes to encode is not divisible by 3 */ private static let base64Padding : UInt8 = 61 // = /** This method takes a byte with a character from Base64-encoded string and gets the binary value that the character corresponds to. - parameter byte: The byte with the Base64 character. - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) */ private enum Base64DecodedByte { case valid(UInt8) case invalid case padding } private static func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { guard byte != base64Padding else {return .padding} var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { let result = decodedStart + (byte - range.lowerBound) return .valid(result) } decodedStart += range.upperBound - range.lowerBound } return .invalid } /** This method takes six bits of binary data and encodes it as a character in Base64. The value in the byte must be less than 64, because a Base64 character can only represent 6 bits. - parameter byte: The byte to encode - returns: The ASCII value for the encoded character. */ private static func base64EncodeByte(_ byte: UInt8) -> UInt8 { assert(byte < 64) var decodedStart: UInt8 = 0 for range in base64ByteMappings { let decodedRange = decodedStart ..< decodedStart + (range.upperBound - range.lowerBound) if decodedRange.contains(byte) { return range.lowerBound + (byte - decodedStart) } decodedStart += range.upperBound - range.lowerBound } return 0 } /** This method decodes Base64-encoded data. If the input contains any bytes that are not valid Base64 characters, this will return nil. - parameter bytes: The Base64 bytes - parameter options: Options for handling invalid input - returns: The decoded bytes. */ private static func base64DecodeBytes(_ bytes: [UInt8], options: Base64DecodingOptions = []) -> [UInt8]? { var decodedBytes = [UInt8]() decodedBytes.reserveCapacity((bytes.count/3)*2) var currentByte : UInt8 = 0 var validCharacterCount = 0 var paddingCount = 0 var index = 0 for base64Char in bytes { let value : UInt8 switch base64DecodeByte(base64Char) { case .valid(let v): value = v validCharacterCount += 1 case .invalid: if options.contains(.ignoreUnknownCharacters) { continue } else { return nil } case .padding: paddingCount += 1 continue } //padding found in the middle of the sequence is invalid if paddingCount > 0 { return nil } switch index%4 { case 0: currentByte = (value << 2) case 1: currentByte |= (value >> 4) decodedBytes.append(currentByte) currentByte = (value << 4) case 2: currentByte |= (value >> 2) decodedBytes.append(currentByte) currentByte = (value << 6) case 3: currentByte |= value decodedBytes.append(currentByte) default: fatalError() } index += 1 } guard (validCharacterCount + paddingCount)%4 == 0 else { //invalid character count return nil } return decodedBytes } /** This method encodes data in Base64. - parameter bytes: The bytes you want to encode - parameter options: Options for formatting the result - returns: The Base64-encoding for those bytes. */ private static func base64EncodeBytes(_ bytes: [UInt8], options: Base64EncodingOptions = []) -> [UInt8] { var result = [UInt8]() result.reserveCapacity((bytes.count/3)*4) let lineOptions : (lineLength : Int, separator : [UInt8])? = { let lineLength: Int if options.contains(.lineLength64Characters) { lineLength = 64 } else if options.contains(.lineLength76Characters) { lineLength = 76 } else { return nil } var separator = [UInt8]() if options.contains(.endLineWithCarriageReturn) { separator.append(13) } if options.contains(.endLineWithLineFeed) { separator.append(10) } //if the kind of line ending to insert is not specified, the default line ending is Carriage Return + Line Feed. if separator.isEmpty { separator = [13,10] } return (lineLength,separator) }() var currentLineCount = 0 let appendByteToResult : (UInt8) -> Void = { result.append($0) currentLineCount += 1 if let options = lineOptions, currentLineCount == options.lineLength { result.append(contentsOf: options.separator) currentLineCount = 0 } } var currentByte : UInt8 = 0 for (index,value) in bytes.enumerated() { switch index%3 { case 0: currentByte = (value >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 6) >> 2) case 1: currentByte |= (value >> 4) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 4) >> 2) case 2: currentByte |= (value >> 6) appendByteToResult(NSData.base64EncodeByte(currentByte)) currentByte = ((value << 2) >> 2) appendByteToResult(NSData.base64EncodeByte(currentByte)) default: fatalError() } } //add padding switch bytes.count%3 { case 0: break //no padding needed case 1: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) appendByteToResult(self.base64Padding) case 2: appendByteToResult(NSData.base64EncodeByte(currentByte)) appendByteToResult(self.base64Padding) default: fatalError() } return result } } // MARK: - extension NSData : _CFBridgeable, _SwiftBridgeable { typealias SwiftType = Data internal var _swiftObject: SwiftType { return Data(referencing: self) } } extension Data : _NSBridgeable, _CFBridgeable { typealias CFType = CFData typealias NSType = NSData internal var _cfObject: CFType { return _nsObject._cfObject } internal var _nsObject: NSType { return _bridgeToObjectiveC() } } extension CFData : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSData typealias SwiftType = Data internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: SwiftType { return Data(referencing: self._nsObject) } } // MARK: - open class NSMutableData : NSData { internal var _cfMutableObject: CFMutableData { return unsafeBitCast(self, to: CFMutableData.self) } public override init() { super.init(bytes: nil, length: 0) } // NOTE: the deallocator block here is implicitly @escaping by virtue of it being optional fileprivate override init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool = false, deallocator: (/*@escaping*/ (UnsafeMutableRawPointer, Int) -> Void)? = nil) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } /// Initializes a data object filled with a given number of bytes copied from a given buffer. public override init(bytes: UnsafeRawPointer?, length: Int) { super.init(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil) } /// Returns an initialized mutable data object capable of holding the specified number of bytes. public init?(capacity: Int) { super.init(bytes: nil, length: 0) } /// Initializes and returns a mutable data object containing a given number of zeroed bytes. public init?(length: Int) { super.init(bytes: nil, length: 0) self.length = length } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int) { super.init(bytesNoCopy: bytes, length: length) } public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil) { super.init(bytesNoCopy: bytes, length: length, deallocator: deallocator) } public override init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, freeWhenDone: Bool) { super.init(bytesNoCopy: bytes, length: length, freeWhenDone: freeWhenDone) } public override init(data: Data) { super.init(data: data) } public override init?(contentsOfFile path: String) { super.init(contentsOfFile: path) } public override init(contentsOfFile path: String, options: NSData.ReadingOptions = []) throws { try super.init(contentsOfFile: path, options: options) } public override init?(contentsOf url: URL) { super.init(contentsOf: url) } public override init(contentsOf url: URL, options: NSData.ReadingOptions = []) throws { try super.init(contentsOf: url, options: options) } public override init?(base64Encoded base64Data: Data, options: NSData.Base64DecodingOptions = []) { super.init(base64Encoded: base64Data, options: options) } public override init?(base64Encoded base64Data: String, options: NSData.Base64DecodingOptions = []) { super.init(base64Encoded: base64Data, options: options) } // MARK: - Funnel Methods /// A pointer to the data contained by the mutable data object. open var mutableBytes: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(CFDataGetMutableBytePtr(_cfMutableObject)) } /// The number of bytes contained in the mutable data object. open override var length: Int { get { return CFDataGetLength(_cfObject) } set { CFDataSetLength(_cfMutableObject, newValue) } } // MARK: - NSObject open override func copy(with zone: NSZone? = nil) -> Any { return NSData(bytes: bytes, length: length) } // MARK: - Mutability /// Appends to the data object a given number of bytes from a given buffer. open func append(_ bytes: UnsafeRawPointer, length: Int) { let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length) CFDataAppendBytes(_cfMutableObject, bytePtr, length) } /// Appends the content of another data object to the data object. open func append(_ other: Data) { let otherLength = other.count other.withUnsafeBytes { append($0, length: otherLength) } } /// Increases the length of the data object by a given number of bytes. open func increaseLength(by extraLength: Int) { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } /// Replaces with a given set of bytes a given range within the contents of the data object. open func replaceBytes(in range: NSRange, withBytes bytes: UnsafeRawPointer) { let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length) CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, length) } /// Replaces with zeroes the contents of the data object in a given range. open func resetBytes(in range: NSRange) { bzero(mutableBytes.advanced(by: range.location), range.length) } /// Replaces the entire contents of the data object with the contents of another data object. open func setData(_ data: Data) { length = data.count data.withUnsafeBytes { replaceBytes(in: NSRange(location: 0, length: length), withBytes: $0) } } /// Replaces with a given set of bytes a given range within the contents of the data object. open func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let bytePtr = replacementBytes?.bindMemory(to: UInt8.self, capacity: replacementLength) CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, replacementLength) } } extension NSData { internal func _isCompact() -> Bool { var regions = 0 enumerateBytes { (_, _, stop) in regions += 1 if regions > 1 { stop.pointee = true } } return regions <= 1 } } extension NSData : _StructTypeBridgeable { public typealias _StructType = Data public func _bridgeToSwift() -> Data { return Data._unconditionallyBridgeFromObjectiveC(self) } } internal func _CFSwiftDataCreateCopy(_ data: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((data as! NSData).copy() as! NSObject) }
apache-2.0
92d577c78e9b84bfdf61872b0d845b02
39.980392
924
0.612622
4.784694
false
false
false
false
mikaoj/BSImagePicker
Sources/Scene/Preview/VideoPreviewViewController.swift
1
4659
// The MIT License (MIT) // // Copyright (c) 2019 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import AVFoundation import Foundation import os import Photos import UIKit class VideoPreviewViewController: PreviewViewController { private let playerView = PlayerView() private var pauseBarButton: UIBarButtonItem! private var playBarButton: UIBarButtonItem! private let imageManager = PHCachingImageManager.default() enum State { case playing case paused } override var asset: PHAsset? { didSet { guard let asset = asset, asset.mediaType == .video else { player = nil return } imageManager.requestAVAsset(forVideo: asset, options: settings.fetch.preview.videoOptions) { (avasset, audioMix, arguments) in guard let avasset = avasset as? AVURLAsset else { return } DispatchQueue.main.async { [weak self] in self?.player = AVPlayer(url: avasset.url) self?.updateState(.playing, animated: false) } } } } private var player: AVPlayer? { didSet { guard let player = player else { return } playerView.player = player NotificationCenter.default.addObserver(self, selector: #selector(reachedEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) } } override func viewDidLoad() { super.viewDidLoad() try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) pauseBarButton = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: #selector(pausePressed(sender:))) playBarButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(playPressed(sender:))) playerView.frame = view.bounds playerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(playerView) scrollView.isUserInteractionEnabled = false doubleTapRecognizer.isEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) playerView.isHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) playerView.isHidden = false view.sendSubviewToBack(scrollView) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateState(.paused, animated: false) playerView.isHidden = true NotificationCenter.default.removeObserver(self) } private func updateState(_ state: State, animated: Bool = true) { switch state { case .playing: navigationItem.setRightBarButton(pauseBarButton, animated: animated) player?.play() case .paused: navigationItem.setRightBarButton(playBarButton, animated: animated) player?.pause() } } // MARK: React to events @objc func playPressed(sender: UIBarButtonItem) { if player?.currentTime() == player?.currentItem?.duration { player?.seek(to: .zero) } updateState(.playing) } @objc func pausePressed(sender: UIBarButtonItem) { updateState(.paused) } @objc func reachedEnd(notification: Notification) { player?.seek(to: .zero) updateState(.paused) } }
mit
8a6ee08abd90ed18f22ca66b2c35d9fb
34.830769
188
0.656934
5.233708
false
false
false
false
nodes-vapor/admin-panel-provider
Sources/AdminPanelProvider/Tags/Leaf/Request+Active.swift
1
827
import Leaf import Vapor extension ArgumentList { func extractPath() -> String? { return context.get(path: ["request", "uri", "path"])?.string } } extension Request { static func isActive(_ path: String?, _ defaultPath: String?, _ args: ArraySlice<Argument>, _ stem: Stem, _ context: LeafContext) -> Bool { guard args.count > 0 else { return path == defaultPath } for arg in args { guard let searchPath = arg.value(with: stem, in: context)?.string else { continue } if searchPath.hasSuffix("*"), path?.contains(searchPath.replacingOccurrences(of: "*", with: "")) ?? false { return true } if searchPath == path { return true } } return false } }
mit
7c9ab669f54d940b1a4edfe7581e67eb
26.566667
143
0.544135
4.672316
false
false
false
false
jordane-quincy/M2_DevMobileIos
JSONProject/Demo/ResultatPersonDetails.swift
1
6713
// // ResultatPersonDetails.swift // Demo // // Created by MAC ISTV on 10/05/2017. // Copyright © 2017 UVHC. All rights reserved. // import UIKit class ResultatPersonDetails: UIViewController, UIScrollViewDelegate { var scrollView = UIScrollView() var containerView = UIView() var customNavigationController: UINavigationController? = nil var affiliate: Person? = nil public func setupNavigationController(navigationController: UINavigationController){ self.customNavigationController = navigationController } public func setupAffiliate(affiliate: Person) { self.affiliate = affiliate } override func viewDidLoad() { super.viewDidLoad() self.title = "Détails" // TODO Créer l'interface en utlisant self.person createViewFromAffiliate() } // For displaying scrollView override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.frame = view.bounds containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height) } func createViewFromAffiliate(){ // Setup interface DispatchQueue.main.async() { // Setup scrollview self.scrollView = UIScrollView() // self.scrollView.delegate = self self.view.addSubview(self.scrollView) self.containerView = UIView() self.scrollView.addSubview(self.containerView) var posY: Double = 70 for (index, attribute) in ((self.affiliate?.attributes)!).enumerated() { if (attribute.value != ""){ let label: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); //Pour les attributs, affichage "label : value" label.text = attribute.label + " : " + attribute.value self.containerView.addSubview(label) posY += (index < ((self.affiliate?.attributes.count)! - 1) ? 30 : 60) } } if (self.affiliate?.serviceOffer != nil) { if (self.affiliate?.serviceOffer?.title != ""){ // Ajout label serviceOffer.title let title: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); title.text = "Service souscrit : " + (self.affiliate?.serviceOffer?.title)! self.containerView.addSubview(title) posY += 20 } if (self.affiliate?.serviceOffer?.offerDescription != ""){ // Ajout description du service let description: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 100.00)); description.numberOfLines = 0 description.text = "Description : \n" + (self.affiliate?.serviceOffer?.offerDescription)! self.containerView.addSubview(description) posY += 100 } //Ajout du prix de l'offre let price: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); price.text = "Prix de l'offre : " + String((self.affiliate?.serviceOffer?.price)!) + "€" self.containerView.addSubview(price) posY += 50 } let numberOfOption = (self.affiliate?.serviceOptions.count)! if (numberOfOption > 0) { let messageOption: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); messageOption.text = "Option" + (numberOfOption > 1 ? "s " : " ") + "souscrite" + (numberOfOption > 1 ? "s :" : " :") self.containerView.addSubview(messageOption) posY += 30 } for option in (self.affiliate?.serviceOptions)! { if (option.title != ""){ // Ajout label option.title let title: UILabel = UILabel(frame: CGRect(x: 50, y: posY, width: 305, height: 30.00)); title.text = "• Option : " + (option.title) self.containerView.addSubview(title) posY += 20 } if (option.optionDescription != ""){ // Ajout description de l'option let description: UILabel = UILabel(frame: CGRect(x: 65, y: posY, width: 305, height: 100.00)); description.numberOfLines = 0 description.text = "Description : \n" + (option.optionDescription) self.containerView.addSubview(description) posY += 100 } //Ajout du prix de l'option let price: UILabel = UILabel(frame: CGRect(x: 65, y: posY, width: 335, height: 30.00)); price.text = "Prix de l'option : " + String(option.price) + "€" self.containerView.addSubview(price) posY += 30 } posY += 20 if (self.affiliate?.paymentWay?.label != ""){ // Ajout label let label: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); label.text = "Moyen de paiement : " + (self.affiliate?.paymentWay?.label)! self.containerView.addSubview(label) posY += 30 } for attribute in (self.affiliate?.paymentWay?.paymentAttributes)! { if (attribute.value != ""){ let label: UILabel = UILabel(frame: CGRect(x: 20, y: posY, width: 335, height: 30.00)); //Pour les attributs, affichage "label : value" label.text = attribute.label + " : " + attribute.value self.containerView.addSubview(label) posY += 30 } } // Set size fo scrollView self.scrollView.contentSize = CGSize(width: 350, height: posY + 50) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5a143f705930ab5f706b7d9c7983b250
40.639752
133
0.51074
4.861494
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSString.swift
1
36071
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public typealias unichar = UInt16 extension unichar : UnicodeScalarLiteralConvertible { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } #if os(OSX) || os(iOS) internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.MacRoman.rawValue internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.WindowsLatin1.rawValue internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.ISOLatin1.rawValue internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.NextStepLatin.rawValue internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.Unicode.rawValue internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.NonLossyASCII.rawValue internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue #endif public struct NSStringEncodingConversionOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let AllowLossy = NSStringEncodingConversionOptions(rawValue: 1) public static let ExternalRepresentation = NSStringEncodingConversionOptions(rawValue: 2) } public struct NSStringEnumerationOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ByLines = NSStringEnumerationOptions(rawValue: 0) public static let ByParagraphs = NSStringEnumerationOptions(rawValue: 1) public static let ByComposedCharacterSequences = NSStringEnumerationOptions(rawValue: 2) public static let ByWords = NSStringEnumerationOptions(rawValue: 3) public static let BySentences = NSStringEnumerationOptions(rawValue: 4) public static let Reverse = NSStringEnumerationOptions(rawValue: 1 << 8) public static let SubstringNotRequired = NSStringEnumerationOptions(rawValue: 1 << 9) public static let Localized = NSStringEnumerationOptions(rawValue: 1 << 10) } extension String : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSString.self } public func _bridgeToObjectiveC() -> NSString { return NSString(self) } public static func _forceBridgeFromObjectiveC(x: NSString, inout result: String?) { if x.dynamicType == NSString.self || x.dynamicType == NSMutableString.self { result = x._storage } else if x.dynamicType == _NSCFString.self { let cf = unsafeBitCast(x, CFStringRef.self) let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) if str != nil { result = String.fromCString(str) } else { let length = CFStringGetLength(cf) let buffer = UnsafeMutablePointer<UniChar>.alloc(length) CFStringGetCharacters(cf, CFRangeMake(0, length), buffer) let str = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: buffer, count: length)) buffer.destroy(length) buffer.dealloc(length) result = str } } else if x.dynamicType == _NSCFConstantString.self { let conststr = unsafeBitCast(x, _NSCFConstantString.self) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length))) result = str } else { NSUnimplemented() // TODO: subclasses } } public static func _conditionallyBridgeFromObjectiveC(x: NSString, inout result: String?) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } } public struct NSStringCompareOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let CaseInsensitiveSearch = NSStringCompareOptions(rawValue: 1) public static let LiteralSearch = NSStringCompareOptions(rawValue: 2) public static let BackwardsSearch = NSStringCompareOptions(rawValue: 4) public static let AnchoredSearch = NSStringCompareOptions(rawValue: 8) public static let NumericSearch = NSStringCompareOptions(rawValue: 64) public static let DiacriticInsensitiveSearch = NSStringCompareOptions(rawValue: 128) public static let WidthInsensitiveSearch = NSStringCompareOptions(rawValue: 256) public static let ForcedOrderingSearch = NSStringCompareOptions(rawValue: 512) public static let RegularExpressionSearch = NSStringCompareOptions(rawValue: 1024) } public class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID()) internal var _storage: String public var length: Int { get { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { return _storage.utf16.count } else { NSRequiresConcreteImplementation() } } } public func characterAtIndex(index: Int) -> unichar { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { let start = _storage.utf16.startIndex return _storage.utf16[start.advancedBy(index)] } else { NSRequiresConcreteImplementation() } } deinit { _CFDeinit(self) } public override convenience init() { let characters = Array<unichar>(count: 1, repeatedValue: 0) self.init(characters: characters, length: 0) } internal init(_ string: String) { _storage = string } public convenience required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func copyWithZone(zone: NSZone) -> AnyObject { return self } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { let contents = _fastContents if contents != nil { return NSMutableString(characters: contents, length: length) } } let characters = UnsafeMutablePointer<unichar>.alloc(length) self.getCharacters(characters, range: NSMakeRange(0, length)) let result = NSMutableString(characters: characters, length: length) characters.destroy() characters.dealloc(length) return result } public static func supportsSecureCoding() -> Bool { return true } public func encodeWithCoder(aCoder: NSCoder) { } public init(characters: UnsafePointer<unichar>, length: Int) { _storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { _storage = String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.byteSize))) } else { var uintValue = value.unicodeScalar.value _storage = String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)) } } internal var _fastCStringContents: UnsafePointer<Int8> { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if _storage._core.isASCII { return unsafeBitCast(_storage._core.startASCII, UnsafePointer<Int8>.self) } } return nil } internal var _fastContents: UnsafePointer<UniChar> { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if !_storage._core.isASCII { return unsafeBitCast(_storage._core.startUTF16, UnsafePointer<UniChar>.self) } } return nil } override internal var _cfTypeID: CFTypeID { return CFStringGetTypeID() } public override func isEqual(object: AnyObject?) -> Bool { guard let string = (object as? NSString)?._swiftObject else { return false } return self.isEqualToString(string) } } extension NSString { public func getCharacters(buffer: UnsafeMutablePointer<unichar>, range: NSRange) { for var idx = 0; idx < range.length; idx++ { buffer[idx] = characterAtIndex(idx + range.location) } } public func substringFromIndex(from: Int) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return String(_storage.utf16.suffixFrom(_storage.utf16.startIndex.advancedBy(from))) } else { return self.substringWithRange(NSMakeRange(from, self.length - from)) } } public func substringToIndex(to: Int) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return String(_storage.utf16.prefixUpTo(_storage.utf16.startIndex .advancedBy(to))) } else { return self.substringWithRange(NSMakeRange(0, to)) } } public func substringWithRange(range: NSRange) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { let start = _storage.utf16.startIndex return String(_storage.utf16[Range<String.UTF16View.Index>(start: start.advancedBy(range.location), end: start.advancedBy(range.location + range.length))]) } else { let buff = UnsafeMutablePointer<unichar>.alloc(range.length) self.getCharacters(buff, range: range) let result = String(buff) buff.destroy() buff.dealloc(range.length) return result } } public func compare(string: String) -> NSComparisonResult { return compare(string, options: [], range:NSMakeRange(0, self.length), locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions) -> NSComparisonResult { return compare(string, options: mask, range:NSMakeRange(0, self.length), locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions, range compareRange: NSRange) -> NSComparisonResult { return compare(string, options: [], range:compareRange, locale: nil) } public func compare(string: String, options mask: NSStringCompareOptions, range compareRange: NSRange, locale: AnyObject?) -> NSComparisonResult { if let _ = locale { NSUnimplemented() } #if os(Linux) var cfflags = CFStringCompareFlags(mask.rawValue) if mask.contains(.LiteralSearch) { cfflags |= UInt(kCFCompareNonliteral) } #else var cfflags = CFStringCompareFlags(rawValue: mask.rawValue) if mask.contains(.LiteralSearch) { cfflags.unionInPlace(.CompareNonliteral) } #endif let cfresult = CFStringCompareWithOptionsAndLocale(self._cfObject, string._cfObject, CFRangeMake(compareRange.location, compareRange.length), cfflags, nil) #if os(Linux) return NSComparisonResult(rawValue: cfresult)! #else return NSComparisonResult(rawValue: cfresult.rawValue)! #endif } public func caseInsensitiveCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: nil) } public func localizedCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func localizedCaseInsensitiveCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func localizedStandardCompare(string: String) -> NSComparisonResult { return self.compare(string, options: [.CaseInsensitiveSearch, .NumericSearch, .WidthInsensitiveSearch, .ForcedOrderingSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func isEqualToString(aString: String) -> Bool { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return _storage == aString } else { return self.length == aString._nsObject.length && self.compare(aString, options: [.LiteralSearch], range: NSMakeRange(0, self.length)) == .OrderedSame } } public func hasPrefix(str: String) -> Bool { return _swiftObject.hasPrefix(str) } public func hasSuffix(str: String) -> Bool { return _swiftObject.hasSuffix(str) } public func commonPrefixWithString(str: String, options mask: NSStringCompareOptions) -> String { NSUnimplemented() } public func containsString(str: String) -> Bool { return self.rangeOfString(str).location != NSNotFound } public func localizedCaseInsensitiveContainsString(str: String) -> Bool { return self.rangeOfString(str, options: [.CaseInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()).location != NSNotFound } public func localizedStandardContainsString(str: String) -> Bool { return self.rangeOfString(str, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()).location != NSNotFound } public func localizedStandardRangeOfString(str: String) -> NSRange { return self.rangeOfString(str, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch], range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func rangeOfString(searchString: String) -> NSRange { return self.rangeOfString(searchString, options: [], range: NSMakeRange(0, self.length), locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions) -> NSRange { return self.rangeOfString(searchString, options: mask, range: NSMakeRange(0, self.length), locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange { return self.rangeOfString(searchString, options: mask, range: searchRange, locale: nil) } public func rangeOfString(searchString: String, options mask: NSStringCompareOptions, range searchRange: NSRange, locale: NSLocale?) -> NSRange { if let _ = locale { NSUnimplemented() } if mask.contains(.RegularExpressionSearch) { NSUnimplemented() } if searchString.length == 0 || searchRange.length == 0 { return NSMakeRange(NSNotFound, 0) } #if os(Linux) var cfflags = CFStringCompareFlags(mask.rawValue) if mask.contains(.LiteralSearch) { cfflags |= UInt(kCFCompareNonliteral) } #else var cfflags = CFStringCompareFlags(rawValue: mask.rawValue) if mask.contains(.LiteralSearch) { cfflags.unionInPlace(.CompareNonliteral) } #endif var result = CFRangeMake(kCFNotFound, 0) if CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRangeMake(searchRange.location, searchRange.length), cfflags, nil, &result) { return NSMakeRange(result.location, result.length) } else { return NSMakeRange(NSNotFound, 0) } } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet) -> NSRange { NSUnimplemented() } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet, options mask: NSStringCompareOptions) -> NSRange { NSUnimplemented() } public func rangeOfCharacterFromSet(searchSet: NSCharacterSet, options mask: NSStringCompareOptions, range searchRange: NSRange) -> NSRange { NSUnimplemented() } public func rangeOfComposedCharacterSequenceAtIndex(index: Int) -> NSRange { NSUnimplemented() } public func rangeOfComposedCharacterSequencesForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func stringByAppendingString(aString: String) -> String { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { return _storage + aString } else { NSUnimplemented() } } public var doubleValue: Double { get { NSUnimplemented() } } public var floatValue: Float { get { NSUnimplemented() } } public var intValue: Int32 { get { NSUnimplemented() } } public var integerValue: Int { get { NSUnimplemented() } } public var longLongValue: Int64 { get { NSUnimplemented() } } public var boolValue: Bool { get { NSUnimplemented() } } public var uppercaseString: String { get { NSUnimplemented() } } public var lowercaseString: String { get { NSUnimplemented() } } public var capitalizedString: String { get { NSUnimplemented() } } public var localizedUppercaseString: String { get { NSUnimplemented() } } public var localizedLowercaseString: String { get { NSUnimplemented() } } public var localizedCapitalizedString: String { get { NSUnimplemented() } } public func uppercaseStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func lowercaseStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func capitalizedStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func getLineStart(startPtr: UnsafeMutablePointer<Int>, end lineEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange) { NSUnimplemented() } public func lineRangeForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func getParagraphStart(startPtr: UnsafeMutablePointer<Int>, end parEndPtr: UnsafeMutablePointer<Int>, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>, forRange range: NSRange) { NSUnimplemented() } public func paragraphRangeForRange(range: NSRange) -> NSRange { NSUnimplemented() } public func enumerateSubstringsInRange(range: NSRange, options opts: NSStringEnumerationOptions, usingBlock block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateLinesUsingBlock(block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public var UTF8String: UnsafePointer<Int8> { get { NSUnimplemented() } } public var fastestEncoding: UInt { get { NSUnimplemented() } } public var smallestEncoding: UInt { get { NSUnimplemented() } } public func dataUsingEncoding(encoding: UInt, allowLossyConversion lossy: Bool) -> NSData? { NSUnimplemented() } public func dataUsingEncoding(encoding: UInt) -> NSData? { NSUnimplemented() } public func canBeConvertedToEncoding(encoding: UInt) -> Bool { NSUnimplemented() } public func cStringUsingEncoding(encoding: UInt) -> UnsafePointer<Int8> { NSUnimplemented() } public func getCString(buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool { if self.dynamicType == NSString.self || self.dynamicType == NSMutableString.self { if _storage._core.isASCII { let len = min(self.length, maxBufferCount) buffer.moveAssignFrom(unsafeBitCast(_storage._core.startASCII, UnsafeMutablePointer<Int8>.self) , count: len) return true } } return false } public func getBytes(buffer: UnsafeMutablePointer<Void>, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: UInt, options: NSStringEncodingConversionOptions, range: NSRange, remainingRange leftover: NSRangePointer) -> Bool { NSUnimplemented() } public func maximumLengthOfBytesUsingEncoding(enc: UInt) -> Int { NSUnimplemented() } public func lengthOfBytesUsingEncoding(enc: UInt) -> Int { NSUnimplemented() } public class func availableStringEncodings() -> UnsafePointer<UInt> { NSUnimplemented() } public class func localizedNameOfStringEncoding(encoding: UInt) -> String { NSUnimplemented() } public class func defaultCStringEncoding() -> UInt { NSUnimplemented() } public var decomposedStringWithCanonicalMapping: String { get { NSUnimplemented() } } public var precomposedStringWithCanonicalMapping: String { get { NSUnimplemented() } } public var decomposedStringWithCompatibilityMapping: String { get { NSUnimplemented() } } public var precomposedStringWithCompatibilityMapping: String { get { NSUnimplemented() } } public func componentsSeparatedByString(separator: String) -> [String] { NSUnimplemented() } public func componentsSeparatedByCharactersInSet(separator: NSCharacterSet) -> [String] { NSUnimplemented() } public func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String { NSUnimplemented() } public func stringByPaddingToLength(newLength: Int, withString padString: String, startingAtIndex padIndex: Int) -> String { NSUnimplemented() } public func stringByFoldingWithOptions(options: NSStringCompareOptions, locale: NSLocale?) -> String { NSUnimplemented() } public func stringByReplacingOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions, range searchRange: NSRange) -> String { NSUnimplemented() } public func stringByReplacingOccurrencesOfString(target: String, withString replacement: String) -> String { NSUnimplemented() } public func stringByReplacingCharactersInRange(range: NSRange, withString replacement: String) -> String { NSUnimplemented() } public func stringByApplyingTransform(transform: String, reverse: Bool) -> String? { NSUnimplemented() } public func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { NSUnimplemented() } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { NSUnimplemented() } public convenience init?(UTF8String nullTerminatedCString: UnsafePointer<Int8>) { NSUnimplemented() } public convenience init(string aString: String) { NSUnimplemented() } public convenience init(format: String, arguments argList: CVaListPointer) { NSUnimplemented() } public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) { NSUnimplemented() } public convenience init?(data: NSData, encoding: UInt) { self.init(bytes: data.bytes, length: data.length, encoding: encoding) } public convenience init?(bytes: UnsafePointer<Void>, length len: Int, encoding: UInt) { guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, UnsafePointer<UInt8>(bytes), len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } self.init(cf._swiftObject) } public convenience init?(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { NSUnimplemented() } public convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { guard let cf = CFStringCreateWithCString(kCFAllocatorDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else { return nil } self.init(cf._swiftObject) } public convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(contentsOfFile path: String, encoding enc: UInt) throws { NSUnimplemented() } public convenience init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<UInt>) throws { NSUnimplemented() } public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>) throws { NSUnimplemented() } } extension NSString : StringLiteralConvertible { } public class NSMutableString : NSString { public func replaceCharactersInRange(range: NSRange, withString aString: String) { if self.dynamicType === NSString.self || self.dynamicType === NSMutableString.self { // this is incorrectly calculated for grapheme clusters that have a size greater than a single unichar let start = _storage.startIndex let subrange = Range(start: start.advancedBy(range.location), end: start.advancedBy(range.location + range.length)) _storage.replaceRange(subrange, with: aString) } else { NSRequiresConcreteImplementation() } } public required override init(characters: UnsafePointer<unichar>, length: Int) { super.init(characters: characters, length: length) } public required init(capacity: Int) { super.init(characters: nil, length: 0) } public convenience required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { if value.hasPointerRepresentation { super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.byteSize)))) } else { var uintValue = value.unicodeScalar.value super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1))) } } internal func appendCharacters(characters: UnsafePointer<unichar>, length: Int) { if self.dynamicType == NSMutableString.self { _storage.appendContentsOf(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } else { replaceCharactersInRange(NSMakeRange(self.length, 0), withString: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))) } } internal func _cfAppendCString(characters: UnsafePointer<Int8>, length: Int) { if self.dynamicType == NSMutableString.self { _storage.appendContentsOf(String.fromCString(characters)!) } } } extension NSMutableString { public func insertString(aString: String, atIndex loc: Int) { self.replaceCharactersInRange(NSMakeRange(loc, 0), withString: aString) } public func deleteCharactersInRange(range: NSRange) { self.replaceCharactersInRange(range, withString: "") } public func appendString(aString: String) { self.replaceCharactersInRange(NSMakeRange(self.length, 0), withString: aString) } public func setString(aString: String) { self.replaceCharactersInRange(NSMakeRange(0, self.length), withString: aString) } public func replaceOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions, range searchRange: NSRange) -> Int { NSUnimplemented() } public func applyTransform(transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer) -> Bool { NSUnimplemented() } } extension String { /// Returns an Array of the encodings string objects support /// in the application’s environment. private static func _getAvailableStringEncodings() -> [NSStringEncoding] { let encodings = CFStringGetListOfAvailableEncodings() var numEncodings = 0 var encodingArray = Array<NSStringEncoding>() while encodings.advancedBy(numEncodings).memory != CoreFoundation.kCFStringEncodingInvalidId { encodingArray.append(CFStringConvertEncodingToNSStringEncoding(encodings.advancedBy(numEncodings).memory)) numEncodings++ } return encodingArray } private static var _availableStringEncodings = String._getAvailableStringEncodings() @warn_unused_result public static func availableStringEncodings() -> [NSStringEncoding] { return _availableStringEncodings } @warn_unused_result public static func defaultCStringEncoding() -> NSStringEncoding { return NSUTF8StringEncoding } @warn_unused_result public static func localizedNameOfStringEncoding(encoding: NSStringEncoding) -> String { return CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject } // this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters internal var length: Int { return utf16.count } public func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool { if encoding == NSUnicodeStringEncoding || encoding == NSNonLossyASCIIStringEncoding || encoding == NSUTF8StringEncoding { return true } return false } public var capitalizedString: String { get { return capitalizedStringWithLocale(nil) } } public var localizedCapitalizedString: String { get { return capitalizedStringWithLocale(NSLocale.currentLocale()) } } @warn_unused_result public func capitalizedStringWithLocale(locale: NSLocale?) -> String { NSUnimplemented() } public func caseInsensitiveCompare(aString: String) -> NSComparisonResult { return compare(aString, options: .CaseInsensitiveSearch, range: NSMakeRange(0, self.length), locale: NSLocale.currentLocale()) } public func compare(aString: String, options mask: NSStringCompareOptions = [], range: NSRange? = nil, locale: NSLocale? = nil) -> NSComparisonResult { NSUnimplemented() } #if os(Linux) public func hasPrefix(prefix: String) -> Bool { let characters = utf16 let prefixCharacters = prefix.utf16 let start = characters.startIndex let prefixStart = prefixCharacters.startIndex if characters.count < prefixCharacters.count { return false } for var idx = 0; idx < prefixCharacters.count; idx++ { if characters[start.advancedBy(idx)] != prefixCharacters[prefixStart.advancedBy(idx)] { return false } } return true } public func hasSuffix(suffix: String) -> Bool { let characters = utf16 let suffixCharacters = suffix.utf16 let start = characters.startIndex let suffixStart = suffixCharacters.startIndex if characters.count < suffixCharacters.count { return false } for var idx = 0; idx < suffixCharacters.count; idx++ { let charactersIdx = start.advancedBy(characters.count - idx - 1) let suffixIdx = suffixStart.advancedBy(suffixCharacters.count - idx - 1) if characters[charactersIdx] != suffixCharacters[suffixIdx] { return false } } return true } #endif } extension NSString : _CFBridgable, _SwiftBridgable { typealias SwiftType = String internal var _cfObject: CFStringRef { return unsafeBitCast(self, CFStringRef.self) } internal var _swiftObject: String { var str: String? String._forceBridgeFromObjectiveC(self, result: &str) return str! } } extension CFStringRef : _NSBridgable, _SwiftBridgable { typealias NSType = NSString typealias SwiftType = String internal var _nsObject: NSType { return unsafeBitCast(self, NSString.self) } internal var _swiftObject: String { return _nsObject._swiftObject } } extension String : _NSBridgable, _CFBridgable { typealias NSType = NSString typealias CFType = CFStringRef internal var _nsObject: NSType { return _bridgeToObjectiveC() } internal var _cfObject: CFType { return _nsObject._cfObject } } extension String : Bridgeable { public func bridge() -> NSString { return _nsObject } } extension NSString : Bridgeable { public func bridge() -> String { return _swiftObject } }
apache-2.0
52f8beb5f76911927a74d7ddd8ab2924
36.405602
273
0.667018
5.377927
false
false
false
false
mentalfaculty/impeller
Tests/ImpellerTests/Person.swift
1
835
// // Person.swift // Impeller // // Created by Drew McCormack on 08/12/2016. // Copyright © 2016 Drew McCormack. All rights reserved. // import Impeller struct Person: Repositable { var metadata = Metadata() var name = "No Name" var age: Int? = nil var tags = [String]() init() {} init(readingFrom reader:PropertyReader) { name = reader.read("name")! age = reader.read(optionalFor: "age")! tags = reader.read("tags")! } func write(to writer:PropertyWriter) { writer.write(name, for: "name") writer.write(age, for: "age") writer.write(tags, for: "tags") } static func == (left: Person, right: Person) -> Bool { return left.name == right.name && left.age == right.age && left.tags == right.tags } }
mit
e4314ae1ccbe4524b2066544cf4b84f8
22.166667
90
0.569544
3.548936
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/HelpdeskTicket.swift
1
3027
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import Stockpile public class HelpdeskTicket { public enum Topic: Equatable { case technical case reactivation case courseSpecific(Course) public static let genericTopics: [HelpdeskTicket.Topic] = [ .technical, .reactivation, ] var identifier: String { switch self { case .technical: return "technical" case .reactivation: return "reactivation" case .courseSpecific: return "course" } } public var isAvailable: Bool { switch self { case .reactivation: return FeatureHelper.hasFeature(.courseReactivation) default: return true } } public var displayName: String? { switch self { case .technical: return CommonLocalizedString("helpdesk.topic.technical", comment: "helpdesk topic technical") case let .courseSpecific(course): return course.title case .reactivation: return CommonLocalizedString("helpdesk.topic.reactivation", comment: "helpdesk topic reactivation") } } } let title: String let mail: String let report: String let topic: Topic public init(title: String, mail: String, topic: Topic, report: String) { self.title = title self.mail = mail self.report = report self.topic = topic } private var currentTrackingData: String { return """ platform: \(UIApplication.platform), \ os version: \(UIApplication.osVersion), \ device: \(UIApplication.device), \ app name: \(UIApplication.appName), \ app version: \(UIApplication.appVersion), \ app build: \(UIApplication.appBuild) """ } private var appLanguage: String { return Locale.supportedCurrent.identifier } } extension HelpdeskTicket: JSONAPIPushable { public var objectStateValue: Int16 { get { return ObjectState.new.rawValue } set {} // swiftlint:disable:this unused_setter_value } public static var type: String { return "tickets" } public func resourceAttributes() -> [String: Any] { return [ "title": self.title, "mail": self.mail, "report": self.report, "topic": self.topic.identifier, "data": self.currentTrackingData, "language": self.appLanguage, ] } public func resourceRelationships() -> [String: AnyObject]? { if case let Topic.courseSpecific(course) = self.topic { return [ "course": course as AnyObject ] } else { return nil } } }
gpl-3.0
6bfd45a158a51ad2f5f08d938b3b058a
25.313043
116
0.55618
4.849359
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/QCKeys.swift
1
2109
// // QCKeys.swift // QiitaCollection // // Created by ANZ on 2015/02/11. // Copyright (c) 2015年 anz. All rights reserved. // struct QCKeys { enum Notification: String { case ShowAlertController = "QC_NotificationKey_ShowAlertController", ShowActivityView = "QC_NotificationKey_ShowActivityView", PushViewController = "QC_NotificationKey_PushViewController", ShowMinimumNotification = "QC_NotificationKey_MinimumNtofice", ShowLoadingWave = "QC_NotificationKey_ShowLoading_Wave", HideLoadingWave = "QC_NotificationKey_HideLoading_Wave", ShowAlertYesNo = "QC_NotificationKey_ShowAlertYesNo", ShowAlertInputText = "QC_NotificationKey_ShowAlertInputText", PresentedViewController = "QC_NotificationKey_PresentedViewController", ResetPublicMenuItems = "QC_NotificationKey_ResetPublicMenuItems", ReloadViewPager = "QC_NotificationKey_ReloadViewPager", ShowAlertOkOnly = "QC_NotificationKey_OkOnly", ClearGuide = "QC_NotificationKey_ClearGuide", ShowInterstitial = "QC_NotificationKey_Interstitial" } enum AlertController: String { case Title = "Title", Description = "Description", Actions = "Actions", Style = "Style" } enum ActivityView: String { case Message = "Message", Link = "Link", Others = "Others" } enum MinimumNotification: String { case Title = "Title", SubTitle = "SubTitle", Style = "Style" } enum AlertView: String { case Title = "Title", Message = "Message", YesAction = "Yes-Action", YesTitle = "Yes-Title", NoTitle = "No-Title", PlaceHolder = "Place-Holder", OtherAction = "Other-Action", OtherTitle = "Other-Title" } enum UserActivity: String { case TypeSendURLToMac = "xyz.anzfactory.qiita-collection" } enum Transition: String { case CenterPoint = "center-point" } }
mit
bed072b5a1dbaf256c0f6fc316cd592d
28.263889
79
0.616991
4.531183
false
false
false
false
cnstoll/Snowman
Snowman/Snowman/CoreMLPlaygroundViewController.swift
1
4151
// // CoreMLPlaygroundViewController.swift // Snowman // // Created by Conrad Stoll on 7/30/17. // Copyright © 2017 Conrad Stoll. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreML import Foundation import UIKit enum CoreMLModelConfiguration : Int { case keras case kerasHalf case pca case pcaHalf func letterPrediction(for drawing : LetterDrawing) -> String { switch self { case .keras: let recognizer = KerasLetterRecognizer(KerasFullAlphabetModel) let results = recognizer.recognizeLetter(for: drawing) return results.first!.letter case .kerasHalf: let firstRecognizer = KerasLetterRecognizer(KerasFirstHalfAlphabetModel) let firstResults = firstRecognizer.recognizeLetter(for: drawing) let secondRecognizer = KerasLetterRecognizer(KerasSecondHalfAlphabetModel) let secondResults = secondRecognizer.recognizeLetter(for: drawing) return firstResults.first!.letter + " | " + secondResults.first!.letter case .pca: let recognizer = SVMPCALetterRecognizer(SVMPCAFullAlphabetModel) let results = recognizer.recognizeLetter(for: drawing) return results.first!.letter case .pcaHalf: let firstRecognizer = SVMPCALetterRecognizer(SVMPCAFirstHalfAlphabetModel) let firstResults = firstRecognizer.recognizeLetter(for: drawing) let secondRecognizer = SVMPCALetterRecognizer(SVMPCASecondHalfAlphabetModel) let secondResults = secondRecognizer.recognizeLetter(for: drawing) return firstResults.first!.letter + " | " + secondResults.first!.letter } } } class CoreMLPlaygroundViewController: UIViewController { @IBOutlet weak var label : UILabel! @IBOutlet weak var imageView : UIImageView! @IBOutlet weak var segmentedControl : UISegmentedControl! var configuration : CoreMLModelConfiguration = .keras var drawing : LetterDrawing? @IBAction func close() { dismiss(animated: true, completion: nil) } @IBAction func didChangeSegmentedControl(sender : UISegmentedControl) { configuration = CoreMLModelConfiguration(rawValue: sender.selectedSegmentIndex)! } @IBAction func didPan(gesture : UIPanGestureRecognizer) { if drawing == nil { drawing = LetterImageDrawing() drawing?.drawingWidth = 280.0 drawing?.drawingHeight = 280.0 drawing?.strokeWidth = 12.0 } guard let currentDrawing = drawing else { return } let location = gesture.location(in: gesture.view) let path = currentDrawing.addPoint(location) UIGraphicsBeginImageContextWithOptions(CGSize(width: imageView.frame.size.height, height: imageView.frame.size.height), false, 0.0) let context = UIGraphicsGetCurrentContext()! context.setStrokeColor(UIColor.black.cgColor) path.lineJoinStyle = .round path.lineCapStyle = .round path.lineWidth = currentDrawing.strokeWidth path.stroke(with: .normal, alpha: 1) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() imageView.image = image if gesture.state == .ended { label.text = configuration.letterPrediction(for: currentDrawing) drawing = nil } } }
apache-2.0
4297ebc25e4f07334dd09ca7dbadaeba
34.775862
139
0.659759
4.917062
false
true
false
false
erkekin/EERegression
EERegression/swix/swix/matrix/m-simple-math.swift
1
2689
// // twoD-math.swift // swix // // Created by Scott Sievert on 7/10/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func apply_function(function: ndarray->ndarray, x: matrix)->matrix{ let y = function(x.flat) var z = zeros_like(x) z.flat = y return z } // TRIG func sin(x: matrix) -> matrix{ return apply_function(sin, x: x) } func cos(x: matrix) -> matrix{ return apply_function(cos, x: x) } func tan(x: matrix) -> matrix{ return apply_function(tan, x: x) } func tanh(x: matrix) -> matrix { return apply_function(tanh, x: x) } // BASIC INFO func abs(x: matrix) -> matrix{ return apply_function(abs, x: x) } func sign(x: matrix) -> matrix{ return apply_function(sign, x: x) } // POWER FUNCTION func pow(x: matrix, power: Double) -> matrix{ var y = pow(x.flat, power: power) var z = zeros_like(x) z.flat = y return z } func sqrt(x: matrix) -> matrix{ return apply_function(sqrt, x: x) } // ROUND func floor(x: matrix) -> matrix{ return apply_function(floor, x: x) } func ceil(x: matrix) -> matrix{ return apply_function(ceil, x: x) } func round(x: matrix) -> matrix{ return apply_function(round, x: x) } // LOG func log(x: matrix) -> matrix{ return apply_function(log, x: x) } // BASIC STATS func min(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = min(x.flat, y: y.flat) return z } func max(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = max(x.flat, y: y.flat) return z } // AXIS func sum(x: matrix, axis:Int = -1) -> ndarray{ // arg dim: indicating what dimension you want to sum over. For example, if dim==0, then it'll sum over dimension 0 -- it will add all the numbers in the 0th dimension, x[0..<x.shape.0, i] assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") if axis==1{ let n = x.shape.1 let m = ones((n,1)) return (x *! m).flat } else if axis==0 { let n = x.shape.0 let m = ones((1,n)) return (m *! x).flat } // the program will never get below this line assert(false) return zeros(1) } func prod(x: matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") let y = log(x) let z = sum(y, axis:axis) return exp(z) } func mean(x:matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "If you want to find the average of the whole matrix call `mean(x.flat)`") let div = axis==0 ? x.shape.0 : x.shape.1 return sum(x, axis:axis) / div.double }
gpl-2.0
a38aec67fdecc6a536a33d2fbac45545
20.512
192
0.601711
2.926007
false
false
false
false
mactive/rw-courses-note
AdvancedSwift3/Set101.playground/Contents.swift
1
1025
//: Playground - noun: a place where people can play import UIKit var letters = Set<Character>() print("letters is of type Set<Character> with \(letters.count) items") letters.insert("a") letters = [] var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] if favoriteGenres.isEmpty { print("favoriteGenres is empty") } favoriteGenres.insert("1azz") //favoriteGenres.remove("Rock") if favoriteGenres.contains("Hip hop") { print("I get up on Hip hop") } for genre in favoriteGenres { print("\(genre)") } for genre in favoriteGenres.sorted() { print("\(genre)") } let oddDigits: Set = [1,3,5,7,9] let evenDigits: Set = [0,2,4,6,8] let singleDigitPrimeNumbers: Set = [2,3,5,7] let subDigits: Set = [1,3] oddDigits.union(evenDigits).sorted() oddDigits.intersection(evenDigits).sorted() oddDigits.subtracting(singleDigitPrimeNumbers).sorted() oddDigits.intersection(singleDigitPrimeNumbers) oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted() subDigits.isSubset(of: oddDigits)
mit
80c1739112aba21d0f4ae904d797d139
21.777778
70
0.727805
3.428094
false
false
false
false
colemancda/XcodeServerSDK
XcodeServerSDK/Server Helpers/XcodeServerConstants.swift
4
2758
// // XcodeServerConstants.swift // Buildasaur // // Created by Honza Dvorsky on 11/01/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation //blueprint let XcodeBlueprintLocationsKey = "DVTSourceControlWorkspaceBlueprintLocationsKey" //dictionary let XcodeBlueprintPrimaryRemoteRepositoryKey = "DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" //string let XcodeRepositoryAuthenticationStrategiesKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryAuthenticationStrategiesKey" //dictionary let XcodeBlueprintWorkingCopyStatesKey = "DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" //dictionary let XcodeBlueprintIdentifierKey = "DVTSourceControlWorkspaceBlueprintIdentifierKey" //string let XcodeBlueprintNameKey = "DVTSourceControlWorkspaceBlueprintNameKey" //string let XcodeBlueprintVersion = "DVTSourceControlWorkspaceBlueprintVersion" //number let XcodeBlueprintRelativePathToProjectKey = "DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" //string let XcodeBlueprintWorkingCopyPathsKey = "DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" //dictionary let XcodeBlueprintRemoteRepositoriesKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" //array //locations let XcodeBranchIdentifierKey = "DVTSourceControlBranchIdentifierKey" let XcodeLocationRevisionKey = "DVTSourceControlLocationRevisionKey" let XcodeBranchOptionsKey = "DVTSourceControlBranchOptionsKey" let XcodeBlueprintLocationTypeKey = "DVTSourceControlWorkspaceBlueprintLocationTypeKey" let XcodeBlueprintRemoteRepositoryURLKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" let XcodeBlueprintRemoteRepositorySystemKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" let XcodeBlueprintRemoteRepositoryIdentifierKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" let XcodeBlueprintRemoteRepositoryCertFingerprintKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryTrustedCertFingerprintKey" let XcodeBlueprintRemoteRepositoryTrustSelfSignedCertKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryTrustSelfSignedCertKey" //repo let XcodeRepoUsernameKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryUsernameKey" let XcodeRepoAuthenticationStrategiesKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryAuthenticationStrategiesKey" let XcodeRepoAuthenticationTypeKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryAuthenticationTypeKey" let XcodeRepoPublicKeyDataKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryPublicKeyDataKey" let XcodeRepoPasswordKey = "DVTSourceControlWorkspaceBlueprintRemoteRepositoryPasswordKey" let XcodeRepoSSHKeysAuthenticationStrategy = "DVTSourceControlSSHKeysAuthenticationStrategy"
mit
5eba689db67139ec2ca0039820fdf686
64.690476
141
0.902103
5.107407
false
false
false
false
littleHH/WarePush
WarePush/Charts-master/Source/ChartsRealm/Data/RealmBubbleDataSet.swift
2
4621
// // RealmBubbleDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if NEEDS_CHARTS import Charts #endif import Realm import RealmSwift import Realm.Dynamic open class RealmBubbleDataSet: RealmBarLineScatterCandleBubbleDataSet, IBubbleChartDataSet { open override func initialize() { } public required init() { super.init() } public init(results: RLMResults<RLMObject>?, xValueField: String, yValueField: String, sizeField: String, label: String?) { _sizeField = sizeField super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label) } public convenience init(results: Results<Object>?, xValueField: String, yValueField: String, sizeField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: label) } public convenience init(results: RLMResults<RLMObject>?, xValueField: String, yValueField: String, sizeField: String) { self.init(results: results, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: "DataSet") } public convenience init(results: Results<Object>?, xValueField: String, yValueField: String, sizeField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String, yValueField: String, sizeField: String, label: String?) { _sizeField = sizeField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String, yValueField: String, sizeField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, sizeField: sizeField, label: label) } // MARK: - Data functions and accessors internal var _sizeField: String? internal var _maxSize = CGFloat(0.0) open var maxSize: CGFloat { return _maxSize } open var normalizeSizeEnabled: Bool = true open var isNormalizeSizeEnabled: Bool { return normalizeSizeEnabled } internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry { let entry = BubbleChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: object[_yValueField!] as! Double, size: object[_sizeField!] as! CGFloat) return entry } open override func calcMinMax() { if _cache.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _cache as! [BubbleChartDataEntry] { calcMinMax(entry: e) let size = e.size if size > _maxSize { _maxSize = size } } } // MARK: - Styling functions and accessors /// Sets/gets the width of the circle that surrounds the bubble when highlighted open var highlightCircleWidth: CGFloat = 2.5 // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBubbleDataSet copy._xMin = _xMin copy._xMax = _xMax copy._maxSize = _maxSize copy.highlightCircleWidth = highlightCircleWidth return copy } }
apache-2.0
27729de5ac47c71d50ca222737266a54
30.868966
179
0.637092
4.936966
false
false
false
false
lyimin/iOS-Animation-Demo
iOS-Animation学习笔记/iOS-Animation学习笔记/登录动画Demo/LoginButton.swift
1
3346
// // LoginButton.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 15/12/25. // Copyright © 2015年 xiaoming. All rights reserved. // import UIKit class LoginButton: UIButton, CAAnimationDelegate { typealias loginSuccessBlock = () -> Void // 登录成功回调 var block : loginSuccessBlock? override init(frame: CGRect) { super.init(frame: frame) // 设置加载是的layer self.layer.cornerRadius = self.height*0.5 self.layer.masksToBounds = true self.addTarget(self, action: #selector(LoginButton.loginBtnDidClick), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - AnimationDelegate func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { // 当登陆放大动画执行完后回调.并设置userinterface = true if anim is CABasicAnimation { let baseAnimation = anim as! CABasicAnimation if baseAnimation.keyPath == "transform.scale" { self.isUserInteractionEnabled = true if self.block != nil { self.block!() } } Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(LoginButton.animationStop), userInfo: nil, repeats: false) // self.layer.removeAllAnimations() } } func animationStop() { self.layer.removeAllAnimations(); } // MARK: - Action or Event func loginBtnDidClick () { self.startAnimation() } // MARK: Public Methods func loginSuccessWithBlock(_ block : loginSuccessBlock?) { self.block = block // 登陆成功后执行放大动画 let scaleAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.delegate = self scaleAnimation.fromValue = 1 scaleAnimation.toValue = 30 scaleAnimation.duration = 0.3 scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) scaleAnimation.fillMode = kCAFillModeForwards scaleAnimation.isRemovedOnCompletion = false self.layer.add(scaleAnimation, forKey: scaleAnimation.keyPath) self.loadView.stopAnimation() } // MARK: Private Methods fileprivate func startAnimation() { // 把登陆按钮变成加载按钮的动画 let widthAnimation : CABasicAnimation = CABasicAnimation(keyPath: "bounds.size.width") widthAnimation.fromValue = self.width widthAnimation.toValue = self.height widthAnimation.isRemovedOnCompletion = false widthAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) widthAnimation.duration = 0.1 widthAnimation.fillMode = kCAFillModeForwards self.layer.add(widthAnimation, forKey: widthAnimation.keyPath) // 执行加载动画 loadView.animation() self.isUserInteractionEnabled = false } // 加载loadview fileprivate lazy var loadView: LoginLoadLayer! = { let loadView : LoginLoadLayer = LoginLoadLayer(frame: self.frame) self.layer.addSublayer(loadView) return loadView }() }
mit
2d3ee14066d5f2482fe7de2aeddb0e56
33.117021
144
0.650764
4.987558
false
false
false
false
QuarkX/Quark
Sources/Quark/Core/Reflection/NominalTypeDescriptor.swift
5
1397
struct NominalTypeDescriptor : PointerType { var pointer: UnsafePointer<_NominalTypeDescriptor> var mangledName: String { return String(cString: relativePointer(base: pointer, offset: pointer.pointee.mangledName) as UnsafePointer<CChar>) } var numberOfFields: Int { return Int(pointer.pointee.numberOfFields) } var fieldOffsetVector: Int { return Int(pointer.pointee.fieldOffsetVector) } var fieldNames: [String] { let p = UnsafeRawPointer(self.pointer).assumingMemoryBound(to: Int32.self) return Array(utf8Strings: relativePointer(base: p.advanced(by: 3), offset: self.pointer.pointee.fieldNames)) } typealias FieldsTypeAccessor = @convention(c) (UnsafePointer<Int>) -> UnsafePointer<UnsafePointer<Int>> var fieldTypesAccessor: FieldsTypeAccessor? { let offset = pointer.pointee.fieldTypesAccessor guard offset != 0 else { return nil } let p = UnsafeRawPointer(self.pointer).assumingMemoryBound(to: Int32.self) let offsetPointer: UnsafePointer<Int> = relativePointer(base: p.advanced(by: 4), offset: offset) return unsafeBitCast(offsetPointer, to: FieldsTypeAccessor.self) } } struct _NominalTypeDescriptor { var mangledName: Int32 var numberOfFields: Int32 var fieldOffsetVector: Int32 var fieldNames: Int32 var fieldTypesAccessor: Int32 }
mit
4f9c2d324cf107432dc6afaa2b5eb1d8
35.763158
123
0.717251
4.535714
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/tests/Messages/OWSUDManagerTest.swift
1
10377
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import XCTest import Foundation import Curve25519Kit import SignalCoreKit import SignalMetadataKit @testable import SignalServiceKit class MockCertificateValidator: NSObject, SMKCertificateValidator { @objc public func throwswrapped_validate(senderCertificate: SMKSenderCertificate, validationTime: UInt64) throws { // Do not throw } @objc public func throwswrapped_validate(serverCertificate: SMKServerCertificate) throws { // Do not throw } } // MARK: - class OWSUDManagerTest: SSKBaseTestSwift { // MARK: - Dependencies private var tsAccountManager: TSAccountManager { return TSAccountManager.sharedInstance() } private var udManager: OWSUDManagerImpl { return SSKEnvironment.shared.udManager as! OWSUDManagerImpl } private var profileManager: ProfileManagerProtocol { return SSKEnvironment.shared.profileManager } // MARK: - Setup/Teardown let aliceE164 = "+13213214321" let aliceUuid = UUID() lazy var aliceAddress = SignalServiceAddress(uuid: aliceUuid, phoneNumber: aliceE164) override func setUp() { super.setUp() tsAccountManager.registerForTests(withLocalNumber: aliceE164, uuid: aliceUuid) // Configure UDManager self.write { transaction in self.profileManager.setProfileKeyData(OWSAES256Key.generateRandom().keyData, for: self.aliceAddress, transaction: transaction) } udManager.certificateValidator = MockCertificateValidator() let senderCertificate = try! SMKSenderCertificate(serializedData: buildSenderCertificateProto().serializedData()) udManager.setSenderCertificate(senderCertificate.serializedData) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - Tests func testMode_self() { XCTAssert(udManager.hasSenderCertificate()) XCTAssert(tsAccountManager.isRegistered) guard let localAddress = tsAccountManager.localAddress else { XCTFail("localAddress was unexpectedly nil") return } XCTAssert(localAddress.isValid) var udAccess: OWSUDAccess! XCTAssertEqual(.enabled, udManager.unidentifiedAccessMode(forAddress: aliceAddress)) udAccess = udManager.udAccess(forAddress: aliceAddress, requireSyncAccess: false) XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.unknown, address: aliceAddress) XCTAssertEqual(.unknown, udManager.unidentifiedAccessMode(forAddress: aliceAddress)) udAccess = udManager.udAccess(forAddress: aliceAddress, requireSyncAccess: false)! XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.disabled, address: aliceAddress) XCTAssertEqual(.disabled, udManager.unidentifiedAccessMode(forAddress: aliceAddress)) XCTAssertNil(udManager.udAccess(forAddress: aliceAddress, requireSyncAccess: false)) udManager.setUnidentifiedAccessMode(.enabled, address: aliceAddress) XCTAssert(UnidentifiedAccessMode.enabled == udManager.unidentifiedAccessMode(forAddress: aliceAddress)) udAccess = udManager.udAccess(forAddress: aliceAddress, requireSyncAccess: false)! XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.unrestricted, address: aliceAddress) XCTAssertEqual(.unrestricted, udManager.unidentifiedAccessMode(forAddress: aliceAddress)) udAccess = udManager.udAccess(forAddress: aliceAddress, requireSyncAccess: false)! XCTAssert(udAccess.isRandomKey) } func testMode_noProfileKey() { XCTAssert(udManager.hasSenderCertificate()) XCTAssert(tsAccountManager.isRegistered) guard let localAddress = tsAccountManager.localAddress else { XCTFail("localAddress was unexpectedly nil") return } XCTAssert(localAddress.isValid) // Ensure UD is enabled by setting our own access level to enabled. udManager.setUnidentifiedAccessMode(.enabled, address: localAddress) let bobRecipientAddress = SignalServiceAddress(phoneNumber: "+13213214322") XCTAssertFalse(bobRecipientAddress.isLocalAddress) var udAccess: OWSUDAccess! XCTAssertEqual(UnidentifiedAccessMode.unknown, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssert(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.unknown, address: bobRecipientAddress) XCTAssertEqual(UnidentifiedAccessMode.unknown, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssert(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.disabled, address: bobRecipientAddress) XCTAssertEqual(UnidentifiedAccessMode.disabled, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) XCTAssertNil(udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)) udManager.setUnidentifiedAccessMode(.enabled, address: bobRecipientAddress) XCTAssertEqual(UnidentifiedAccessMode.enabled, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) XCTAssertNil(udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)) // Bob should work in unrestricted mode, even if he doesn't have a profile key. udManager.setUnidentifiedAccessMode(.unrestricted, address: bobRecipientAddress) XCTAssertEqual(UnidentifiedAccessMode.unrestricted, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssert(udAccess.isRandomKey) } func testMode_withProfileKey() { XCTAssert(udManager.hasSenderCertificate()) XCTAssert(tsAccountManager.isRegistered) guard let localAddress = tsAccountManager.localAddress else { XCTFail("localAddress was unexpectedly nil") return } XCTAssert(localAddress.isValid) // Ensure UD is enabled by setting our own access level to enabled. udManager.setUnidentifiedAccessMode(.enabled, address: localAddress) let bobRecipientAddress = SignalServiceAddress(phoneNumber: "+13213214322") XCTAssertFalse(bobRecipientAddress.isLocalAddress) self.write { transaction in self.profileManager.setProfileKeyData(OWSAES256Key.generateRandom().keyData, for: bobRecipientAddress, transaction: transaction) } var udAccess: OWSUDAccess! XCTAssertEqual(.unknown, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.unknown, address: bobRecipientAddress) XCTAssertEqual(.unknown, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.disabled, address: bobRecipientAddress) XCTAssertEqual(.disabled, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) XCTAssertNil(udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)) udManager.setUnidentifiedAccessMode(.enabled, address: bobRecipientAddress) XCTAssertEqual(.enabled, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssertFalse(udAccess.isRandomKey) udManager.setUnidentifiedAccessMode(.unrestricted, address: bobRecipientAddress) XCTAssertEqual(.unrestricted, udManager.unidentifiedAccessMode(forAddress: bobRecipientAddress)) udAccess = udManager.udAccess(forAddress: bobRecipientAddress, requireSyncAccess: false)! XCTAssert(udAccess.isRandomKey) } // MARK: - Util func buildServerCertificateProto() -> SMKProtoServerCertificate { let serverKey = try! Curve25519.generateKeyPair().ecPublicKey().serialized let certificateData = try! SMKProtoServerCertificateCertificate.builder(id: 1, key: serverKey ).buildSerializedData() let signatureData = Randomness.generateRandomBytes(ECCSignatureLength) let wrapperProto = SMKProtoServerCertificate.builder(certificate: certificateData, signature: signatureData) return try! wrapperProto.build() } func buildSenderCertificateProto() -> SMKProtoSenderCertificate { let expires = NSDate.ows_millisecondTimeStamp() + kWeekInMs let identityKey = try! Curve25519.generateKeyPair().ecPublicKey().serialized let signer = buildServerCertificateProto() let certificateBuilder = SMKProtoSenderCertificateCertificate.builder(senderDevice: 1, expires: expires, identityKey: identityKey, signer: signer) certificateBuilder.setSenderE164(aliceE164) certificateBuilder.setSenderUuid(aliceUuid.uuidString) let certificateData = try! certificateBuilder.buildSerializedData() let signatureData = Randomness.generateRandomBytes(ECCSignatureLength) let wrapperProto = try! SMKProtoSenderCertificate.builder(certificate: certificateData, signature: signatureData).build() return wrapperProto } }
gpl-3.0
fd0093d90e91f200d2b15537f3b9d161
45.12
140
0.71803
5.467334
false
false
false
false
fotock/SanIcon-Swift
SanIconSwift/SanIcon/SanIcon.swift
1
53349
// // SanIcon.swift // SanIconSwift // // Created by Shelley Shyan on 15-4-10. // Copyright (c) 2015年 Sanfriend Co, Ltd. All rights reserved. // import UIKit import CoreText public enum SanIcon: String { case ArrowUp = "\u{F110}" case ArrowDown = "\u{F111}" case ArrowLeft = "\u{F112}" case ArrowRight = "\u{F113}" case ArrowRoundUp = "\u{F114}" case ArrowRoundDown = "\u{F115}" case ArrowRoundLeft = "\u{F116}" case ArrowRoundRight = "\u{F117}" case ArrowUpThin = "\u{F118}" case ArrowDownThin = "\u{F119}" case ArrowLeftThin = "\u{F120}" case ArrowRightThin = "\u{F121}" case CaretUp = "\u{F122}" case CaretDown = "\u{F123}" case CaretLeft = "\u{F124}" case CaretRight = "\u{F125}" case ChevronUpBig = "\u{F126}" case ChevronDownBig = "\u{F127}" case ChevronLeftBig = "\u{F128}" case ChevronRightBig = "\u{F129}" case ChevronUpThin = "\u{F130}" case ChevronDownThin = "\u{F131}" case ChevronLeftThin = "\u{F132}" case ChevronRightThin = "\u{F133}" case ChevronLeft = "\u{F134}" case ChevronRight = "\u{F135}" case Add = "\u{F136}" case Minus = "\u{F137}" case Remove = "\u{F138}" case AddRound = "\u{F139}" case MinusRound = "\u{F140}" case RemoveRound = "\u{F141}" case PlusAdd = "\u{F142}" case MinusRemove = "\u{F143}" case Plus = "\u{F144}" case Minus3 = "\u{F145}" case PlusCircle = "\u{F146}" case MinusCircle = "\u{F147}" case PlusOutline = "\u{F148}" case MinusCircle2 = "\u{F149}" case PlusCircleOutline = "\u{F150}" case MinusCircleOutline = "\u{F151}" case CheckCircle = "\u{F152}" case RemoveDeleteCircle = "\u{F153}" case CheckMarkCircle = "\u{F154}" case CloseCircle = "\u{F155}" case CheckMarkCircleOutline = "\u{F156}" case CloseCircleOutline = "\u{F157}" case CheckMark4 = "\u{F158}" case CloseEmpty = "\u{F159}" case CheckMark3 = "\u{F160}" case Remove2 = "\u{F161}" case MenuRound = "\u{F162}" case MenuSmall = "\u{F163}" case Drag = "\u{F164}" case DragSmall = "\u{F165}" case More2 = "\u{F166}" case More = "\u{F167}" case MoreOutline = "\u{F168}" case MoreOption = "\u{F169}" case ClockAlarm1 = "\u{F170}" case ClockAlarmOutline = "\u{F171}" case ClockAlarm = "\u{F172}" case Clock3Outline = "\u{F173}" case Clock3 = "\u{F174}" case ClockOutline = "\u{F175}" case ClockTimeOutline = "\u{F176}" case ClockTime = "\u{F177}" case StopwatchOutline = "\u{F178}" case Stopwatch = "\u{F179}" case Stopwatch1 = "\u{F180}" case AtThin = "\u{F181}" case AtThick = "\u{F182}" case AtBold = "\u{F183}" case Heart = "\u{F184}" case HeartSmall = "\u{F185}" case HeartSmallOutline = "\u{F186}" case Heart1 = "\u{F187}" case Heart1Empty = "\u{F188}" case Star2 = "\u{F189}" case Star8 = "\u{F190}" case Star1 = "\u{F191}" case Star8Empty = "\u{F192}" case Star9 = "\u{F193}" case Star9Empty = "\u{F194}" case Star9Half = "\u{F195}" case Star9Half1 = "\u{F196}" case Eye3 = "\u{F197}" case Eye = "\u{F198}" case EyeOutline = "\u{F199}" case Eye4 = "\u{F200}" case Flag = "\u{F201}" case FlagOutline = "\u{F202}" case Flag3 = "\u{F203}" case Flag1 = "\u{E000}" case Contact = "\u{E001}" case ContactOutline = "\u{E002}" case ContactAdd = "\u{E003}" case Contact2 = "\u{E004}" case ContactAdd2 = "\u{E005}" case ContactOutlineAdd = "\u{E006}" case ContactBig = "\u{E007}" case ContactAdd3 = "\u{E008}" case UserCircle = "\u{E009}" case UserCircleOutline = "\u{E00A}" case ContactGroup = "\u{E00B}" case ContactGroupOutline = "\u{E00C}" case Contacts1 = "\u{E00D}" case Bell = "\u{E00E}" case BellAlarm = "\u{E00F}" case BellOutline = "\u{E010}" case Lightbulb1 = "\u{E011}" case Lightbulb2 = "\u{E012}" case LightbulbOutline = "\u{E013}" case Lightbulb = "\u{E014}" case Info = "\u{E015}" case InfoSmall = "\u{E016}" case InfoSmallCircleOutline = "\u{E017}" case InfoSmallCircle = "\u{E018}" case InfoCircle2 = "\u{E019}" case InfoCircle = "\u{E01A}" case Home = "\u{E01B}" case Question = "\u{E01C}" case QuestionCircle = "\u{E01D}" case QuestionCircle1 = "\u{E01E}" case QuestionCircleOutline = "\u{E01F}" case QuestionSmall = "\u{E020}" case Search2 = "\u{E021}" case Search3 = "\u{E022}" case Search = "\u{E023}" case SearchOutline = "\u{E024}" case Gear4 = "\u{E025}" case Gear3 = "\u{E026}" case Gear2 = "\u{E027}" case Gear1 = "\u{E028}" case Gear1Outline = "\u{E029}" case Cog = "\u{E02A}" case CogOutline = "\u{E02B}" case TagsRound = "\u{E02C}" case Tags = "\u{E02D}" case TagRound = "\u{E02E}" case Tag = "\u{E02F}" case TagOutline = "\u{E030}" case Photos = "\u{E031}" case PhotosOutline = "\u{E032}" case AlbumsOutline = "\u{E033}" case Albums = "\u{E034}" case PhotoPicture = "\u{E035}" case PhotoImage = "\u{E036}" case FolderSmall = "\u{E037}" case FolderSmallOutline = "\u{E038}" case FolderOpen = "\u{E039}" case FolderOpen2 = "\u{E03A}" case Camera1 = "\u{E03B}" case CameraOutline = "\u{E03C}" case Camera = "\u{E03D}" case Camera2 = "\u{E03E}" case Box = "\u{E03F}" case BoxOutline = "\u{E040}" case Briefcase = "\u{E041}" case Briefcase2 = "\u{E042}" case BriefcaseOutline = "\u{E043}" case Bag = "\u{E044}" case Browsers = "\u{E045}" case BrowsersOutline = "\u{E046}" case Compose = "\u{E047}" case ComposeEdit = "\u{E048}" case ComposeEditOutline = "\u{E049}" case Compass = "\u{E04A}" case EditRedo = "\u{E04B}" case EditRedoOutline = "\u{E04C}" case EditForward = "\u{E04D}" case EditReply = "\u{E04E}" case EditReplyAll = "\u{E04F}" case EditUndo = "\u{E050}" case EditUndoOutline = "\u{E051}" case NavigateLocation = "\u{E052}" case NavigateOutline = "\u{E053}" case SendMail = "\u{E054}" case SendMailOutline = "\u{E055}" case MailSend = "\u{E056}" case Contacts = "\u{E057}" case ContactsSocial = "\u{E058}" case Mic5 = "\u{E059}" case Mic3 = "\u{E05A}" case Mic = "\u{E05B}" case MicOutline = "\u{E05C}" case MicOff = "\u{E05D}" case Mic4 = "\u{E05E}" case Mic2 = "\u{E05F}" case Play = "\u{E060}" case Play2 = "\u{E061}" case PlayOutline = "\u{E062}" case Pause = "\u{E063}" case Pause2 = "\u{E064}" case PauseOutline = "\u{E065}" case SkipbackwardOutline = "\u{E066}" case Skipbackward = "\u{E067}" case Skipforward = "\u{E068}" case SkipforwardOutline = "\u{E069}" case Rewind = "\u{E06A}" case RewindOutline = "\u{E06B}" case FastForward = "\u{E06C}" case FastForwardOutline = "\u{E06D}" case FastBackward = "\u{E06E}" case FastForward1 = "\u{E06F}" case HandLike = "\u{E070}" case HandUnlike = "\u{E071}" case Android = "\u{E072}" case AndroidOutine = "\u{E073}" case Apple = "\u{E074}" case AppleOutline = "\u{E075}" case Windows = "\u{E076}" case WindowsOutline = "\u{E077}" case Linux = "\u{E078}" case Wordpress = "\u{E079}" case WordpressOutline = "\u{E07A}" case Trash2 = "\u{E07B}" case Trash = "\u{E07C}" case Trash4 = "\u{E07D}" case Trash3 = "\u{E07E}" case TrashOutline = "\u{E07F}" case SpeakerNo = "\u{E080}" case Speaker = "\u{E081}" case VolumeLow = "\u{E082}" case VolumeMedium = "\u{E083}" case VolumeHigh = "\u{E084}" case SquareUpload = "\u{E085}" case SquareUploadOutline = "\u{E086}" case CloudUpload2 = "\u{E087}" case CloudUpload = "\u{E088}" case CloudUploadOutline = "\u{E089}" case SignalWifi = "\u{E08A}" case Wifi = "\u{E08B}" case SignalBar = "\u{E08C}" case Refresh = "\u{E08D}" case Refresh1 = "\u{E08E}" case RefreshCircle = "\u{E08F}" case RefreshCircleOutline = "\u{E090}" case ReloadThin = "\u{E091}" case Loop = "\u{E092}" case Rss = "\u{E093}" case RssOutline = "\u{E094}" case Share = "\u{E095}" case MarkPin = "\u{E096}" case Mark = "\u{E097}" case MarkOutline = "\u{E098}" case MarkPin1 = "\u{E099}" case Speedometer = "\u{E09A}" case Speedometer1 = "\u{E09B}" case SpeedometerOutline = "\u{E09C}" case TimerClock = "\u{E09D}" case TimerClockOutline = "\u{E09E}" case Screen = "\u{E09F}" case Screen1 = "\u{E0A0}" case ScreenOutline = "\u{E0A1}" case PhotosPictures = "\u{E0A2}" case Female = "\u{E0A3}" case Male = "\u{E0A4}" case FemaleSymbol = "\u{E0A5}" case MaleSymbol = "\u{E0A6}" case Keypad2 = "\u{E0A7}" case KeypadOutline = "\u{E0A8}" case MailLetter = "\u{E0A9}" case MailLetter2 = "\u{E0AA}" case MailLetterOutline = "\u{E0AB}" case LogIn = "\u{E0AC}" case LogOut = "\u{E0AD}" case LogOut1 = "\u{E0AE}" case LockBig = "\u{E0AF}" case Lock = "\u{E0B0}" case LockOutline = "\u{E0B1}" case Key = "\u{E0B2}" case Key1 = "\u{E0B3}" case Lock1 = "\u{E0B4}" case Chatbubble = "\u{E0B5}" case ChatbubbleOutline = "\u{E0B6}" case ChatTalk = "\u{E0B7}" case ChatTalkOutline = "\u{E0B8}" case TalkChatBubble = "\u{E0B9}" case TalkChatBubble2 = "\u{E0BA}" case TalkChatBubble1 = "\u{E0BB}" case TalkChat = "\u{E0BC}" case TalkChat1 = "\u{E0BD}" case MusicNote = "\u{E0BE}" case MusicNote2 = "\u{E0BF}" case MusicSong = "\u{E0C0}" case Infinite = "\u{E0C1}" case InfiniteOutline = "\u{E0C2}" case InboxBox = "\u{E0C3}" case Inbox = "\u{E0C4}" case InboxOutline = "\u{E0C5}" case FlashElectric = "\u{E0C6}" case FlashElectric2 = "\u{E0C7}" case ElectricFlashOutline = "\u{E0C8}" case BatteryEmpty = "\u{E0C9}" case BatteryLow = "\u{E0CA}" case Battery = "\u{E0CB}" case BatteryFull = "\u{E0CC}" case BatteryCharging = "\u{E0CD}" case BatteryMedium = "\u{E0CE}" case Bluetooth = "\u{E0CF}" case MobilePhone = "\u{E0D0}" case Call = "\u{E0D1}" case CallPhone = "\u{E0D2}" case CallPhoneOutline = "\u{E0D3}" case Bitcoin = "\u{E0D4}" case BitcoinOutline = "\u{E0D5}" case Bookmark = "\u{E0D6}" case Bubbles = "\u{E0D7}" case Brightness = "\u{E0D8}" case BrightnessOutline = "\u{E0D9}" case CheckMark2 = "\u{E0DA}" case Buffer = "\u{E0DB}" case BufferOutline = "\u{E0DC}" case Bug = "\u{E0DD}" case Calculator = "\u{E0DE}" case Calculator2 = "\u{E0DF}" case CalculatorOutline = "\u{E0E0}" case Calendar = "\u{E0E1}" case Calendar3 = "\u{E0E2}" case CalendarOutline = "\u{E0E3}" case Calendar2 = "\u{E0E4}" case CheckMark = "\u{E0E5}" case Car = "\u{E0E6}" case CircleFilled = "\u{E0E7}" case CircleFilledOutline = "\u{E0E8}" case CloudSun = "\u{E0E9}" case CloudSunOutline = "\u{E0EA}" case CloudDownload = "\u{E0EB}" case CloudDownloadOutline = "\u{E0EC}" case CloudMoon = "\u{E0ED}" case CloudMoonOutline = "\u{E0EE}" case CloudRain = "\u{E0EF}" case CloudRainOutline = "\u{E0F0}" case CloudSmall = "\u{E0F1}" case CloudSmallOutline = "\u{E0F2}" case CloudLightning = "\u{E0F3}" case CloudLightningOutline = "\u{E0F4}" case Cloud = "\u{E0F5}" case CloudOutline = "\u{E0F7}" case Copy = "\u{E0F8}" case CopyOutline = "\u{E0F9}" case EyeGlass = "\u{E0FA}" case EyeGlassOutline = "\u{E0FB}" case Globe = "\u{E0FC}" case GlobeOutline = "\u{E0FD}" case Github = "\u{E0FE}" case GithubOutline = "\u{E0FF}" case Filmstrip = "\u{E100}" case FilmstripOutline = "\u{E101}" case Moon = "\u{E102}" case MoonOutline = "\u{E103}" case DeviceLaptop = "\u{E104}" case WineGlass = "\u{E105}" case WineGlassOutline = "\u{E106}" case Unlock = "\u{E107}" case Unlock2 = "\u{E108}" case UnlockOutline = "\u{E109}" case VideoCamera = "\u{E10A}" case VideoCameraOutline = "\u{E10B}" case DeviceTablet = "\u{E10C}" case SquareDownload = "\u{E10D}" case SquareDownloadOutline = "\u{E10E}" case ShoppingCart = "\u{E10F}" case ShoppingCartOutline = "\u{E110}" case Print1 = "\u{E111}" case Print = "\u{E112}" case PrintOutline = "\u{E113}" case ReturnLeft = "\u{E114}" case ReturnLeft1 = "\u{E115}" case ResizeArrowUp = "\u{E116}" case ResizeArrowDown = "\u{E117}" case ResizeArrow2 = "\u{E118}" case Snowy = "\u{E119}" case PowerOff = "\u{E11A}" case PencilEdit = "\u{E11B}" case Pin = "\u{E11C}" case Pie2 = "\u{E11D}" case PieOutline = "\u{E11E}" case Pie = "\u{E11F}" case Flight2 = "\u{E120}" case Random = "\u{E121}" case PaperClip = "\u{E122}" case Parentheses = "\u{E123}" case PaperAirplane = "\u{E124}" case Nuclear = "\u{E125}" case Mixer2 = "\u{E126}" case Mixer = "\u{E127}" case Map = "\u{E128}" case Book = "\u{E129}" case ToolHammer = "\u{E12A}" case ToolFork = "\u{E12B}" case ToolSpoon = "\u{E12C}" case ToolMagnet = "\u{E12D}" case ToolKnife = "\u{E12E}" case Ipod = "\u{E12F}" case Medkit = "\u{E130}" case Medkit2 = "\u{E131}" case MedkitOutline = "\u{E132}" case Loading1 = "\u{E133}" case Loading2 = "\u{E134}" case Loading3 = "\u{E135}" case Loading4 = "\u{E136}" case Location = "\u{E137}" case NoteFile = "\u{E138}" case LetterMail = "\u{E139}" case Leaf = "\u{E13A}" case Headphone = "\u{E13B}" case Hashtag = "\u{E13C}" case Grid = "\u{E13D}" case Keypad = "\u{E13E}" case Link = "\u{E13F}" case IceCream = "\u{E140}" case Gamepad2 = "\u{E141}" case Gamepad = "\u{E142}" case Friends = "\u{E143}" case FileDocumentText = "\u{E144}" case Filing = "\u{E145}" case GlobeWorld = "\u{E146}" case GlobeWorld1 = "\u{E147}" case GlassWine = "\u{E148}" case ElectricNoOff = "\u{E149}" case Exclamation = "\u{E14A}" case Eject = "\u{E14B}" case Egg = "\u{E14C}" case Dropdown = "\u{E14D}" case DropboxOutline = "\u{E14E}" case Dropbox = "\u{E14F}" case DownloadInbox = "\u{E150}" case CircleDownload = "\u{E151}" case Document = "\u{E152}" case DisplayContrast = "\u{E153}" case Disc = "\u{E154}" case CupCoffee = "\u{E155}" case Crosshairpinpoint = "\u{E156}" case Contrast = "\u{E157}" case CodeWorking = "\u{E158}" case CodeDownload = "\u{E159}" case Code = "\u{E15A}" case Clipboard = "\u{E15B}" case Clock2 = "\u{E15C}" case BookmarkOutline = "\u{E15D}" case Female1 = "\u{E15E}" case Male1 = "\u{E15F}" case Foot = "\u{E160}" case Microphone = "\u{E161}" case ShoppingCart1 = "\u{E162}" case ListBullet = "\u{E163}" case ListNumber = "\u{E164}" case Photo = "\u{E165}" case Mountains = "\u{E166}" case Torso = "\u{E167}" case TorsoFemale = "\u{E168}" case ZoomIn = "\u{E169}" case ZoomOut = "\u{E16A}" case Yen = "\u{E16B}" case Star4 = "\u{E16C}" case AngleDoubleUp = "\u{E16D}" case AngleDoubleDown = "\u{E16E}" case AngleDoubleLeft = "\u{E16F}" case AngleDoubleRight = "\u{E170}" case Font = "\u{E171}" case FighterJet = "\u{E172}" case Like = "\u{E173}" case Unlike = "\u{E174}" case ZeroCircle = "\u{E175}" case OneCircle = "\u{E176}" case TwoCircle = "\u{E177}" case ThreeCircle = "\u{E178}" case FourCircle = "\u{E179}" case FiveCircle = "\u{E17A}" case SixCircle = "\u{E17B}" case SevenCircle = "\u{E17C}" case EightCircle = "\u{E17D}" case NineCircle = "\u{E17E}" case PlusCircle1 = "\u{E17F}" case MinusCircle1 = "\u{E180}" case ArrowUpThinCircle = "\u{E181}" case ArrowDownThinCircle = "\u{E182}" case ArrowLeftThinCircle = "\u{E183}" case ArrowRightThinCircle = "\u{E184}" case ArrowLeftLightCircle = "\u{E185}" case ArrowRightLightCircle = "\u{E186}" case SearchCircle = "\u{E187}" case ShareCircle = "\u{E188}" case ShareOutlineCircle = "\u{E189}" case ArrowRightBoldCircle = "\u{E18A}" case ArrowLeftBoldCircle = "\u{E18B}" case ArrowRightBoldRoundCircle = "\u{E18C}" case ArrowLeftBoldRoundCircle = "\u{E18D}" case CrossCircle = "\u{E18E}" case MenuCircle = "\u{E18F}" case InfoCircle1 = "\u{E190}" case ExclamationCircle = "\u{E191}" case Star5 = "\u{E192}" case Star5Empty = "\u{E193}" case Up = "\u{E194}" case UpBold = "\u{E195}" case DownBold = "\u{E196}" case Down = "\u{E197}" case Share1 = "\u{E198}" case ChevronUpMini = "\u{E199}" case ChevronDownMini = "\u{E19A}" case ChevronLeftMini = "\u{E19B}" case ChevronRightMini = "\u{E19C}" case UpOpenBig = "\u{E19D}" case DownOpenBig = "\u{E19E}" case LeftOpenBig = "\u{E19F}" case RightOpenBig = "\u{E1A0}" case UpOpen = "\u{E1A1}" case DownOpen = "\u{E1A2}" case LeftOpen = "\u{E1A3}" case RightOpen = "\u{E1A4}" case Stop = "\u{E1A5}" case Storage = "\u{E1A6}" case SwapExchage = "\u{E1A7}" case Wrench = "\u{E1A8}" case SettingTools = "\u{E1A9}" case Sort = "\u{E1AA}" case ArrowGraphDownLeft = "\u{E1AB}" case ArrowGraphDownRight = "\u{E1AC}" case ArrowGraphUpLeft = "\u{E1AD}" case ArrowGraphUpRight = "\u{E1AE}" case ArrowMove = "\u{E1AF}" case ArrowUpLeft = "\u{E1B0}" case ArrowUpRight = "\u{E1B1}" case ArrowDownLeft = "\u{E1B2}" case ArrowDownRight = "\u{E1B3}" case LockStreamline = "\u{E1B4}" case UnlockStreamline = "\u{E1B5}" case CommentStreamline = "\u{E1B6}" case ShoppingInStreamline = "\u{E1B7}" case ShoppingOutStreamline = "\u{E1B8}" case IpadStreamline = "\u{E1B9}" case IphoneStreamline = "\u{E1BA}" case IpodStreamline = "\u{E1BB}" case LaptopStreamline = "\u{E1BC}" case ComputerStreamline = "\u{E1BE}" case EditStreamline = "\u{E1BF}" case EmailStreamline = "\u{E1C0}" case DatabaseStreamline = "\u{E1C1}" case GarbageStreamline = "\u{E1C2}" case PictureStreamline = "\u{E1C3}" case PictureStreamline1 = "\u{E1C4}" case HomeStreamline = "\u{E1C5}" case WifiLow = "\u{E1C6}" case WifiMedium = "\u{E1C7}" case WifiFull = "\u{E1C8}" case CloudUpload1 = "\u{E1C9}" case CloudDownload1 = "\u{E1CA}" case GitBranch = "\u{E1CB}" case GitCompare = "\u{E1CC}" case GitCommit = "\u{E1CD}" case GitMerge = "\u{E1CE}" case GitPullRequest = "\u{E1CF}" case Graph = "\u{E200}" case Globe1 = "\u{E201}" case MortarBoard = "\u{E202}" case Rocket = "\u{E203}" case Pulse = "\u{E204}" case Zap = "\u{E205}" case Tools = "\u{E206}" case LogIn1 = "\u{E207}" case LogOut11 = "\u{E208}" case Mail = "\u{E209}" case Key2 = "\u{E210}" case Lock2 = "\u{E211}" case Star = "\u{E212}" case Archive = "\u{E213}" case Beaker = "\u{E214}" case BeakerScienceFlask = "\u{E215}" case Bookmark1 = "\u{E216}" case CreditCard = "\u{E217}" case EyeDisabled = "\u{E220}" case ForkRepo = "\u{E221}" case HandBlock = "\u{E222}" case Navigate = "\u{E223}" case RadioWaves = "\u{E224}" case Record2 = "\u{E225}" case Speakerphone = "\u{E226}" case Umbrella = "\u{E227}" case Usb = "\u{E228}" case YoutubePlay = "\u{E229}" case YoutubePlayOutline = "\u{E230}" case AddressBook = "\u{E231}" case Bluetooth1 = "\u{E232}" case Paperclip = "\u{E233}" case Torsos = "\u{E234}" case TorsosAll = "\u{E235}" case Trophy = "\u{E236}" case Thumbnails = "\u{E237}" case ToolWrench = "\u{E238}" case Widget = "\u{E239}" case Yen1 = "\u{E240}" case Refresh4 = "\u{E241}" case Bookmark2 = "\u{E242}" case Attach = "\u{E243}" case Address = "\u{E250}" case Book1 = "\u{E251}" case Basket = "\u{E252}" case DocLandscape = "\u{E253}" case Doc = "\u{E254}" case Direction = "\u{E255}" case Database = "\u{E256}" case CreditCard1 = "\u{E257}" case Cog1 = "\u{E258}" case Dot3 = "\u{E259}" case Home1 = "\u{E260}" case Location1 = "\u{E261}" case Mail1 = "\u{E262}" case Map1 = "\u{E263}" case Megaphone = "\u{E264}" case Menu = "\u{E265}" case DeviceMobile = "\u{E266}" case DeviceMonitor = "\u{E267}" case Moon1 = "\u{E268}" case Power = "\u{E269}" case Star3 = "\u{E270}" case SocialBaidu = "\u{E271}" case SocialBaiduCircle = "\u{E272}" case SocialQq = "\u{E273}" case SocialQqCircle = "\u{E274}" case SocialSina = "\u{E275}" case SocialSinaCircle = "\u{E276}" case SocialWeibo = "\u{E277}" case SocialWeiboCircle = "\u{E278}" case SocialIqyi = "\u{E281}" case SocialIqyiCircle = "\u{E282}" case SocialDouban = "\u{E283}" case Flight3 = "\u{E284}" case ShareOutline = "\u{E285}" case LinkExternal = "\u{E286B}" case Code1 = "\u{E287}" case Dollar = "\u{E288}" case Terminal = "\u{E289}" case Unlock1 = "\u{E290}" case Unlock3 = "\u{E291}" case ZoomIn1 = "\u{E292}" case ZoomOut1 = "\u{E293}" case Ccw = "\u{E294}" case Cancel = "\u{E295}" case Check = "\u{E296}" case Dot2 = "\u{E297}" case Dot = "\u{E298}" case Docs = "\u{E299}" case DownloadInbox2 = "\u{E300}" case Flight = "\u{E301}" case Flash = "\u{E302}" case Export = "\u{E303}" case Tools1 = "\u{E304}" case Signal = "\u{E305}" case ChartBar = "\u{E306}" case ChartPie = "\u{E307}" case ChartLine = "\u{E308}" case Code2 = "\u{E309}" case Vcard = "\u{E310}" case Share2 = "\u{E311}" case Milestone = "\u{E312}" case MessageTalk = "\u{E313}" case User2 = "\u{E314}" case Timer = "\u{E315}" case LinkStreamline = "\u{E316}" case SettingsStreamline1 = "\u{E317}" case Bookmark3 = "\u{E318}" case BookBookmark = "\u{E319}" case Burst = "\u{E31A}" case BurstNew = "\u{E31B}" case MaleFemale = "\u{E31C}" case PageExport = "\u{E31D}" case Refresh2 = "\u{E31E}" case BarChart = "\u{E320}" case Barcode = "\u{E321}" case User = "\u{E322}" case UserAdd = "\u{E323}" case Googleplus = "\u{E324}" case Googleplus1 = "\u{E325}" case Googleplus2 = "\u{E326}" case GoogleplusThick = "\u{E327}" case Facebook = "\u{E328}" case FacebookOutline = "\u{E329}" case Linkedin = "\u{E330}" case LinkedinOutline = "\u{E331}" case Pinterest = "\u{E332}" case PinterestOutline = "\u{E333}" case Twitter = "\u{E334}" case TwitterOutline = "\u{E335}" case Tumblr = "\u{E336}" case TumblrOutline = "\u{E337}" case Mail2 = "\u{E338}" static let allIcons = [ArrowUp, ArrowDown, ArrowLeft, ArrowRight, ArrowRoundUp, ArrowRoundDown, ArrowRoundLeft, ArrowRoundRight, ArrowUpThin, ArrowDownThin, ArrowLeftThin, ArrowRightThin, CaretUp, CaretDown, CaretLeft, CaretRight, ChevronUpBig, ChevronDownBig, ChevronLeftBig, ChevronRightBig, ChevronUpThin, ChevronDownThin, ChevronLeftThin, ChevronRightThin, ChevronLeft, ChevronRight, Add, Minus, Remove, AddRound, MinusRound, RemoveRound, PlusAdd, MinusRemove, Plus, Minus3, PlusCircle, MinusCircle, PlusOutline, MinusCircle2, PlusCircleOutline, MinusCircleOutline, CheckCircle, RemoveDeleteCircle, CheckMarkCircle, CloseCircle, CheckMarkCircleOutline, CloseCircleOutline, CheckMark4, CloseEmpty, CheckMark3, Remove2, MenuRound, MenuSmall, Drag, DragSmall, More2, More, MoreOutline, MoreOption, ClockAlarm1, ClockAlarmOutline, ClockAlarm, Clock3Outline, Clock3, ClockOutline, ClockTimeOutline, ClockTime, StopwatchOutline, Stopwatch, Stopwatch1, AtThin, AtThick, AtBold, Heart, HeartSmall, HeartSmallOutline, Heart1, Heart1Empty, Star2, Star8, Star1, Star8Empty, Star9, Star9Empty, Star9Half, Star9Half1, Eye3, Eye, EyeOutline, Eye4, Flag, FlagOutline, Flag3, Flag1, Contact, ContactOutline, ContactAdd, Contact2, ContactAdd2, ContactOutlineAdd, ContactBig, ContactAdd3, UserCircle, UserCircleOutline, ContactGroup, ContactGroupOutline, Contacts1, Bell, BellAlarm, BellOutline, Lightbulb1, Lightbulb2, LightbulbOutline, Lightbulb, Info, InfoSmall, InfoSmallCircleOutline, InfoSmallCircle, InfoCircle2, InfoCircle, Home, Question, QuestionCircle, QuestionCircle1, QuestionCircleOutline, QuestionSmall, Search2, Search3, Search, SearchOutline, Gear4, Gear3, Gear2, Gear1, Gear1Outline, Cog, CogOutline, TagsRound, Tags, TagRound, Tag, TagOutline, Photos, PhotosOutline, AlbumsOutline, Albums, PhotoPicture, PhotoImage, FolderSmall, FolderSmallOutline, FolderOpen, FolderOpen2, Camera1, CameraOutline, Camera, Camera2, Box, BoxOutline, Briefcase, Briefcase2, BriefcaseOutline, Bag, Browsers, BrowsersOutline, Compose, ComposeEdit, ComposeEditOutline, Compass, EditRedo, EditRedoOutline, EditForward, EditReply, EditReplyAll, EditUndo, EditUndoOutline, NavigateLocation, NavigateOutline, SendMail, SendMailOutline, MailSend, Contacts, ContactsSocial, Mic5, Mic3, Mic, MicOutline, MicOff, Mic4, Mic2, Play, Play2, PlayOutline, Pause, Pause2, PauseOutline, SkipbackwardOutline, Skipbackward, Skipforward, SkipforwardOutline, Rewind, RewindOutline, FastForward, FastForwardOutline, FastBackward, FastForward1, HandLike, HandUnlike, Android, AndroidOutine, Apple, AppleOutline, Windows, WindowsOutline, Linux, Wordpress, WordpressOutline, Trash2, Trash, Trash4, Trash3, TrashOutline, SpeakerNo, Speaker, VolumeLow, VolumeMedium, VolumeHigh, SquareUpload, SquareUploadOutline, CloudUpload2, CloudUpload, CloudUploadOutline, SignalWifi, Wifi, SignalBar, Refresh, Refresh1, RefreshCircle, RefreshCircleOutline, ReloadThin, Loop, Rss, RssOutline, Share, MarkPin, Mark, MarkOutline, MarkPin1, Speedometer, Speedometer1, SpeedometerOutline, TimerClock, TimerClockOutline, Screen, Screen1, ScreenOutline, PhotosPictures, Female, Male, FemaleSymbol, MaleSymbol, Keypad2, KeypadOutline, MailLetter, MailLetter2, MailLetterOutline, LogIn, LogOut, LogOut1, LockBig, Lock, LockOutline, Key, Key1, Lock1, Chatbubble, ChatbubbleOutline, ChatTalk, ChatTalkOutline, TalkChatBubble, TalkChatBubble2, TalkChatBubble1, TalkChat, TalkChat1, MusicNote, MusicNote2, MusicSong, Infinite, InfiniteOutline, InboxBox, Inbox, InboxOutline, FlashElectric, FlashElectric2, ElectricFlashOutline, BatteryEmpty, BatteryLow, Battery, BatteryFull, BatteryCharging, BatteryMedium, Bluetooth, MobilePhone, Call, CallPhone, CallPhoneOutline, Bitcoin, BitcoinOutline, Bookmark, Bubbles, Brightness, BrightnessOutline, CheckMark2, Buffer, BufferOutline, Bug, Calculator, Calculator2, CalculatorOutline, Calendar, Calendar3, CalendarOutline, Calendar2, CheckMark, Car, CircleFilled, CircleFilledOutline, CloudSun, CloudSunOutline, CloudDownload, CloudDownloadOutline, CloudMoon, CloudMoonOutline, CloudRain, CloudRainOutline, CloudSmall, CloudSmallOutline, CloudLightning, CloudLightningOutline, Cloud, CloudOutline, Copy, CopyOutline, EyeGlass, EyeGlassOutline, Globe, GlobeOutline, Github, GithubOutline, Filmstrip, FilmstripOutline, Moon, MoonOutline, DeviceLaptop, WineGlass, WineGlassOutline, Unlock, Unlock2, UnlockOutline, VideoCamera, VideoCameraOutline, DeviceTablet, SquareDownload, SquareDownloadOutline, ShoppingCart, ShoppingCartOutline, Print1, Print, PrintOutline, ReturnLeft, ReturnLeft1, ResizeArrowUp, ResizeArrowDown, ResizeArrow2, Snowy, PowerOff, PencilEdit, Pin, Pie2, PieOutline, Pie, Flight2, Random, PaperClip, Parentheses, PaperAirplane, Nuclear, Mixer2, Mixer, Map, Book, ToolHammer, ToolFork, ToolSpoon, ToolMagnet, ToolKnife, Ipod, Medkit, Medkit2, MedkitOutline, Loading1, Loading2, Loading3, Loading4, Location, NoteFile, LetterMail, Leaf, Headphone, Hashtag, Grid, Keypad, Link, IceCream, Gamepad2, Gamepad, Friends, FileDocumentText, Filing, GlobeWorld, GlobeWorld1, GlassWine, ElectricNoOff, Exclamation, Eject, Egg, Dropdown, DropboxOutline, Dropbox, DownloadInbox, CircleDownload, Document, DisplayContrast, Disc, CupCoffee, Crosshairpinpoint, Contrast, CodeWorking, CodeDownload, Code, Clipboard, Clock2, BookmarkOutline, Female1, Male1, Foot, Microphone, ShoppingCart1, ListBullet, ListNumber, Photo, Mountains, Torso, TorsoFemale, ZoomIn, ZoomOut, Yen, Star4, AngleDoubleUp, AngleDoubleDown, AngleDoubleLeft, AngleDoubleRight, Font, FighterJet, Like, Unlike, ZeroCircle, OneCircle, TwoCircle, ThreeCircle, FourCircle, FiveCircle, SixCircle, SevenCircle, EightCircle, NineCircle, PlusCircle1, MinusCircle1, ArrowUpThinCircle, ArrowDownThinCircle, ArrowLeftThinCircle, ArrowRightThinCircle, ArrowLeftLightCircle, ArrowRightLightCircle, SearchCircle, ShareCircle, ShareOutlineCircle, ArrowRightBoldCircle, ArrowLeftBoldCircle, ArrowRightBoldRoundCircle, ArrowLeftBoldRoundCircle, CrossCircle, MenuCircle, InfoCircle1, ExclamationCircle, Star5, Star5Empty, Up, UpBold, DownBold, Down, Share1, ChevronUpMini, ChevronDownMini, ChevronLeftMini, ChevronRightMini, UpOpenBig, DownOpenBig, LeftOpenBig, RightOpenBig, UpOpen, DownOpen, LeftOpen, RightOpen, Stop, Storage, SwapExchage, Wrench, SettingTools, Sort, ArrowGraphDownLeft, ArrowGraphDownRight, ArrowGraphUpLeft, ArrowGraphUpRight, ArrowMove, ArrowUpLeft, ArrowUpRight, ArrowDownLeft, ArrowDownRight, LockStreamline, UnlockStreamline, CommentStreamline, ShoppingInStreamline, ShoppingOutStreamline, IpadStreamline, IphoneStreamline, IpodStreamline, LaptopStreamline, ComputerStreamline, EditStreamline, EmailStreamline, DatabaseStreamline, GarbageStreamline, PictureStreamline, PictureStreamline1, HomeStreamline, WifiLow, WifiMedium, WifiFull, CloudUpload1, CloudDownload1, GitBranch, GitCompare, GitCommit, GitMerge, GitPullRequest, Graph, Globe1, MortarBoard, Rocket, Pulse, Zap, Tools, LogIn1, LogOut11, Mail, Key2, Lock2, Star, Archive, Beaker, BeakerScienceFlask, Bookmark1, CreditCard, EyeDisabled, ForkRepo, HandBlock, Navigate, RadioWaves, Record2, Speakerphone, Umbrella, Usb, YoutubePlay, YoutubePlayOutline, AddressBook, Bluetooth1, Paperclip, Torsos, TorsosAll, Trophy, Thumbnails, ToolWrench, Widget, Yen1, Refresh4, Bookmark2, Attach, Address, Book1, Basket, DocLandscape, Doc, Direction, Database, CreditCard1, Cog1, Dot3, Home1, Location1, Mail1, Map1, Megaphone, Menu, DeviceMobile, DeviceMonitor, Moon1, Power, Star3, SocialBaidu, SocialBaiduCircle, SocialQq, SocialQqCircle, SocialSina, SocialSinaCircle, SocialWeibo, SocialWeiboCircle, SocialIqyi, SocialIqyiCircle, SocialDouban, Flight3, ShareOutline, LinkExternal, Code1, Dollar, Terminal, Unlock1, Unlock3, ZoomIn1, ZoomOut1, Ccw, Cancel, Check, Dot2, Dot, Docs, DownloadInbox2, Flight, Flash, Export, Tools1, Signal, ChartBar, ChartPie, ChartLine, Code2, Vcard, Share2, Milestone, MessageTalk, User2, Timer, LinkStreamline, SettingsStreamline1, Bookmark3, BookBookmark, Burst, BurstNew, MaleFemale, PageExport, Refresh2, BarChart, Barcode, User, UserAdd, Googleplus, Googleplus1, Googleplus2, GoogleplusThick, Facebook, FacebookOutline, Linkedin, LinkedinOutline, Pinterest, PinterestOutline, Twitter, TwitterOutline, Tumblr, TumblrOutline, Mail2] static let allIconLiterals: [String] = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowRoundUp", "ArrowRoundDown", "ArrowRoundLeft", "ArrowRoundRight", "ArrowUpThin", "ArrowDownThin", "ArrowLeftThin", "ArrowRightThin", "CaretUp", "CaretDown", "CaretLeft", "CaretRight", "ChevronUpBig", "ChevronDownBig", "ChevronLeftBig", "ChevronRightBig", "ChevronUpThin", "ChevronDownThin", "ChevronLeftThin", "ChevronRightThin", "ChevronLeft", "ChevronRight", "Add", "Minus", "Remove", "AddRound", "MinusRound", "RemoveRound", "PlusAdd", "MinusRemove", "Plus", "Minus3", "PlusCircle", "MinusCircle", "PlusOutline", "MinusCircle2", "PlusCircleOutline", "MinusCircleOutline", "CheckCircle", "RemoveDeleteCircle", "CheckMarkCircle", "CloseCircle", "CheckMarkCircleOutline", "CloseCircleOutline", "CheckMark4", "CloseEmpty", "CheckMark3", "Remove2", "MenuRound", "MenuSmall", "Drag", "DragSmall", "More2", "More", "MoreOutline", "MoreOption", "ClockAlarm1", "ClockAlarmOutline", "ClockAlarm", "Clock3Outline", "Clock3", "ClockOutline", "ClockTimeOutline", "ClockTime", "StopwatchOutline", "Stopwatch", "Stopwatch1", "AtThin", "AtThick", "AtBold", "Heart", "HeartSmall", "HeartSmallOutline", "Heart1", "Heart1Empty", "Star2", "Star8", "Star1", "Star8Empty", "Star9", "Star9Empty", "Star9Half", "Star9Half1", "Eye3", "Eye", "EyeOutline", "Eye4", "Flag", "FlagOutline", "Flag3", "Flag1", "Contact", "ContactOutline", "ContactAdd", "Contact2", "ContactAdd2", "ContactOutlineAdd", "ContactBig", "ContactAdd3", "UserCircle", "UserCircleOutline", "ContactGroup", "ContactGroupOutline", "Contacts1", "Bell", "BellAlarm", "BellOutline", "Lightbulb1", "Lightbulb2", "LightbulbOutline", "Lightbulb", "Info", "InfoSmall", "InfoSmallCircleOutline", "InfoSmallCircle", "InfoCircle2", "InfoCircle", "Home", "Question", "QuestionCircle", "QuestionCircle1", "QuestionCircleOutline", "QuestionSmall", "Search2", "Search3", "Search", "SearchOutline", "Gear4", "Gear3", "Gear2", "Gear1", "Gear1Outline", "Cog", "CogOutline", "TagsRound", "Tags", "TagRound", "Tag", "TagOutline", "Photos", "PhotosOutline", "AlbumsOutline", "Albums", "PhotoPicture", "PhotoImage", "FolderSmall", "FolderSmallOutline", "FolderOpen", "FolderOpen2", "Camera1", "CameraOutline", "Camera", "Camera2", "Box", "BoxOutline", "Briefcase", "Briefcase2", "BriefcaseOutline", "Bag", "Browsers", "BrowsersOutline", "Compose", "ComposeEdit", "ComposeEditOutline", "Compass", "EditRedo", "EditRedoOutline", "EditForward", "EditReply", "EditReplyAll", "EditUndo", "EditUndoOutline", "NavigateLocation", "NavigateOutline", "SendMail", "SendMailOutline", "MailSend", "Contacts", "ContactsSocial", "Mic5", "Mic3", "Mic", "MicOutline", "MicOff", "Mic4", "Mic2", "Play", "Play2", "PlayOutline", "Pause", "Pause2", "PauseOutline", "SkipbackwardOutline", "Skipbackward", "Skipforward", "SkipforwardOutline", "Rewind", "RewindOutline", "FastForward", "FastForwardOutline", "FastBackward", "FastForward1", "HandLike", "HandUnlike", "Android", "AndroidOutine", "Apple", "AppleOutline", "Windows", "WindowsOutline", "Linux", "Wordpress", "WordpressOutline", "Trash2", "Trash", "Trash4", "Trash3", "TrashOutline", "SpeakerNo", "Speaker", "VolumeLow", "VolumeMedium", "VolumeHigh", "SquareUpload", "SquareUploadOutline", "CloudUpload2", "CloudUpload", "CloudUploadOutline", "SignalWifi", "Wifi", "SignalBar", "Refresh", "Refresh1", "RefreshCircle", "RefreshCircleOutline", "ReloadThin", "Loop", "Rss", "RssOutline", "Share", "MarkPin", "Mark", "MarkOutline", "MarkPin1", "Speedometer", "Speedometer1", "SpeedometerOutline", "TimerClock", "TimerClockOutline", "Screen", "Screen1", "ScreenOutline", "PhotosPictures", "Female", "Male", "FemaleSymbol", "MaleSymbol", "Keypad2", "KeypadOutline", "MailLetter", "MailLetter2", "MailLetterOutline", "LogIn", "LogOut", "LogOut1", "LockBig", "Lock", "LockOutline", "Key", "Key1", "Lock1", "Chatbubble", "ChatbubbleOutline", "ChatTalk", "ChatTalkOutline", "TalkChatBubble", "TalkChatBubble2", "TalkChatBubble1", "TalkChat", "TalkChat1", "MusicNote", "MusicNote2", "MusicSong", "Infinite", "InfiniteOutline", "InboxBox", "Inbox", "InboxOutline", "FlashElectric", "FlashElectric2", "ElectricFlashOutline", "BatteryEmpty", "BatteryLow", "Battery", "BatteryFull", "BatteryCharging", "BatteryMedium", "Bluetooth", "MobilePhone", "Call", "CallPhone", "CallPhoneOutline", "Bitcoin", "BitcoinOutline", "Bookmark", "Bubbles", "Brightness", "BrightnessOutline", "CheckMark2", "Buffer", "BufferOutline", "Bug", "Calculator", "Calculator2", "CalculatorOutline", "Calendar", "Calendar3", "CalendarOutline", "Calendar2", "CheckMark", "Car", "CircleFilled", "CircleFilledOutline", "CloudSun", "CloudSunOutline", "CloudDownload", "CloudDownloadOutline", "CloudMoon", "CloudMoonOutline", "CloudRain", "CloudRainOutline", "CloudSmall", "CloudSmallOutline", "CloudLightning", "CloudLightningOutline", "Cloud", "CloudOutline", "Copy", "CopyOutline", "EyeGlass", "EyeGlassOutline", "Globe", "GlobeOutline", "Github", "GithubOutline", "Filmstrip", "FilmstripOutline", "Moon", "MoonOutline", "DeviceLaptop", "WineGlass", "WineGlassOutline", "Unlock", "Unlock2", "UnlockOutline", "VideoCamera", "VideoCameraOutline", "DeviceTablet", "SquareDownload", "SquareDownloadOutline", "ShoppingCart", "ShoppingCartOutline", "Print1", "Print", "PrintOutline", "ReturnLeft", "ReturnLeft1", "ResizeArrowUp", "ResizeArrowDown", "ResizeArrow2", "Snowy", "PowerOff", "PencilEdit", "Pin", "Pie2", "PieOutline", "Pie", "Flight2", "Random", "PaperClip", "Parentheses", "PaperAirplane", "Nuclear", "Mixer2", "Mixer", "Map", "Book", "ToolHammer", "ToolFork", "ToolSpoon", "ToolMagnet", "ToolKnife", "Ipod", "Medkit", "Medkit2", "MedkitOutline", "Loading1", "Loading2", "Loading3", "Loading4", "Location", "NoteFile", "LetterMail", "Leaf", "Headphone", "Hashtag", "Grid", "Keypad", "Link", "IceCream", "Gamepad2", "Gamepad", "Friends", "FileDocumentText", "Filing", "GlobeWorld", "GlobeWorld1", "GlassWine", "ElectricNoOff", "Exclamation", "Eject", "Egg", "Dropdown", "DropboxOutline", "Dropbox", "DownloadInbox", "CircleDownload", "Document", "DisplayContrast", "Disc", "CupCoffee", "Crosshairpinpoint", "Contrast", "CodeWorking", "CodeDownload", "Code", "Clipboard", "Clock2", "BookmarkOutline", "Female1", "Male1", "Foot", "Microphone", "ShoppingCart1", "ListBullet", "ListNumber", "Photo", "Mountains", "Torso", "TorsoFemale", "ZoomIn", "ZoomOut", "Yen", "Star4", "AngleDoubleUp", "AngleDoubleDown", "AngleDoubleLeft", "AngleDoubleRight", "Font", "FighterJet", "Like", "Unlike", "ZeroCircle", "OneCircle", "TwoCircle", "ThreeCircle", "FourCircle", "FiveCircle", "SixCircle", "SevenCircle", "EightCircle", "NineCircle", "PlusCircle1", "MinusCircle1", "ArrowUpThinCircle", "ArrowDownThinCircle", "ArrowLeftThinCircle", "ArrowRightThinCircle", "ArrowLeftLightCircle", "ArrowRightLightCircle", "SearchCircle", "ShareCircle", "ShareOutlineCircle", "ArrowRightBoldCircle", "ArrowLeftBoldCircle", "ArrowRightBoldRoundCircle", "ArrowLeftBoldRoundCircle", "CrossCircle", "MenuCircle", "InfoCircle1", "ExclamationCircle", "Star5", "Star5Empty", "Up", "UpBold", "DownBold", "Down", "Share1", "ChevronUpMini", "ChevronDownMini", "ChevronLeftMini", "ChevronRightMini", "UpOpenBig", "DownOpenBig", "LeftOpenBig", "RightOpenBig", "UpOpen", "DownOpen", "LeftOpen", "RightOpen", "Stop", "Storage", "SwapExchage", "Wrench", "SettingTools", "Sort", "ArrowGraphDownLeft", "ArrowGraphDownRight", "ArrowGraphUpLeft", "ArrowGraphUpRight", "ArrowMove", "ArrowUpLeft", "ArrowUpRight", "ArrowDownLeft", "ArrowDownRight", "LockStreamline", "UnlockStreamline", "CommentStreamline", "ShoppingInStreamline", "ShoppingOutStreamline", "IpadStreamline", "IphoneStreamline", "IpodStreamline", "LaptopStreamline", "ComputerStreamline", "EditStreamline", "EmailStreamline", "DatabaseStreamline", "GarbageStreamline", "PictureStreamline", "PictureStreamline1", "HomeStreamline", "WifiLow", "WifiMedium", "WifiFull", "CloudUpload1", "CloudDownload1", "GitBranch", "GitCompare", "GitCommit", "GitMerge", "GitPullRequest", "Graph", "Globe1", "MortarBoard", "Rocket", "Pulse", "Zap", "Tools", "LogIn1", "LogOut11", "Mail", "Key2", "Lock2", "Star", "Archive", "Beaker", "BeakerScienceFlask", "Bookmark1", "CreditCard", "EyeDisabled", "ForkRepo", "HandBlock", "Navigate", "RadioWaves", "Record2", "Speakerphone", "Umbrella", "Usb", "YoutubePlay", "YoutubePlayOutline", "AddressBook", "Bluetooth1", "Paperclip", "Torsos", "TorsosAll", "Trophy", "Thumbnails", "ToolWrench", "Widget", "Yen1", "Refresh4", "Bookmark2", "Attach", "Address", "Book1", "Basket", "DocLandscape", "Doc", "Direction", "Database", "CreditCard1", "Cog1", "Dot3", "Home1", "Location1", "Mail1", "Map1", "Megaphone", "Menu", "DeviceMobile", "DeviceMonitor", "Moon1", "Power", "Star3", "SocialBaidu", "SocialBaiduCircle", "SocialQq", "SocialQqCircle", "SocialSina", "SocialSinaCircle", "SocialWeibo", "SocialWeiboCircle", "SocialIqyi", "SocialIqyiCircle", "SocialDouban", "Flight3", "ShareOutline", "LinkExternal", "Code1", "Dollar", "Terminal", "Unlock1", "Unlock3", "ZoomIn1", "ZoomOut1", "Ccw", "Cancel", "Check", "Dot2", "Dot", "Docs", "DownloadInbox2", "Flight", "Flash", "Export", "Tools1", "Signal", "ChartBar", "ChartPie", "ChartLine", "Code2", "Vcard", "Share2", "Milestone", "MessageTalk", "User2", "Timer", "LinkStreamline", "SettingsStreamline1", "Bookmark3", "BookBookmark", "Burst", "BurstNew", "MaleFemale", "PageExport", "Refresh2", "BarChart", "Barcode", "User", "UserAdd", "Googleplus", "Googleplus1", "Googleplus2", "GoogleplusThick", "Facebook", "FacebookOutline", "Linkedin", "LinkedinOutline", "Pinterest", "PinterestOutline", "Twitter", "TwitterOutline", "Tumblr", "TumblrOutline", "Mail2"] } private class FontLoader { class func loadFont(name: String) { let bundle = NSBundle.mainBundle() let fontURL = bundle.URLForResource(name, withExtension: "ttf") let data = NSData(contentsOfURL: fontURL!)! let provider = CGDataProviderCreateWithCFData(data) let font = CGFontCreateWithDataProvider(provider)! var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font, &error) { let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as NSError NSException(name: NSInternalInconsistencyException, reason: errorDescription, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } } public extension UIFont { public class func saniconOfSize(fontSize: CGFloat) -> UIFont { struct Static { static var onceToken : dispatch_once_t = 0 } let fontName = "sanicon" if (UIFont.fontNamesForFamilyName(fontName).count == 0) { dispatch_once(&Static.onceToken) { FontLoader.loadFont(fontName) } } return UIFont(name: fontName, size: fontSize)! } } public extension String { public static func sanicon(name: SanIcon) -> String { return name.rawValue.substringToIndex(advance(name.rawValue.startIndex, 1)) } }
mit
6774490523153966bd8dadb63f4552ad
24.069549
140
0.523685
3.606233
false
false
false
false
Halin-Lee/SwiftTestApp
Library/Fundamental/Fundamental/Classes/Mediator/Mediator.swift
1
9296
// // Mediator.swift // Pods // // Created by Halin Lee on 6/22/17. // // import Foundation import UIKit import ReactiveCocoa public class Mediator{ static let TAG:String = NSStringFromClass(Mediator.self); public static let instance = Mediator() /// 回退表,保存VC的上个VC,当VC后退时,会自动带上参数 var backDictionary = NSMapTable<UIViewController,UIViewController>.weakToWeakObjects() public required init() { } public func setup(rootVC:UIViewController) -> UINavigationController{ let rootNav = UINavigationController(rootViewController:rootVC) self.observeVCAppear(controller: rootVC) return rootNav } /// 构造并显示一个VC /// /// - Parameters: /// - cls: VC类 /// - param: 启动参数 /// - animated: 是否显示动画 /// - Returns: 是否成功显示 public func present(controllerClass cls:UIViewController.Type,currentVC:UIViewController, param:Dictionary<String, Any>? = nil, animated:Bool = true) -> Bool { let viewController = cls.init() return self.present(controller: viewController, currentVC: currentVC, param: param,animated:animated) } public func present(controller:UIViewController, currentVC:UIViewController, param:Dictionary<String, Any>? = nil, animated:Bool = true) -> Bool { //插入回退监听,用于配制navigation self.observeVCAppear(controller: controller) //如果可以接收回退,保存回退 if currentVC is ConfigurableViewController { backDictionary.setObject(currentVC, forKey: controller) } var presentType = ViewControllerPresentType.push if controller is ConfigurableViewController { let configuarbleVC = controller as! ConfigurableViewController //设置参数,获得呈现方式 if param != nil { configuarbleVC.receiveStartParam(parameters: param!) } } if controller is DesignableViewController { //配置展现方式 let designableVC = controller as! DesignableViewController presentType = designableVC.viewControllerPresentType() } //寻找当前正在present的controller let rootController = UIApplication.shared.delegate!.window!?.rootViewController var topController = rootController while (topController!.presentedViewController != nil) { topController = topController!.presentedViewController } switch presentType { case .present: //使用Present方式呈现VC let newNav = UINavigationController.init(rootViewController: controller) topController!.present(newNav, animated: animated, completion: nil) case .push: //使用Push方式呈现VC (topController as! UINavigationController).pushViewController(controller, animated: animated) } //某些动画可能导致主线程睡眠(比如cell点击动画),所以这里要主动唤醒主线程 //http://stackoverflow.com/questions/21075540/presentviewcontrolleranimatedyes-view-will-not-appear-until-user-taps-again CFRunLoopWakeUp(CFRunLoopGetCurrent()) Logger.log(tag: Mediator.TAG, message: "打开页面\(controller)") return true } /// 配制viewDidAppear监听,设置Navigation /// /// - Parameter controller: 需要配置的vc public func observeVCAppear(controller:UIViewController){ controller.reactive .trigger(for:#selector(UIViewController.viewWillAppear(_:))) .observe{ [weak controller] (event) in switch event{ case .value(_): let nav = controller!.navigationController! //这里如果使用weakself会导致无法释放,原因未知 let isNavHidden = nav.isNavigationBarHidden //如果vc实现了 Designable 则由 Designable 决定是否显示nav,否则默认阴惨 let isHideNavigationBar = controller is DesignableViewController ? (controller as! DesignableViewController).isHideNavigationBar() : false; //当前显示状态与期望的状态不同,设置 if isHideNavigationBar != isNavHidden { nav.setNavigationBarHidden(isHideNavigationBar, animated: true); } default: return } } } public func pop(currentVC:UIViewController, param:Dictionary<String, Any>? = nil, animated:Bool = true) -> Bool{ if currentVC.navigationController == nil { //没有nav,直接dismiss currentVC.presentingViewController!.dismiss(animated: animated, completion: nil) } else { let nav = currentVC.navigationController! if nav.viewControllers.count == 1 { //nav只剩下一个了,直接dismiss nav.presentingViewController!.dismiss(animated: animated, completion: nil) } else { //能pop,直接pop nav.popViewController(animated: animated) } } _ = self.sendPopParam(currentVC: currentVC,param: param, fromChild: true) Logger.log(tag: Mediator.TAG, message: "弹出页面\(currentVC)") return true } /// 会退到指定类 /// /// - Parameters: /// - cls: 类 /// - param: 参数 /// - animated: 是否显示动画 /// - Returns: 是否成功 public func popTo(class cls:UIViewController.Type,currentVC:UIViewController, param:Dictionary<String, Any>? = nil,animated:Bool = true) -> Bool { var targetVC:UIViewController? var popNav:UINavigationController? var popVC:UIViewController? = currentVC.navigationController != nil ? currentVC.navigationController : currentVC while targetVC == nil && popVC != nil{ if (popVC!.isKind(of: cls) && popVC != currentVC){ //找到指定类的VC且VC不是当前的VC,找到了可回退的VC targetVC = popVC break } if popVC is UINavigationController { for vc in (popVC as! UINavigationController).viewControllers.reversed(){ if (vc.isKind(of: cls) && vc != currentVC){ //找到指定类的VC且VC不是当前的VC,找到了可回退的VC popNav = popVC as? UINavigationController targetVC = vc break } } } popVC = popVC!.presentingViewController } if targetVC == nil { Logger.logE(tag: Mediator.TAG, message: "找不到可回退的VC \(cls)") return false } if popNav == nil { //没有nav,那么一定是用present的方式展现,所有直接dismiss就可以了 targetVC!.dismiss(animated: animated, completion: nil) } else { //当前navgation不等于目标nav,需要先dismiss let needDismiss = currentVC.navigationController != popNav if needDismiss { popNav!.dismiss(animated: animated, completion: nil) } //整理popNav的队列 var viewControllers = popNav!.viewControllers; for vc in viewControllers.reversed() { if (vc.isKind(of: cls) && vc != currentVC){ break } viewControllers.removeLast() } //设置 if needDismiss && animated{ //不需要动画,或者已经有dismiss动画,直接设置vc popNav!.viewControllers = viewControllers; } else { //需要动画,将当前的vc插入到nav,再播放pop动画 viewControllers.append(currentVC) popNav!.viewControllers = viewControllers popNav!.popViewController(animated: true) } } _ = self.sendPopParam(currentVC: currentVC,param: param, fromChild: false) Logger.log(tag: Mediator.TAG, message: "从页面\(currentVC)返回页面\(String(describing: targetVC))") return true; } func sendPopParam(currentVC:UIViewController, param:Dictionary<String, Any>? = nil,fromChild:Bool) -> Bool { if param != nil { let lastVC:ConfigurableViewController? = backDictionary.object(forKey: currentVC) as? ConfigurableViewController; if lastVC == nil { Logger.logE(tag: Mediator.TAG, message: "VC已被弹出") return false } lastVC!.receivePopParam(parameters: param!, fromChild: fromChild) } return true } }
mit
3883c47420567e9dd2eaf287995bd887
33.112
163
0.579151
4.972595
false
false
false
false
oarrabi/Guaka-Generator
Tests/GuakaClILibTests/DirectoryUtilitiesTests.swift
1
6486
// // DirectoryUtilitiesTests.swift // guaka-cli // // Created by Omar Abdelhafith on 27/11/2016. // // import XCTest @testable import GuakaClILib class DirectoryUtilitiesTests: XCTestCase { override func setUp() { super.setUp() MockDirectoryType.clear() } func testReturnCurrentFolderIfNameIsNotProvidedExample() { MockDirectoryType.currentDirectory = "ABCD" GuakaCliConfig.dir = MockDirectoryType.self let s = try! DirectoryUtilities.currentDirectory(forName: nil) XCTAssertEqual(s, "ABCD") } func testReturnCurrentPathPlusRelativePathExample() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/root/some/path": true] MockDirectoryType.pathsEmptyValue = ["/root/some/path": true] GuakaCliConfig.dir = MockDirectoryType.self let s = try! DirectoryUtilities.currentDirectory(forName: "some/path") XCTAssertEqual(s, "/root/some/path") } func testReturnCurrentPathPlusNamePathExample() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/root/path": true] MockDirectoryType.pathsEmptyValue = ["/root/path": true] GuakaCliConfig.dir = MockDirectoryType.self let s = try! DirectoryUtilities.currentDirectory(forName: "path") XCTAssertEqual(s, "/root/path") } func testReturnAbsolutePathExample() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/some/root/path": true] MockDirectoryType.pathsEmptyValue = ["/some/root/path": true] GuakaCliConfig.dir = MockDirectoryType.self let s = try! DirectoryUtilities.currentDirectory(forName: "/some/root/path") XCTAssertEqual(s, "/some/root/path") } func testReturnExceptionIfPathIsNotValud() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/some/root/path": false] GuakaCliConfig.dir = MockDirectoryType.self do { try DirectoryUtilities.currentDirectory(forName: "/some/root/path") } catch GuakaError.wrongDirectoryGiven(let path) { XCTAssertEqual(path, "/some/root/path") } catch { XCTFail() } } func testRetunrErrorIfPathIsFolderAndNonEmpty() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/some/root/path": true] MockDirectoryType.pathsEmptyValue = ["/some/root/path": false] GuakaCliConfig.dir = MockDirectoryType.self do { try DirectoryUtilities.currentDirectory(forName: "/some/root/path") } catch GuakaError.wrongDirectoryGiven(let path) { XCTAssertEqual(path, "/some/root/path") } catch { XCTFail() } } func testReturnErrorIfPathDoesNotExist() { MockDirectoryType.currentDirectory = "/root" GuakaCliConfig.dir = MockDirectoryType.self do { try DirectoryUtilities.currentDirectory(forName: "/some/root/path") } catch GuakaError.wrongDirectoryGiven(let path) { XCTAssertEqual(path, "/some/root/path") } catch { XCTFail() } } func testThrowsFolderIfFolderHasContent() { MockDirectoryType.currentDirectory = "/root" GuakaCliConfig.dir = MockDirectoryType.self let paths = Paths(rootDirectory: "/root") do { try DirectoryUtilities.createDirectoryStructure(paths: paths, directoryState: .hasContent) } catch GuakaError.triedToCreateProjectInNonEmptyDirectory(let path) { XCTAssertEqual(path, "/root") } catch { XCTFail() } } func testTriesToCreateRootFolderIfNonExisting() { MockDirectoryType.pathsCreationValue = [ "/root": true, "/root/Sources": true, ] GuakaCliConfig.dir = MockDirectoryType.self let paths = Paths(rootDirectory: "/root") try! DirectoryUtilities.createDirectoryStructure(paths: paths, directoryState: .nonExisting) let val = MockDirectoryType.pathsCreated.contains("/root") XCTAssertEqual(val, true) } func testTriesToCreateSourcesFolderIfNonExisting() { MockDirectoryType.pathsCreationValue = [ "/root": true, "/root/Sources": true, ] GuakaCliConfig.dir = MockDirectoryType.self let paths = Paths(rootDirectory: "/root") try! DirectoryUtilities.createDirectoryStructure(paths: paths, directoryState: .nonExisting) let val = MockDirectoryType.pathsCreated.contains("/root/Sources") XCTAssertEqual(val, true) } func testThrowsErrorIfCreateRootFailed() { MockDirectoryType.pathsCreationValue = [ "/root": false, "/root/Sources": true, ] GuakaCliConfig.dir = MockDirectoryType.self let paths = Paths(rootDirectory: "/root") do { try DirectoryUtilities.createDirectoryStructure(paths: paths, directoryState: .nonExisting) } catch GuakaError.failedCreatingFolder(let path) { XCTAssertEqual(path, "/root") } catch { XCTFail() } } func testThrowsErrorIfCreateSourcesFailed() { MockDirectoryType.pathsCreationValue = [ "/root": true, "/root/Sources": false, ] GuakaCliConfig.dir = MockDirectoryType.self let paths = Paths(rootDirectory: "/root") do { try DirectoryUtilities.createDirectoryStructure(paths: paths, directoryState: .nonExisting) } catch GuakaError.failedCreatingFolder(let path) { XCTAssertEqual(path, "/root/Sources") } catch { XCTFail() } } func testFullSuccessfullRun() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsExistanceValue = ["/root": true] MockDirectoryType.pathsEmptyValue = ["/root": true] MockDirectoryType.pathsCreationValue = ["/root": true, "/root/Sources": true] GuakaCliConfig.dir = MockDirectoryType.self try! DirectoryUtilities.createDirectoryStrucutre(forName: nil) } func testReturnThePathsForAFolder() { MockDirectoryType.currentDirectory = "/root" MockDirectoryType.pathsValidationValue = ["/some/root/path": true] MockDirectoryType.pathsEmptyValue = ["/some/root/path": true] GuakaCliConfig.dir = MockDirectoryType.self let s = try! DirectoryUtilities.paths(forName: "/some/root/path") XCTAssertEqual(s.rootDirectory, "/some/root/path") } }
mit
99c1159061e0c051574f20b0fecb7c7a
28.752294
83
0.681468
4.16838
false
true
false
false
karwa/swift-corelibs-foundation
Foundation/NSCFDictionary.swift
3
6419
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation internal final class _NSCFDictionary : NSMutableDictionary { deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } required init() { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) { fatalError() } required convenience init(dictionaryLiteral elements: (NSObject, AnyObject)...) { fatalError() } override var count: Int { return CFDictionaryGetCount(unsafeBitCast(self, to: CFDictionary.self)) } override func objectForKey(_ aKey: AnyObject) -> AnyObject? { let value = CFDictionaryGetValue(_cfObject, unsafeBitCast(aKey, to: UnsafePointer<Void>.self)) if value != nil { return unsafeBitCast(value, to: AnyObject.self) } else { return nil } } // This doesn't feel like a particularly efficient generator of CFDictionary keys, but it works for now. We should probably put a function into CF that allows us to simply iterate the keys directly from the underlying CF storage. private struct _NSCFKeyGenerator : IteratorProtocol { var keyArray : [NSObject] = [] var index : Int = 0 let count : Int mutating func next() -> AnyObject? { if index == count { return nil } else { let item = keyArray[index] index += 1 return item } } init(_ dict : _NSCFDictionary) { let cf = dict._cfObject count = CFDictionaryGetCount(cf) let keys = UnsafeMutablePointer<UnsafePointer<Void>?>(allocatingCapacity: count) CFDictionaryGetKeysAndValues(cf, keys, nil) for idx in 0..<count { let key = unsafeBitCast(keys.advanced(by: idx).pointee!, to: NSObject.self) keyArray.append(key) } keys.deinitialize() keys.deallocateCapacity(count) } } override func keyEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(_NSCFKeyGenerator(self)) } override func removeObjectForKey(_ aKey: AnyObject) { CFDictionaryRemoveValue(_cfMutableObject, unsafeBitCast(aKey, to: UnsafePointer<Void>.self)) } override func setObject(_ anObject: AnyObject, forKey aKey: NSObject) { CFDictionarySetValue(_cfMutableObject, unsafeBitCast(aKey, to: UnsafePointer<Void>.self), unsafeBitCast(anObject, to: UnsafePointer<Void>.self)) } override var classForCoder: AnyClass { return NSMutableDictionary.self } } internal func _CFSwiftDictionaryGetCount(_ dictionary: AnyObject) -> CFIndex { return (dictionary as! NSDictionary).count } internal func _CFSwiftDictionaryGetCountOfKey(_ dictionary: AnyObject, key: AnyObject) -> CFIndex { if _CFSwiftDictionaryContainsKey(dictionary, key: key) { return 1 } else { return 0 } } internal func _CFSwiftDictionaryContainsKey(_ dictionary: AnyObject, key: AnyObject) -> Bool { return (dictionary as! NSDictionary).objectForKey(key) != nil } //(AnyObject, AnyObject) -> Unmanaged<AnyObject> internal func _CFSwiftDictionaryGetValue(_ dictionary: AnyObject, key: AnyObject) -> Unmanaged<AnyObject>? { if let obj = (dictionary as! NSDictionary).objectForKey(key) { return Unmanaged<AnyObject>.passUnretained(obj) } else { return nil } } internal func _CFSwiftDictionaryGetValueIfPresent(_ dictionary: AnyObject, key: AnyObject, value: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) -> Bool { if let val = _CFSwiftDictionaryGetValue(dictionary, key: key) { value?.pointee = val return true } else { value?.pointee = nil return false } } internal func _CFSwiftDictionaryGetCountOfValue(_ dictionary: AnyObject, value: AnyObject) -> CFIndex { if _CFSwiftDictionaryContainsValue(dictionary, value: value) { return 1 } else { return 0 } } internal func _CFSwiftDictionaryContainsValue(_ dictionary: AnyObject, value: AnyObject) -> Bool { NSUnimplemented() } internal func _CFSwiftDictionaryGetValuesAndKeys(_ dictionary: AnyObject, valuebuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>?, keybuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) { var idx = 0 if valuebuf == nil && keybuf == nil { return } (dictionary as! NSDictionary).enumerateKeysAndObjectsUsingBlock { key, value, _ in valuebuf?[idx] = Unmanaged<AnyObject>.passUnretained(value) keybuf?[idx] = Unmanaged<AnyObject>.passUnretained(key) idx += 1 } } internal func _CFSwiftDictionaryApplyFunction(_ dictionary: AnyObject, applier: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer<Void>) -> Void, context: UnsafeMutablePointer<Void>) { (dictionary as! NSDictionary).enumerateKeysAndObjectsUsingBlock { key, value, _ in applier(key, value, context) } } internal func _CFSwiftDictionaryAddValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionaryReplaceValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionarySetValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionaryRemoveValue(_ dictionary: AnyObject, key: AnyObject) { (dictionary as! NSMutableDictionary).removeObjectForKey(key) } internal func _CFSwiftDictionaryRemoveAllValues(_ dictionary: AnyObject) { (dictionary as! NSMutableDictionary).removeAllObjects() }
apache-2.0
f75b154e208ea35af9f5c93fa3915604
34.860335
233
0.671444
4.972115
false
false
false
false
ochan1/OC-PublicCode
Makestagram/Makestagram/Services/ChatService.swift
1
4566
// // ChatService.swift // Makestagram // // Created by Oscar Chan on 7/12/17. // Copyright © 2017 Oscar Chan. All rights reserved. // import Foundation import FirebaseDatabase struct ChatService { static func create(from message: Message, with chat: Chat, completion: @escaping (Chat?) -> Void) { // 1 var membersDict = [String : Bool]() for uid in chat.memberUIDs { membersDict[uid] = true } // 2 let lastMessage = "\(message.sender.username): \(message.content)" chat.lastMessage = lastMessage let lastMessageSent = message.timestamp.timeIntervalSince1970 chat.lastMessageSent = message.timestamp // 3 let chatDict: [String : Any] = ["title" : chat.title, "memberHash" : chat.memberHash, "members" : membersDict, "lastMessage" : lastMessage, "lastMessageSent" : lastMessageSent] // 4 let chatRef = Database.database().reference().child("chats").child(User.current.uid).childByAutoId() chat.key = chatRef.key // 5 var multiUpdateValue = [String : Any]() // 6 for uid in chat.memberUIDs { multiUpdateValue["chats/\(uid)/\(chatRef.key)"] = chatDict } // 7 let messagesRef = Database.database().reference().child("messages").child(chatRef.key).childByAutoId() let messageKey = messagesRef.key // 8 multiUpdateValue["messages/\(chatRef.key)/\(messageKey)"] = message.dictValue // 9 let rootRef = Database.database().reference() rootRef.updateChildValues(multiUpdateValue) { (error, ref) in if let error = error { assertionFailure(error.localizedDescription) return } completion(chat) } } static func checkForExistingChat(with user: User, completion: @escaping (Chat?) -> Void) { // 1 let members = [user, User.current] let hashValue = Chat.hash(forMembers: members) // 2 let chatRef = Database.database().reference().child("chats").child(User.current.uid) // 3 let query = chatRef.queryOrdered(byChild: "memberHash").queryEqual(toValue: hashValue) // 4 query.observeSingleEvent(of: .value, with: { (snapshot) in guard let chatSnap = snapshot.children.allObjects.first as? DataSnapshot, let chat = Chat(snapshot: chatSnap) else { return completion(nil) } completion(chat) }) } static func sendMessage(_ message: Message, for chat: Chat, success: ((Bool) -> Void)? = nil) { guard let chatKey = chat.key else { success?(false) return } var multiUpdateValue = [String : Any]() for uid in chat.memberUIDs { let lastMessage = "\(message.sender.username): \(message.content)" multiUpdateValue["chats/\(uid)/\(chatKey)/lastMessage"] = lastMessage multiUpdateValue["chats/\(uid)/\(chatKey)/lastMessageSent"] = message.timestamp.timeIntervalSince1970 } let messagesRef = Database.database().reference().child("messages").child(chatKey).childByAutoId() let messageKey = messagesRef.key multiUpdateValue["messages/\(chatKey)/\(messageKey)"] = message.dictValue let rootRef = Database.database().reference() rootRef.updateChildValues(multiUpdateValue, withCompletionBlock: { (error, ref) in if let error = error { assertionFailure(error.localizedDescription) success?(false) return } success?(true) }) } static func observeMessages(forChatKey chatKey: String, completion: @escaping (DatabaseReference, Message?) -> Void) -> DatabaseHandle { let messagesRef = Database.database().reference().child("messages").child(chatKey) return messagesRef.observe(.childAdded, with: { snapshot in guard let message = Message(snapshot: snapshot) else { return completion(messagesRef, nil) } completion(messagesRef, message) }) } }
mit
b32818ae8bcedd4ba3c3d50043b6d91b
35.814516
140
0.55816
4.951193
false
false
false
false
BrenoVin/-watch-example
AirAber/AirAber/AppDelegate.swift
1
1113
// // AppDelegate.swift // AirAber // // Created by Mic Pringle on 05/08/2015. // Copyright © 2015 Mic Pringle. All rights reserved. // import UIKit import WatchConnectivity @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var session: WCSession? { didSet { if let session = session { session.delegate = self session.activateSession() } } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if WCSession.isSupported() { session = WCSession.defaultSession() } return true } } extension AppDelegate: WCSessionDelegate { func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { if let reference = message["reference"] as? String, boardingPass = QRCode(reference) { replyHandler(["boardingPassData": boardingPass.PNGData]) } } }
mit
12a3b2bd24f41be96f5a703a02ceff45
24.883721
133
0.632194
4.986547
false
false
false
false
Antondomashnev/Sourcery
Pods/Yams/Sources/Yams/Parser.swift
1
11637
// // Parser.swift // Yams // // Created by Norio Nomura on 12/15/16. // Copyright (c) 2016 Yams. All rights reserved. // #if SWIFT_PACKAGE import CYaml #endif import Foundation /// Parse all YAML documents in a String /// and produce corresponding Swift objects. /// /// - Parameters: /// - yaml: String /// - resolver: Resolver /// - constructor: Constructor /// - Returns: YamlSequence<Any> /// - Throws: YamlError public func load_all(yaml: String, _ resolver: Resolver = .default, _ constructor: Constructor = .default) throws -> YamlSequence<Any> { let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor) return YamlSequence { try parser.nextRoot()?.any } } /// Parse the first YAML document in a String /// and produce the corresponding Swift object. /// /// - Parameters: /// - yaml: String /// - resolver: Resolver /// - constructor: Constructor /// - Returns: Any? /// - Throws: YamlError public func load(yaml: String, _ resolver: Resolver = .default, _ constructor: Constructor = .default) throws -> Any? { return try Parser(yaml: yaml, resolver: resolver, constructor: constructor).singleRoot()?.any } /// Parse all YAML documents in a String /// and produce corresponding representation trees. /// /// - Parameters: /// - yaml: String /// - resolver: Resolver /// - constructor: Constructor /// - Returns: YamlSequence<Node> /// - Throws: YamlError public func compose_all(yaml: String, _ resolver: Resolver = .default, _ constructor: Constructor = .default) throws -> YamlSequence<Node> { let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor) return YamlSequence(parser.nextRoot) } /// Parse the first YAML document in a String /// and produce the corresponding representation tree. /// /// - Parameters: /// - yaml: String /// - resolver: Resolver /// - constructor: Constructor /// - Returns: Node? /// - Throws: YamlError public func compose(yaml: String, _ resolver: Resolver = .default, _ constructor: Constructor = .default) throws -> Node? { return try Parser(yaml: yaml, resolver: resolver, constructor: constructor).singleRoot() } /// Sequence that holds error public struct YamlSequence<T>: Sequence, IteratorProtocol { public private(set) var error: Swift.Error? public mutating func next() -> T? { do { return try closure() } catch { self.error = error return nil } } fileprivate init(_ closure: @escaping () throws -> T?) { self.closure = closure } private let closure: () throws -> T? } public final class Parser { // MARK: public public let yaml: String public let resolver: Resolver public let constructor: Constructor /// Set up Parser. /// /// - Parameter string: YAML /// - Parameter resolver: Resolver /// - Parameter constructor: Constructor /// - Throws: YamlError public init(yaml string: String, resolver: Resolver = .default, constructor: Constructor = .default) throws { yaml = string self.resolver = resolver self.constructor = constructor yaml_parser_initialize(&parser) #if USE_UTF8 yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING) utf8CString = string.utf8CString utf8CString.withUnsafeBytes { bytes in let input = bytes.baseAddress?.assumingMemoryBound(to: UInt8.self) yaml_parser_set_input_string(&parser, input, bytes.count - 1) } #else // use native endian let isLittleEndian = 1 == 1.littleEndian yaml_parser_set_encoding(&parser, isLittleEndian ? YAML_UTF16LE_ENCODING : YAML_UTF16BE_ENCODING) let encoding: String.Encoding #if swift(>=3.1) encoding = isLittleEndian ? .utf16LittleEndian : .utf16BigEndian #else /* ``` "".data(using: .utf16LittleEndian).withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in bytes == nil // true on Swift 3.0.2, false on Swift 3.1 } ``` for avoiding above, use `.utf16` if yaml is empty. */ encoding = yaml.isEmpty ? .utf16 : isLittleEndian ? .utf16LittleEndian : .utf16BigEndian #endif data = yaml.data(using: encoding)! data.withUnsafeBytes { bytes in yaml_parser_set_input_string(&parser, bytes, data.count) } #endif try parse() // Drop YAML_STREAM_START_EVENT } deinit { yaml_parser_delete(&parser) } /// Parse next document and return root Node. /// /// - Returns: next Node /// - Throws: YamlError public func nextRoot() throws -> Node? { guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil } return try loadDocument() } public func singleRoot() throws -> Node? { guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil } let node = try loadDocument() let event = try parse() if event.type != YAML_STREAM_END_EVENT { throw YamlError.composer( context: YamlError.Context(text: "expected a single document in the stream", mark: Mark(line: 1, column: 1)), problem: "but found another document", event.startMark, yaml: yaml ) } return node } // MARK: private fileprivate var anchors = [String: Node]() fileprivate var parser = yaml_parser_t() #if USE_UTF8 private let utf8CString: ContiguousArray<CChar> #else private let data: Data #endif } // MARK: implementation details extension Parser { fileprivate var streamEndProduced: Bool { return parser.stream_end_produced != 0 } fileprivate func loadDocument() throws -> Node { let node = try loadNode(from: parse()) try parse() // Drop YAML_DOCUMENT_END_EVENT return node } private func loadNode(from event: Event) throws -> Node { switch event.type { case YAML_ALIAS_EVENT: return try loadAlias(from: event) case YAML_SCALAR_EVENT: return try loadScalar(from: event) case YAML_SEQUENCE_START_EVENT: return try loadSequence(from: event) case YAML_MAPPING_START_EVENT: return try loadMapping(from: event) default: fatalError("unreachable") } } @discardableResult fileprivate func parse() throws -> Event { let event = Event() guard yaml_parser_parse(&parser, &event.event) == 1 else { throw YamlError(from: parser, with: yaml) } return event } private func loadAlias(from event: Event) throws -> Node { guard let alias = event.aliasAnchor else { fatalError("unreachable") } guard let node = anchors[alias] else { throw YamlError.composer(context: nil, problem: "found undefined alias", event.startMark, yaml: yaml) } return node } private func loadScalar(from event: Event) throws -> Node { let node = Node.scalar(.init(event.scalarValue, tag(event.scalarTag), event.scalarStyle, event.startMark)) if let anchor = event.scalarAnchor { anchors[anchor] = node } return node } private func loadSequence(from firstEvent: Event) throws -> Node { var array = [Node]() var event = try parse() while event.type != YAML_SEQUENCE_END_EVENT { array.append(try loadNode(from: event)) event = try parse() } let node = Node.sequence(.init(array, tag(firstEvent.sequenceTag), event.sequenceStyle, event.startMark)) if let anchor = firstEvent.sequenceAnchor { anchors[anchor] = node } return node } private func loadMapping(from firstEvent: Event) throws -> Node { var pairs = [(Node, Node)]() var event = try parse() while event.type != YAML_MAPPING_END_EVENT { let key = try loadNode(from: event) event = try parse() let value = try loadNode(from: event) pairs.append((key, value)) event = try parse() } let node = Node.mapping(.init(pairs, tag(firstEvent.mappingTag), event.mappingStyle, event.startMark)) if let anchor = firstEvent.mappingAnchor { anchors[anchor] = node } return node } private func tag(_ string: String?) -> Tag { let tagName = string.map(Tag.Name.init(rawValue:)) ?? .implicit return Tag(tagName, resolver, constructor) } } /// Representation of `yaml_event_t` fileprivate class Event { var event = yaml_event_t() deinit { yaml_event_delete(&event) } var type: yaml_event_type_t { return event.type } // alias var aliasAnchor: String? { return string(from: event.data.alias.anchor) } // scalar var scalarAnchor: String? { return string(from: event.data.scalar.anchor) } var scalarStyle: Node.Scalar.Style { // swiftlint:disable:next force_unwrapping return Node.Scalar.Style(rawValue: event.data.scalar.style.rawValue)! } var scalarTag: String? { guard event.data.scalar.plain_implicit == 0, event.data.scalar.quoted_implicit == 0 else { return nil } return string(from: event.data.scalar.tag) } var scalarValue: String { // scalar may contain NULL characters let buffer = UnsafeBufferPointer(start: event.data.scalar.value, count: event.data.scalar.length) // libYAML converts scalar characters into UTF8 if input is other than YAML_UTF8_ENCODING return String(bytes: buffer, encoding: .utf8)! } // sequence var sequenceAnchor: String? { return string(from: event.data.sequence_start.anchor) } var sequenceStyle: Node.Sequence.Style { // swiftlint:disable:next force_unwrapping return Node.Sequence.Style(rawValue: event.data.sequence_start.style.rawValue)! } var sequenceTag: String? { return event.data.sequence_start.implicit != 0 ? nil : string(from: event.data.sequence_start.tag) } // mapping var mappingAnchor: String? { return string(from: event.data.scalar.anchor) } var mappingStyle: Node.Mapping.Style { // swiftlint:disable:next force_unwrapping return Node.Mapping.Style(rawValue: event.data.mapping_start.style.rawValue)! } var mappingTag: String? { return event.data.mapping_start.implicit != 0 ? nil : string(from: event.data.sequence_start.tag) } // start_mark var startMark: Mark { return Mark(line: event.start_mark.line + 1, column: event.start_mark.column + 1) } } fileprivate func string(from pointer: UnsafePointer<UInt8>!) -> String? { return String.decodeCString(pointer, as: UTF8.self, repairingInvalidCodeUnits: true)?.result }
mit
2ff0ca287c1da1d7de44cbac60227495
32.153846
114
0.596546
4.414643
false
false
false
false