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
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTTimeSource.swift
1
1481
// // GATTTimeSource.swift // Bluetooth // // Created by Carlos Duclos on 7/6/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Time Source - SeeAlso: [Time Source](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.time_source.xml) */ @frozen public enum GATTTimeSource: UInt8, GATTCharacteristic { internal static let length = MemoryLayout<UInt8>.size public static var uuid: BluetoothUUID { return .timeSource } /// Unknown case unknown = 0 /// Network Time Protocol case networkTimeProtocol = 1 /// GPS case gps = 2 /// Radio Time Signal case radioTimeSignal = 3 /// Manual case manual = 4 /// Atomic Clock case atomicClock = 5 /// Cellular Network case cellularNetwork = 6 public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.init(rawValue: data[0]) } public var data: Data { return Data([rawValue]) } } extension GATTTimeSource: Equatable { public static func == (lhs: GATTTimeSource, rhs: GATTTimeSource) -> Bool { return lhs.rawValue == rhs.rawValue } } extension GATTTimeSource: CustomStringConvertible { public var description: String { return rawValue.description } }
mit
3b000bad24352186a028593cd6182616
19
141
0.605405
4.457831
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Util/SLVUtil.swift
1
1284
// // SLVUtil.swift // selluv-ios // // Created by 조백근 on 2017. 1. 5.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation class SLVUtil { //MARK: Util public class func setupAttributeName(first: String, second: String) -> NSAttributedString { let style = NSMutableParagraphStyle() style.alignment = .center let text = "\(first) \(second)" let nmLen = first.distance(from: first.startIndex, to: first.endIndex) let fullLen = text.distance(from: text.startIndex, to: text.endIndex) let myMutableString = NSMutableAttributedString(string: text, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular), NSForegroundColorAttributeName: text_color_g204] ) myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium), range: NSRange(location:0,length:nmLen)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:nmLen)) myMutableString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location:0,length:fullLen)) return myMutableString } }
mit
66d18617bae05f9d18ba4b36f3868ba6
41.5
164
0.708235
4.569892
false
false
false
false
manavgabhawala/swift
test/SILGen/collection_subtype_downcast.swift
1
2133
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast14array_downcastFT5arrayGSaP___GSqGSaVS_1S__ : // CHECK: bb0([[ARG:%.*]] : $Array<Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs21_arrayConditionalCastu0_rFGSax_GSqGSaq___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Any, S>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func array_downcast(array: [Any]) -> [S]? { return array as? [S] } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast13dict_downcastFT4dictGVs10DictionaryVS_1SP___GSqGS0_S1_Si__ : // CHECK: bb0([[ARG:%.*]] : $Dictionary<S, Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs30_dictionaryDownCastConditionalu2_Rxs8Hashable0_S_rFGVs10Dictionaryxq__GSqGS0_q0_q1___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any, S, Int>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func dict_downcast(dict: [S: Any]) -> [S: Int]? { return dict as? [S: Int] } // It's not actually possible to test this for Sets independent of // the bridging rules.
apache-2.0
32ccb97f6ffdbe6aed33ee38775296c1
45.065217
244
0.632846
2.882993
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
Pod/Classes/UI/Common/ParentalGate.swift
1
3420
// // ParentalGate.swift // Alamofire // // Created by Gunhan Sancar on 25/08/2020. // import UIKit class ParentalGate { private var topWindow: UIWindow? private var challangeAlertController: UIAlertController? private var errorAlertController: UIAlertController? private var firstNumber: Int = 0 private var secondNumber: Int = 0 private var solution: Int = 0 var openAction: VoidBlock? var cancelAction: VoidBlock? var failAction: VoidBlock? var successAction: VoidBlock? private let numberGenerator: NumberGeneratorType private let stringProvider: StringProviderType init(numberGenerator: NumberGeneratorType, stringProvider: StringProviderType) { self.numberGenerator = numberGenerator self.stringProvider = stringProvider newQuestion() } func stop() { challangeAlertController?.dismiss(animated: true, completion: nil) errorAlertController?.dismiss(animated: true, completion: nil) topWindow?.isHidden = true topWindow = nil } func show() { challangeAlertController = UIAlertController(title: stringProvider.parentalGateTitle, message: stringProvider.parentalGateMessage( firstNumber: firstNumber, secondNumber: secondNumber), preferredStyle: .alert) let continueAction = UIAlertAction(title: stringProvider.continueTitle, style: .default) { [weak self] _ in self?.onContinue() } let cancelAction = UIAlertAction(title: stringProvider.cancelTitle, style: .default) { [weak self] _ in self?.stop() self?.cancelAction?() } if let controller = challangeAlertController { controller.addAction(cancelAction) controller.addAction(continueAction) controller.addTextField(configurationHandler: { textField in textField.keyboardType = .numberPad }) topWindow = controller.presentInNewWindow() } self.openAction?() } private func onSuccessfulAttempt() { stop() self.successAction?() } private func onFailedAttempt() { stop() errorAlertController = UIAlertController(title: stringProvider.errorTitle, message: stringProvider.errorMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: stringProvider.cancelTitle, style: .default) { [weak self] _ in self?.stop() self?.failAction?() } if let controller = errorAlertController { controller.addAction(okAction) topWindow = controller.presentInNewWindow() } } private func onContinue() { let textField = challangeAlertController?.textFields?.first textField?.resignFirstResponder() if textField?.text?.toInt ?? 0 == solution { onSuccessfulAttempt() } else { onFailedAttempt() } } private func newQuestion() { firstNumber = numberGenerator.nextIntForParentalGate() secondNumber = numberGenerator.nextIntForParentalGate() solution = firstNumber + secondNumber } }
lgpl-3.0
5e9cfa910eb50e44dcc2dd7d2335df8d
30.962617
115
0.614327
5.402844
false
false
false
false
AndrewGene/JSONSuggest
JSONSuggest.swift
1
75666
// // JSONSuggest.swift // JSONSuggest // // Created by Andrew Goodwin on 9/15/16. // Copyright © 2016 Andrew Goodwin. All rights reserved. // import Foundation public class JSONSuggest{ static var sharedSuggest = JSONSuggest() var classList = [SuggestClass]() var swiftVersion = "2" var singleFile = false var includeSerialization = true var includeDeserialization = true var ignoreImplementedClasses = false var defaultValues:[String:String] = ["String":"\"\"", "Int": "-1", "Double":"-1.0","Bool":"false"] var deliveryMethod:DeliveryMethod = .FileSystem var saveDirectory = "/Users/<your_username_here>/Desktop" //var saveDirectory = "$HOME/Desktop" var isDebug = true //you can set this to false when you release and it will not run var classOrder = [String]() var numberOfLinesGenerated = 0 private var currentClass:SuggestClass? = nil private init(){ } func hasClass(name:String)->Bool{ return self.classList.filter({$0.className == name}).count > 0 } func makeSuggestions(JSON:AnyObject){ makeSuggestions(JSON, root: "Root") } func makeSuggestions(JSON:AnyObject, root:String){ if isDebug{ if deliveryMethod == .FileSystem && (saveDirectory == "" || saveDirectory == "/Users/<your_username_here>/Desktop"){ print("To save to the file system, please set the .saveDirectory property. Try something like \"/Users/<your_username_here>/Desktop\".") print("") print("❕Hint: open the Console app and type...") print("") print("echo $USER") print("") print("...to see your username ❕") } else if deliveryMethod == .FileSystem && (saveDirectory.hasPrefix("~") || saveDirectory.hasPrefix("$")){ print("Save directory cannot contain aliases. Try something like \"/Users/<your_username_here>/Desktop\".") print("") print("❕Hint: open the Console app and type...") print("") print("echo $USER") print("") print("...to see your username❕") } else{ if JSON is [String:AnyObject]{ if (JSON as! [String:AnyObject]).values.count > 0{ if (JSON as! [String:AnyObject]).values.first is [String:AnyObject]{ //print("good to go") } else{ //print("found simple type") let newClass = SuggestClass(className: root) classList.append(newClass) currentClass = newClass } } traverseDictionary((JSON as! [String:AnyObject])) } else if JSON is [[String:AnyObject]]{ let newClass = SuggestClass(className: root) classList.append(newClass) currentClass = newClass traverseArray(JSON as! [[String:AnyObject]]) } determineOptionals() if deliveryMethod == .URL || deliveryMethod == .FileSystem{ writeList() } else{ printList() } } } } private func determineOptionals(){ for cls in classList{ for property in cls.properties{ if !property.isOptional{ if property.instances < cls.instances{ property.isOptional = true } } } } } private func determineSimpleProperty(k:String,v:AnyObject){ //TODO: add NSDate and [NSDate] if v is [String]{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "[String]" for str in v as! [String]{ if str != ""{ suggestProperty.canBeReplaced = false break } } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ for str in v as! [String]{ if str != ""{ suggestProperty.canBeReplaced = false break } } suggestProperty.type = "[String]" } } } } if v is [Bool]{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "[Bool]" for str in v as! [Bool]{ if "\(str)" == "1" || "\(str)" == "0" || "\(str)" == "true" || "\(str)" == "false"{ suggestProperty.canBeReplaced = false break } } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ for str in v as! [Bool]{ if "\(str)" == "1" || "\(str)" == "0" || "\(str)" == "true" || "\(str)" == "false"{ suggestProperty.canBeReplaced = false break } } suggestProperty.type = "[Bool]" } } } } if v is [Double]{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "[Double]" for str in v as! [Double]{ if ("\(str)").containsString("."){ suggestProperty.canBeReplaced = false break } } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ for str in v as! [Double]{ if ("\(str)").containsString("."){ suggestProperty.canBeReplaced = false break } } suggestProperty.type = "[Double]" } } } } if v is [Int]{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "[Int]" for str in v as! [Int]{ if !("\(str)").containsString(".") && str != 0 && str != 1{ suggestProperty.canBeReplaced = false break } } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ for str in v as! [Int]{ if !("\(str)").containsString(".") && str != 0 && str != 1{ suggestProperty.canBeReplaced = false break } } suggestProperty.type = "[Int]" } } } } if v is String{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "String" if v as! String != ""{ suggestProperty.canBeReplaced = false } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ if v as! String != ""{ suggestProperty.canBeReplaced = false suggestProperty.type = "String" } } } } } if v is Bool{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "Bool" if "\(v)" == "1" || "\(v)" == "0" || "\(v)" == "true" || "\(v)" == "false"{ suggestProperty.canBeReplaced = false } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ if "\(v)" == "1" || "\(v)" == "0" || "\(v)" == "true" || "\(v)" == "false"{ suggestProperty.canBeReplaced = false suggestProperty.type = "Bool" } } } } } if v is Double{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "Double" if "\(v)".containsString("."){ suggestProperty.canBeReplaced = false } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ if "\(v)".containsString("."){ suggestProperty.canBeReplaced = false suggestProperty.type = "Double" } } } } } if v is Int{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "Int" if !"\(v)".containsString(".") && (v as! Int) != 0 && (v as! Int) != 1{ suggestProperty.canBeReplaced = false } if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } else{ let suggestProperty = currentClass!.properties.filter({$0.name == k}).first! suggestProperty.instances += 1 if suggestProperty.canBeReplaced{ if !"\(v)".containsString(".") && (v as! Int) != 0 && (v as! Int) != 1{ suggestProperty.canBeReplaced = false suggestProperty.type = "Int" } } } } } if v is NSNull{ if currentClass != nil{ if !currentClass!.hasProperty(k){ let suggestProperty = SuggestProperty() suggestProperty.name = k suggestProperty.type = "UNDEFINED" suggestProperty.canBeReplaced = true suggestProperty.isOptional = true if currentClass!.subClasses.filter({$0.className == suggestProperty.name}).count == 0{ currentClass!.properties.append(suggestProperty) } } } } } private func traverseDictionary(JSON:[String:AnyObject]){ for (k,v) in JSON{ if v is [String:AnyObject]{ let filtered = classList.filter({$0.className == k}) if filtered.count > 0 && currentClass != nil && currentClass!.isFromArray{ let theClass = filtered.first! classOrder.append(theClass.className) } else{ let newClass = SuggestClass(className: k) if classList.filter({$0.className == newClass.className}).count == 0{ let parse = SuggestToParse() parse.key = k parse.value = v as! [String:AnyObject] newClass.toParse.append(parse) classList.append(newClass) if currentClass != nil{ let propertyThatShouldBeClass = currentClass!.properties.filter({$0.name == newClass.className}) if propertyThatShouldBeClass.count > 0{ let theProperty = propertyThatShouldBeClass.first! currentClass!.properties = currentClass!.properties.filter({$0.name != theProperty.name}) } if currentClass!.subClasses.filter({$0.className == newClass.className}).count == 0{ newClass.isOptional = true currentClass!.subClasses.append(newClass) //display purposes only } } } } } if v is [[String:AnyObject]]{ let suggestProperty = SuggestProperty() suggestProperty.name = k if (v as! [[String:AnyObject]]).count > 0{ suggestProperty.canBeReplaced = false } var propertyType = "[\(k)]" if k.hasSuffix("s"){ propertyType = "[\(k.substringToIndex(k.endIndex.predecessor()))]" } suggestProperty.type = propertyType if (currentClass != nil && !currentClass!.hasProperty(k)){ currentClass!.properties.append(suggestProperty) } else if currentClass != nil{ suggestProperty.instances += 1 //count number of times this property has shown up, if it's less that total times the class is seen then it's optional } let newClass = SuggestClass(className: propertyType.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")) if classList.filter({$0.className == newClass.className}).count == 0{ newClass.isFromArray = true if (v as! [[String:AnyObject]]).count > 0{ let parse = SuggestToParse() parse.key = k parse.value = v as! [[String : AnyObject]] newClass.toParse.append(parse) } newClass.maxIterations = (v as! [[String:AnyObject]]).count classList.append(newClass) } else{ let filtered = classList.filter({$0.className == propertyType.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")}) if filtered.count > 0 && currentClass != nil && currentClass!.isFromArray{ let theClass = filtered.first! if (v as! [[String:AnyObject]]).count > 0{ let parse = SuggestToParse() parse.key = k parse.value = v as! [[String : AnyObject]] theClass.toParse.append(parse) } theClass.maxIterations = (v as! [[String:AnyObject]]).count } } } determineSimpleProperty(k, v: v) } if currentClass != nil && currentClass!.isFromArray{ currentClass!.instances += 1 currentClass!.iterations += 1 if currentClass!.iterations == currentClass!.maxIterations{ currentClass!.iterations = 0 //reset currentClass!.maxIterations = 1 //reset currentClass = nil for cl in classList{ let notStarted = cl.toParse.filter({!$0.started}).count if notStarted > 0{ currentClass = cl classOrder.append(currentClass!.className) break } } if currentClass != nil{ for tp in currentClass!.toParse{ if !tp.started{ if tp.value is [String:AnyObject]{ tp.started = true traverseDictionary(tp.value as! [String:AnyObject]) } else{ tp.started = true traverseArray(tp.value as! [[String:AnyObject]]) } } } } } else{ //continue } } else{ currentClass = nil for cl in classList{ let notStarted = cl.toParse.filter({!$0.started}).count if notStarted > 0{ currentClass = cl classOrder.append(currentClass!.className) break } } if currentClass != nil{ for tp in currentClass!.toParse{ if !tp.started{ if tp.value is [String:AnyObject]{ tp.started = true traverseDictionary(tp.value as! [String:AnyObject]) } else{ tp.started = true traverseArray(tp.value as! [[String:AnyObject]]) } } } } } } private func traverseArray(JSON:[[String:AnyObject]]){ for entry in JSON{ traverseDictionary(entry) } } func writeLine(message:String)->String{ numberOfLinesGenerated += 1 return message + "\r\n" } func writeList(){ var fileString = writeLine("") if singleFile{ fileString += writeLine("import Foundation") fileString += writeLine("") //line break } for cls in classList{ var clsName = cls.className.firstCapitalizedString if clsName.hasSuffix("s"){ clsName = clsName.substringToIndex(clsName.endIndex.predecessor()) } if NSClassFromString(clsName) != nil && ignoreImplementedClasses{ print("\(clsName) exists") }else{ if deliveryMethod == .FileSystem{ //TODO:print to local file system if singleFile == false{ fileString = writeClass(cls) _ = try? fileString.writeToFile(saveDirectory + "/" + clsName + ".swift", atomically: true, encoding: NSUTF8StringEncoding) } else{ fileString += writeClass(cls) } } else{ fileString += writeClass(cls) if !singleFile{ fileString += ("~eof~") } } } if !singleFile && cls.className != classList.last!.className{ fileString += writeLine("") fileString += writeLine("import Foundation") fileString += writeLine("") //line break } } if deliveryMethod == .URL{ post(["code":fileString,"lines":numberOfLinesGenerated,"singleFile":singleFile], url: "http://www.jsonsuggest.com/api/uploadCode") } else if deliveryMethod == .FileSystem{ if singleFile{ _ = try? fileString.writeToFile(saveDirectory + "/Models.swift", atomically: true, encoding: NSUTF8StringEncoding) } print("Your files have been saved to : \(saveDirectory)") print("") if singleFile{ print("Models.swift") } else{ for cls in classList { var clsName = cls.className.firstCapitalizedString if clsName.hasSuffix("s"){ clsName = clsName.substringToIndex(clsName.endIndex.predecessor()) } print("\(clsName).swift") } } print("") print("=== Stats ===") print("") print("Number of lines generated: \(numberOfLinesGenerated)") print("Total time saved: \(Float(numberOfLinesGenerated)/750.0 * 8)") print("(Assuming 750 lines of code per day is typical for this type of work)") print("") print("💰 If your time is valuable, please consider donating to futher development at the link below... 💰") print("") print("https://cash.me/$AndrewGene") print("") print("Thanks") } //print("*********************-End Suggestions-***********************") } func writeClass(cls:SuggestClass)->String{ var fileString = "" var clsName = cls.className.firstCapitalizedString if clsName.hasSuffix("s"){ clsName = clsName.substringToIndex(clsName.endIndex.predecessor()) } if ignoreImplementedClasses{ fileString += writeLine("@objc(\(clsName))") } fileString += writeLine("public class \(clsName)\(ignoreImplementedClasses ? " : NSObject" : ""){") fileString += writeLine("") //line break for prop in cls.properties{ var propString = " var \(prop.name.propertycaseString)\(prop.isOptional ? " : \(prop.type.firstCapitalizedString)?" : "") = " if prop.isOptional{ propString += "nil" if prop.type == "UNDEFINED"{ propString = propString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String") propString += " //**This was actually undefined--being set to String by default**" } } else{ if prop.type.hasPrefix("["){ propString += "\(prop.type.firstCapitalizedString)()" } else if defaultValues[prop.type.firstCapitalizedString] != nil{ propString += defaultValues[prop.type.firstCapitalizedString]! } else{ propString += prop.type.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "\"\" //**This was actually undefined--being set to String by default**") } } fileString += writeLine(propString) } fileString += writeLine("") //line break for cl in cls.subClasses{ var className = cl.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } if cl.isOptional{ let clString = " var \(cl.className.propertycaseString) : \(className)? = nil" fileString += writeLine(clString) } else{ let clString = " var \(cl.className.propertycaseString) = \(className)()" fileString += writeLine(clString) } } fileString += writeLine("") //line break fileString += writeLine(" \(ignoreImplementedClasses ? "override " : "")init(){") fileString += writeLine("") //line break fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" init?(JSON:AnyObject?){") fileString += writeLine(" var json = JSON") fileString += writeLine(" if json != nil{") fileString += writeLine(" if json is [String:AnyObject]{") fileString += writeLine(" if let firstKey = (json as! [String:AnyObject]).keys.first{") fileString += writeLine(" if firstKey == \"\(clsName)\"{") fileString += writeLine(" json = json![firstKey]") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine("") //line break //meat of the class goes here let optionalProperties = cls.properties.filter({$0.isOptional}) let requiredProperties = cls.properties.filter({!$0.isOptional}) let optionalClasses = cls.subClasses.filter({!$0.isOptional}) let requiredClasses = cls.subClasses.filter({!$0.isOptional}) /*for property in cls.properties { if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [[String:AnyObject]]{") print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") print(" }") } /*else if !property.isSimple(){ //object print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [String:AnyObject]{") print(" self.\(property.name.propertycaseString) = \(property.type)(\(property.name.propertycaseString))") print(" }") }*/ else{ print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String")){") print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") print(" }") } }*/ if requiredProperties.count > 0{ fileString += writeLine(" guard") for property in requiredProperties{ if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects fileString += writeLine(" let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? [[String:AnyObject]]\(property.name == requiredProperties.last!.name ? "" : ",")") //print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") //print(" }") } else{ fileString += writeLine(" let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String"))\(property.name == requiredProperties.last!.name ? "" : ",")") //print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") //print(" }") } } fileString += writeLine(" else{") //print(" print(\"required \(clsName) property is missing\")") fileString += writeLine(" return nil") fileString += writeLine(" }") fileString += writeLine("") //line break for property in requiredProperties{ if property.type.hasPrefix("[") && !property.isSimple(){ fileString += writeLine(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") } else{ fileString += writeLine(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") } } fileString += writeLine("") //line break } for property in optionalProperties { if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects fileString += writeLine(" if let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? [[String:AnyObject]]{") fileString += writeLine(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") fileString += writeLine(" }") } /*else if !property.isSimple(){ //object print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [String:AnyObject]{") print(" self.\(property.name.propertycaseString) = \(property.type)(\(property.name.propertycaseString))") print(" }") }*/ else{ fileString += writeLine(" if let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String")){") fileString += writeLine(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") fileString += writeLine(" }") } } if optionalProperties.count > 0{ fileString += writeLine("") //line break } if requiredClasses.count > 0{ fileString += writeLine(" guard") for sub in requiredClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } fileString += writeLine(" let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [[String:AnyObject]]\(sub.className == requiredClasses.last!.className ? "" : ",")") } fileString += writeLine(" else{") //print(" print(\"required \(clsName) class is missing\")") fileString += writeLine(" return nil") fileString += writeLine(" }") fileString += writeLine("") //line break for sub in requiredClasses{ fileString += writeLine(" self.\(sub.className.propertycaseString) = \(sub.className.propertycaseString)") } fileString += writeLine("") //line break } for sub in optionalClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } fileString += writeLine(" if let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [String:AnyObject]{") fileString += writeLine(" self.\(sub.className.propertycaseString) = \(className)(JSON: \(sub.className.propertycaseString))") fileString += writeLine(" }") } if optionalClasses.count > 0{ fileString += writeLine("") //line break } /*for sub in cls.subClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } print(" if let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [String:AnyObject]{") print(" self.\(sub.className.propertycaseString) = \(className)(JSON: \(sub.className.propertycaseString))") print(" }") }*/ //end of meat fileString += writeLine("") //line break fileString += writeLine(" }") fileString += writeLine(" else{") fileString += writeLine(" return nil") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" else{") fileString += writeLine(" return nil") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" class func fromJSONArray(JSON:[[String:AnyObject]]) -> [\(clsName)]{") fileString += writeLine(" var returnArray = [\(clsName)]()") fileString += writeLine(" for entry in JSON{") fileString += writeLine(" if let ent = \(clsName)(JSON: entry){") fileString += writeLine(" returnArray.append(ent)") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" return returnArray") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" private func traverseJSON(inout \(clsName.propertycaseString + "s"):[\(clsName)], JSON:AnyObject, complete:((\(clsName.propertycaseString + "s"):[\(clsName)])->())?){") fileString += writeLine(" if JSON is [String:AnyObject]{") fileString += writeLine(" for (_,v) in (JSON as! [String:AnyObject]){") fileString += writeLine(" if v is [String:AnyObject]{") fileString += writeLine(" if let attempt = \(clsName)(JSON: v as! [String:AnyObject]){") fileString += writeLine(" \(clsName.propertycaseString + "s").append(attempt)") fileString += writeLine(" }") fileString += writeLine(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: v as! [String:AnyObject], complete: nil)") fileString += writeLine(" }") fileString += writeLine(" else if v is [[String:AnyObject]]{") fileString += writeLine(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: v as! [[String:AnyObject]], complete: nil)") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" else if JSON is [[String:AnyObject]]{") fileString += writeLine(" for entry in (JSON as! [[String:AnyObject]]){") fileString += writeLine(" if let attempt = \(clsName)(JSON: entry){") fileString += writeLine(" \(clsName.propertycaseString + "s").append(attempt)") fileString += writeLine(" }") fileString += writeLine(" else{") fileString += writeLine(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: entry, complete: nil)") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" if complete != nil{") fileString += writeLine(" complete!(\(clsName.propertycaseString + "s"): \(clsName.propertycaseString + "s"))") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" func findInJSON(JSON:AnyObject, complete:((\(clsName.propertycaseString + "s"):[\(clsName)])->())?){") fileString += writeLine(" var \(clsName.propertycaseString + "s") = [\(clsName)]()") fileString += writeLine(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: JSON) { (\(clsName.propertycaseString + "s")) in") fileString += writeLine(" if complete != nil{") fileString += writeLine(" complete!(\(clsName.propertycaseString + "s"): \(clsName.propertycaseString + "s"))") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine("}") fileString += writeLine("") //line break fileString += writeLine("extension \(clsName){") fileString += writeLine(" var toJSON: [String:AnyObject] {") fileString += writeLine(" var jsonObject = [String:AnyObject]()") for property in requiredProperties{ if property.isSimple() || property.type == "UNDEFINED"{ fileString += writeLine(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)") } else{ fileString += writeLine(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString).toJSONArray") } } if requiredProperties.count > 0{ fileString += writeLine("") //line break } for property in optionalProperties{ if property.isSimple() || property.type == "UNDEFINED"{ fileString += writeLine(" if self.\(property.name.propertycaseString) != nil{") fileString += writeLine(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)!") fileString += writeLine(" }") } else{ fileString += writeLine(" if self.\(property.name.propertycaseString) != nil{") fileString += writeLine(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)!.toJSONArray") fileString += writeLine(" }") } } if optionalProperties.count > 0{ fileString += writeLine("") //line break } for sub in requiredClasses{ fileString += writeLine(" jsonObject[\"\(sub.className.propertycaseString)\"] = self.\(sub.className.propertycaseString).toJSON") } if requiredClasses.count > 0{ fileString += writeLine("") //line break } for sub in optionalClasses{ fileString += writeLine(" if self.\(sub.className.propertycaseString) != nil{") fileString += writeLine(" jsonObject[\"\(sub.className.propertycaseString)\"] = self.\(sub.className.propertycaseString).toJSON") fileString += writeLine(" }") } if optionalClasses.count > 0{ fileString += writeLine("") //line break } fileString += writeLine(" return jsonObject") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" var toJSONString: String {") fileString += writeLine(" var jsonString = \"\"") for property in requiredProperties{ if property.isSimple() || property.type == "UNDEFINED"{ fileString += writeLine(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString))\\\"\"") } else{ fileString += writeLine(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString).toJSONString)\\\"\"") } } if requiredProperties.count > 0{ fileString += writeLine("") //line break } for property in optionalProperties{ if property.isSimple() || property.type == "UNDEFINED"{ fileString += writeLine(" if self.\(property.name.propertycaseString) != nil{") fileString += writeLine(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString)!)\\\"\"") fileString += writeLine(" }") } else{ fileString += writeLine(" if self.\(property.name.propertycaseString) != nil{") fileString += writeLine(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString)!.toJSONString)\\\"\"") fileString += writeLine(" }") } } if optionalProperties.count > 0{ fileString += writeLine("") //line break } for sub in requiredClasses{ fileString += writeLine(" jsonString += \", \\\"\(sub.className.propertycaseString)\\\":\\\"\\(self.\(sub.className.propertycaseString).toJSONString)\\\"\"") } if requiredClasses.count > 0{ fileString += writeLine("") //line break } for sub in optionalClasses{ fileString += writeLine(" if self.\(sub.className.propertycaseString) != nil{") fileString += writeLine(" jsonString += \", \\\"\(sub.className.propertycaseString)\\\":\\\"\\(self.\(sub.className.propertycaseString).toJSONString)\\\"\"") fileString += writeLine(" }") } if optionalClasses.count > 0{ fileString += writeLine("") //line break } if cls.properties.count + cls.subClasses.count > 0{ fileString += writeLine(" jsonString = String(jsonString.characters.dropFirst()) //removes the ','") fileString += writeLine(" jsonString = String(jsonString.characters.dropFirst()) //removes the beginning space") } fileString += writeLine("") //line break fileString += writeLine(" return jsonString") fileString += writeLine(" }") fileString += writeLine("}") fileString += writeLine("") //line break fileString += writeLine("extension Array where Element:\(clsName){") fileString += writeLine(" var toJSONArray : [[String:AnyObject]]{") fileString += writeLine(" var returnArray = [[String:AnyObject]]()") fileString += writeLine(" for entry in self{") fileString += writeLine(" returnArray.append(entry.toJSON)") fileString += writeLine(" }") fileString += writeLine(" return returnArray") fileString += writeLine(" }") fileString += writeLine("") //line break fileString += writeLine(" var toJSONString : String{") fileString += writeLine(" var returnString = \"\"") fileString += writeLine(" for entry in self{") fileString += writeLine(" returnString += entry.toJSONString") fileString += writeLine(" }") fileString += writeLine(" return returnString") fileString += writeLine(" }") fileString += writeLine("}") fileString += writeLine("") //line break return fileString } func printList(){ if ignoreImplementedClasses{ print("!!!!! FOR THE \"ignoreImplementedClasses\" FEATURE TO WORK, THE CLASS MUST SUBCLASS NSOBJECT !!!!!") } //print("********************-Class Suggestions-************************") print("") //line break if singleFile{ print("import Foundation") print("") //line break } for cls in classList{ var clsName = cls.className.firstCapitalizedString if clsName.hasSuffix("s"){ clsName = clsName.substringToIndex(clsName.endIndex.predecessor()) } if NSClassFromString(clsName) != nil && ignoreImplementedClasses{ print("\(clsName) exists") }else{ printClass(cls) if !singleFile{ print("~eof~") } } if !singleFile && cls.className != classList.last!.className{ print("") print("import Foundation") print("") //line break } } //print("*********************-End Suggestions-***********************") } func printClass(cls:SuggestClass){ var clsName = cls.className.firstCapitalizedString if clsName.hasSuffix("s"){ clsName = clsName.substringToIndex(clsName.endIndex.predecessor()) } if ignoreImplementedClasses{ print("@objc(\(clsName))") } print("public class \(clsName)\(ignoreImplementedClasses ? " : NSObject" : ""){") print("") //line break for prop in cls.properties{ var propString = " var \(prop.name.propertycaseString)\(prop.isOptional ? " : \(prop.type.firstCapitalizedString)?" : "") = " if prop.isOptional{ propString += "nil" if prop.type == "UNDEFINED"{ propString = propString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String") propString += " //**This was actually undefined--being set to String by default**" } } else{ if prop.type.hasPrefix("["){ propString += "\(prop.type.firstCapitalizedString)()" } else if defaultValues[prop.type.firstCapitalizedString] != nil{ propString += defaultValues[prop.type.firstCapitalizedString]! } else{ propString += prop.type.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "\"\" //**This was actually undefined--being set to String by default**") } } print(propString) } print("") //line break for cl in cls.subClasses{ var className = cl.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } if cl.isOptional{ let clString = " var \(cl.className.propertycaseString) : \(className)? = nil" print(clString) } else{ let clString = " var \(cl.className.propertycaseString) = \(className)()" print(clString) } } print("") //line break print(" \(ignoreImplementedClasses ? "override " : "")init(){") print("") //line break print(" }") print("") //line break print(" init?(JSON:AnyObject?){") print(" var json = JSON") print(" if json != nil{") print(" if json is [String:AnyObject]{") print(" if let firstKey = (json as! [String:AnyObject]).keys.first{") print(" if firstKey == \"\(clsName)\"{") print(" json = json![firstKey]") print(" }") print(" }") print("") //line break //meat of the class goes here let optionalProperties = cls.properties.filter({$0.isOptional}) let requiredProperties = cls.properties.filter({!$0.isOptional}) let optionalClasses = cls.subClasses.filter({!$0.isOptional}) let requiredClasses = cls.subClasses.filter({!$0.isOptional}) /*for property in cls.properties { if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [[String:AnyObject]]{") print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") print(" }") } /*else if !property.isSimple(){ //object print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [String:AnyObject]{") print(" self.\(property.name.propertycaseString) = \(property.type)(\(property.name.propertycaseString))") print(" }") }*/ else{ print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String")){") print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") print(" }") } }*/ if requiredProperties.count > 0{ print(" guard") for property in requiredProperties{ if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects print(" let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? [[String:AnyObject]]\(property.name == requiredProperties.last!.name ? "" : ",")") //print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") //print(" }") } else{ print(" let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String"))\(property.name == requiredProperties.last!.name ? "" : ",")") //print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") //print(" }") } } print(" else{") //print(" print(\"required \(clsName) property is missing\")") print(" return nil") print(" }") print("") //line break for property in requiredProperties{ if property.type.hasPrefix("[") && !property.isSimple(){ print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") } else{ print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") } } print("") //line break } for property in optionalProperties { if property.type.hasPrefix("[") && !property.isSimple(){ //array of objects print(" if let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? [[String:AnyObject]]{") print(" self.\(property.name.propertycaseString) = \(property.type.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")).fromJSONArray(\(property.name.propertycaseString))") print(" }") } /*else if !property.isSimple(){ //object print(" if let \(property.name.propertycaseString) = json[\"\(property.name)\"] as? [String:AnyObject]{") print(" self.\(property.name.propertycaseString) = \(property.type)(\(property.name.propertycaseString))") print(" }") }*/ else{ print(" if let \(property.name.propertycaseString) = json?[\"\(property.name)\"] as? \(property.type.firstCapitalizedString.stringByReplacingOccurrencesOfString("UNDEFINED", withString: "String")){") print(" self.\(property.name.propertycaseString) = \(property.name.propertycaseString)") print(" }") } } if optionalProperties.count > 0{ print("") //line break } if requiredClasses.count > 0{ print(" guard") for sub in requiredClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } print(" let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [[String:AnyObject]]\(sub.className == requiredClasses.last!.className ? "" : ",")") } print(" else{") //print(" print(\"required \(clsName) class is missing\")") print(" return nil") print(" }") print("") //line break for sub in requiredClasses{ print(" self.\(sub.className.propertycaseString) = \(sub.className.propertycaseString)") } print("") //line break } for sub in optionalClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } print(" if let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [String:AnyObject]{") print(" self.\(sub.className.propertycaseString) = \(className)(JSON: \(sub.className.propertycaseString))") print(" }") } if optionalClasses.count > 0{ print("") //line break } /*for sub in cls.subClasses{ var className = sub.className.firstCapitalizedString if className.hasSuffix("s"){ className = className.substringToIndex(className.endIndex.predecessor()) } print(" if let \(sub.className.propertycaseString) = json?[\"\(sub.className)\"] as? [String:AnyObject]{") print(" self.\(sub.className.propertycaseString) = \(className)(JSON: \(sub.className.propertycaseString))") print(" }") }*/ //end of meat print("") //line break print(" }") print(" else{") print(" return nil") print(" }") print(" }") print(" else{") print(" return nil") print(" }") print(" }") print("") //line break print(" class func fromJSONArray(JSON:[[String:AnyObject]]) -> [\(clsName)]{") print(" var returnArray = [\(clsName)]()") print(" for entry in JSON{") print(" if let ent = \(clsName)(JSON: entry){") print(" returnArray.append(ent)") print(" }") print(" }") print(" return returnArray") print(" }") print("") //line break print(" private func traverseJSON(inout \(clsName.propertycaseString + "s"):[\(clsName)], JSON:AnyObject, complete:((\(clsName.propertycaseString + "s"):[\(clsName)])->())?){") print(" if JSON is [String:AnyObject]{") print(" for (_,v) in (JSON as! [String:AnyObject]){") print(" if v is [String:AnyObject]{") print(" if let attempt = \(clsName)(JSON: v as! [String:AnyObject]){") print(" \(clsName.propertycaseString + "s").append(attempt)") print(" }") print(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: v as! [String:AnyObject], complete: nil)") print(" }") print(" else if v is [[String:AnyObject]]{") print(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: v as! [[String:AnyObject]], complete: nil)") print(" }") print(" }") print(" }") print(" else if JSON is [[String:AnyObject]]{") print(" for entry in (JSON as! [[String:AnyObject]]){") print(" if let attempt = \(clsName)(JSON: entry){") print(" \(clsName.propertycaseString + "s").append(attempt)") print(" }") print(" else{") print(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: entry, complete: nil)") print(" }") print(" }") print(" }") print(" if complete != nil{") print(" complete!(\(clsName.propertycaseString + "s"): \(clsName.propertycaseString + "s"))") print(" }") print(" }") print("") //line break print(" func findInJSON(JSON:AnyObject, complete:((\(clsName.propertycaseString + "s"):[\(clsName)])->())?){") print(" var \(clsName.propertycaseString + "s") = [\(clsName)]()") print(" traverseJSON(&\(clsName.propertycaseString + "s"), JSON: JSON) { (\(clsName.propertycaseString + "s")) in") print(" if complete != nil{") print(" complete!(\(clsName.propertycaseString + "s"): \(clsName.propertycaseString + "s"))") print(" }") print(" }") print(" }") print("") //line break print("}") print("") //line break print("extension \(clsName){") print(" var toJSON: [String:AnyObject] {") print(" var jsonObject = [String:AnyObject]()") for property in requiredProperties{ if property.isSimple() || property.type == "UNDEFINED"{ print(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)") } else{ print(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString).toJSONArray") } } if requiredProperties.count > 0{ print("") //line break } for property in optionalProperties{ if property.isSimple() || property.type == "UNDEFINED"{ print(" if self.\(property.name.propertycaseString) != nil{") print(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)!") print(" }") } else{ print(" if self.\(property.name.propertycaseString) != nil{") print(" jsonObject[\"\(property.name.propertycaseString)\"] = self.\(property.name.propertycaseString)!.toJSONArray") print(" }") } } if optionalProperties.count > 0{ print("") //line break } for sub in requiredClasses{ print(" jsonObject[\"\(sub.className.propertycaseString)\"] = self.\(sub.className.propertycaseString).toJSON") } if requiredClasses.count > 0{ print("") //line break } for sub in optionalClasses{ print(" if self.\(sub.className.propertycaseString) != nil{") print(" jsonObject[\"\(sub.className.propertycaseString)\"] = self.\(sub.className.propertycaseString).toJSON") print(" }") } if optionalClasses.count > 0{ print("") //line break } print(" return jsonObject") print(" }") print("") //line break print(" var toJSONString: String {") print(" var jsonString = \"\"") for property in requiredProperties{ if property.isSimple() || property.type == "UNDEFINED"{ print(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString))\\\"\"") } else{ print(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString).toJSONString)\\\"\"") } } if requiredProperties.count > 0{ print("") //line break } for property in optionalProperties{ if property.isSimple() || property.type == "UNDEFINED"{ print(" if self.\(property.name.propertycaseString) != nil{") print(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString)!)\\\"\"") print(" }") } else{ print(" if self.\(property.name.propertycaseString) != nil{") print(" jsonString += \", \\\"\(property.name.propertycaseString)\\\":\\\"\\(self.\(property.name.propertycaseString)!.toJSONString)\\\"\"") print(" }") } } if optionalProperties.count > 0{ print("") //line break } for sub in requiredClasses{ print(" jsonString += \", \\\"\(sub.className.propertycaseString)\\\":\\\"\\(self.\(sub.className.propertycaseString).toJSONString)\\\"\"") } if requiredClasses.count > 0{ print("") //line break } for sub in optionalClasses{ print(" if self.\(sub.className.propertycaseString) != nil{") print(" jsonString += \", \\\"\(sub.className.propertycaseString)\\\":\\\"\\(self.\(sub.className.propertycaseString).toJSONString)\\\"\"") print(" }") } if optionalClasses.count > 0{ print("") //line break } if cls.properties.count + cls.subClasses.count > 0{ print(" jsonString = String(jsonString.characters.dropFirst()) //removes the ','") print(" jsonString = String(jsonString.characters.dropFirst()) //removes the beginning space") } print("") //line break print(" return jsonString") print(" }") print("}") print("") //line break print("extension Array where Element:\(clsName){") print(" var toJSONArray : [[String:AnyObject]]{") print(" var returnArray = [[String:AnyObject]]()") print(" for entry in self{") print(" returnArray.append(entry.toJSON)") print(" }") print(" return returnArray") print(" }") print("") //line break print(" var toJSONString : String{") print(" var returnString = \"\"") print(" for entry in self{") print(" returnString += entry.toJSONString") print(" }") print(" return returnString") print(" }") print("}") print("") //line break //print("---------------------------") print("") //line break } func post(params : Dictionary<String, AnyObject>, url : String) { do { let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted) // create post request let url = NSURL(string: url)! let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" // insert json data to the request request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonData let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in if error != nil{ print("Error -> \(error)") return } do { if let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]{ if let link = result["link"] as? String{ print("Download your file at ... ****************************************") print("") print(" 👉 \(link) 👈 ") print("") print("This link is only good for 1 hour") print("") print("‼️ NO VALUES FROM AN API ARE EVER SENT TO jsonsuggest.com ‼️") print("******************************************************************") } } } catch { print("Error -> \(error)") } } task.resume() } catch { print(error) } } } public enum DeliveryMethod: String{ case Console = "Console" case URL = "URL" case FileSystem = "FileSystem" } public class SuggestClass{ var className = "" var subClasses = [SuggestClass]() var properties = [SuggestProperty]() var isFromArray = false var maxIterations = 1 var iterations = 0 var toParse = [SuggestToParse]() var instances = 0 var isOptional = false init(className:String){ self.className = className } func hasClass(name:String)->Bool{ return self.subClasses.filter({$0.className == name}).count > 0 } func hasProperty(name:String)->Bool{ return self.properties.filter({$0.name == name}).count > 0 } } public class SuggestProperty{ var type = "" var isOptional = false var name = "" var canBeReplaced = true //some JSON messages will use "" for a null value; when this is the case, we map it to a String value but might replace it with another type once it is filled in var instances = 1 func isSimple()->Bool{ if type == "String" || type == "Int" || type == "Double" || type == "Float" || type == "Bool" || type == "[String]" || type == "[Int]" || type == "[Double]" || type == "[Float]" || type == "[Bool]"{ return true } return false } } public class SuggestToParse{ var key = "" var value:AnyObject? = nil var started = false } extension String{ var propertycaseString: String { let source = self if source == source.uppercaseString{ return source } var multipleUpperCaseInARow = false var lastCharUpperCase = false var upperCaseInFront = false var i = 0 for ch in source.characters{ let char = "\(ch)" if char == char.uppercaseString{ if lastCharUpperCase == true{ multipleUpperCaseInARow = true if i == 1{ upperCaseInFront = true } break } lastCharUpperCase = true } else{ lastCharUpperCase = false } i = i + 1 } if multipleUpperCaseInARow{ if !upperCaseInFront{ return source.firstLowerCaseString } return source } else{ return source.camelcaseString } } var camelcaseString: String { let source = self if source.characters.contains(" ") { let first = source.substringToIndex(source.startIndex.advancedBy(1)) let cammel = source.capitalizedString.stringByReplacingOccurrencesOfString(" ", withString: "") let rest = String(cammel.characters.dropFirst()) return "\(first)\(rest)" } else { let first = source.lowercaseString.substringToIndex(source.startIndex.advancedBy(1)) let rest = String(source.characters.dropFirst()) return "\(first)\(rest)" } } var firstCapitalizedString: String { let source = self var isArray = false if source.hasPrefix("["){ isArray = true } let first:String let rest:String if isArray{ let bufferString = String(source.characters.dropFirst()) first = bufferString.lowercaseString.substringToIndex(bufferString.startIndex.advancedBy(1)).capitalizedString rest = String(bufferString.characters.dropFirst()) } else{ first = source.lowercaseString.substringToIndex(source.startIndex.advancedBy(1)).capitalizedString rest = String(source.characters.dropFirst()) } return "\(isArray ? "[" : "")\(first)\(rest)" } var firstLowerCaseString: String { let source = self var isArray = false if source.hasPrefix("["){ isArray = true } let first:String let rest:String if isArray{ let bufferString = String(source.characters.dropFirst()) first = bufferString.lowercaseString.substringToIndex(bufferString.startIndex.advancedBy(1)).lowercaseString rest = String(bufferString.characters.dropFirst()) } else{ first = source.lowercaseString.substringToIndex(source.startIndex.advancedBy(1)).lowercaseString rest = String(source.characters.dropFirst()) } return "\(isArray ? "[" : "")\(first)\(rest)" } }
gpl-3.0
58fc67289a568f2dc5ce2d5dda6a7fbf
47.33099
312
0.488028
5.531042
false
false
false
false
mindogo/Krautreporter-iOS
Krautreporter/Krautreporter/Model/AuthorMO.swift
1
2915
import CoreData import SwiftyJSON @objc(AuthorMO) final class AuthorMO: _AuthorMO, ResponseCollectionManagedObjectsSerializable, ResponseManagedObjectSerializable { private func setRequiredValues(id: Int, name: String){ self.id = id self.name = name } /** fetch object by id (not objectId) if exists, otherwise create new entity and set id :param: context the used context :param: id <#id description#> :returns: fetched managed entity if already existing or newly created managed entity */ class func fetchOrCreate(context: NSManagedObjectContext, byCustomID id: NSNumber) -> AuthorMO{ let request = NSFetchRequest(entityName: self.entityName()) request.predicate = NSPredicate(format: "id == %@", id) if let result = (context.executeFetchRequest(request,error: nil) as? [AuthorMO]) where result.count > 0{ return result[0] }else { let author = AuthorMO(managedObjectContext: context) author.id = id return author } } //Mark: Response Serialization /** Creates a new managed object from json data. Uses fetchOrCreate to prevent duplicate entries using an id retrieved from json data. If the object already exists, values are updated :param: response response description :param: representation <#representation description#> :param: context <#context description#> :returns: a managed object of nil, if the context or json data is not valid */ static func managedEntityFromJson(response: NSHTTPURLResponse, representation: AnyObject, context: NSManagedObjectContext?) -> AuthorMO? { var json = JSON(representation) //if the json data was retrieved from a list, the data tag is not present json = json["data"] != nil ? json["data"] : json if let id = json["id"].int, name = json["name"].string, context = context{ var author: AuthorMO? context.performBlockAndWait(){ author = self.fetchOrCreate(context, byCustomID: id) author?.setRequiredValues(id, name: name) } return author } else { return nil } } static func collectionOfManagedEntities(#response: NSHTTPURLResponse, representation: AnyObject, context: NSManagedObjectContext?) -> [AuthorMO]{ let json = JSON(representation) var authors: [AuthorMO] = [] for (index: String, subJson: JSON) in json["data"] { if let author = AuthorMO.managedEntityFromJson(response, representation: subJson.rawValue, context: context){ authors.append(author) } } return authors } }
mit
b76fc5f58c5873d5256f26500c3cc07d
34.987654
149
0.614751
5.08726
false
false
false
false
bigtreenono/NSPTools
RayWenderlich/Introduction to Swift/7 . Functions/ChallengeFunctions.playground/section-1.swift
1
220
func sumOfMultiples(#mult1:Int, #mult2:Int, max:Int=1000) -> Int { var sum = 0 for i in 0..<max { if i % mult1 == 0 || i % mult2 == 0 { sum += i } } return sum } sumOfMultiples(mult1: 3, mult2: 5)
mit
037d32ab4cc171fc7455a755f3b55359
19
66
0.540909
2.716049
false
false
false
false
wawandco/away
Example/Pods/Nimble/Nimble/Matchers/BeCloseTo.swift
1
4728
import Foundation internal let DefaultDelta = 0.0001 internal func isCloseTo(actualValue: Double?, expectedValue: Double, delta: Double, failureMessage: FailureMessage) -> Bool { failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))" if actualValue != nil { failureMessage.actualValue = "<\(stringify(actualValue!))>" } else { failureMessage.actualValue = "<nil>" } return actualValue != nil && abs(actualValue! - expectedValue) < delta } /// A Nimble matcher that succeeds when a value is close to another. This is used for floating /// point values which can have imprecise results when doing arithmetic on them. /// /// @see equal public func beCloseTo(expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<Double> { return NonNilMatcherFunc { actualExpression, failureMessage in return isCloseTo(actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage) } } /// A Nimble matcher that succeeds when a value is close to another. This is used for floating /// point values which can have imprecise results when doing arithmetic on them. /// /// @see equal public func beCloseTo(expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<NMBDoubleConvertible> { return NonNilMatcherFunc { actualExpression, failureMessage in return isCloseTo(actualExpression.evaluate()?.doubleValue, expectedValue: expectedValue.doubleValue, delta: delta, failureMessage: failureMessage) } } public class NMBObjCBeCloseToMatcher : NMBMatcher { var _expected: NSNumber var _delta: CDouble init(expected: NSNumber, within: CDouble) { _expected = expected _delta = within } public func matches(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let actualBlock: () -> NMBDoubleConvertible? = ({ return actualExpression() as? NMBDoubleConvertible }) let expr = Expression(expression: actualBlock, location: location) let matcher = beCloseTo(self._expected, within: self._delta) return matcher.matches(expr, failureMessage: failureMessage) } public func doesNotMatch(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let actualBlock: () -> NMBDoubleConvertible? = ({ return actualExpression() as? NMBDoubleConvertible }) let expr = Expression(expression: actualBlock, location: location) let matcher = beCloseTo(self._expected, within: self._delta) return matcher.doesNotMatch(expr, failureMessage: failureMessage) } public var within: (CDouble) -> NMBObjCBeCloseToMatcher { return ({ delta in return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta) }) } } extension NMBObjCMatcher { public class func beCloseToMatcher(expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher { return NMBObjCBeCloseToMatcher(expected: expected, within: within) } } public func beCloseTo(expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))" if let actual = actualExpression.evaluate() { if actual.count != expectedValues.count { return false } else { for (index, actualItem) in actual.enumerate() { if fabs(actualItem - expectedValues[index]) > delta { return false } } return true } } return false } } // MARK: - Operators infix operator ≈ {} public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) { lhs.to(beCloseTo(rhs)) } public func ≈(lhs: Expectation<Double>, rhs: Double) { lhs.to(beCloseTo(rhs)) } public func ≈(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) { lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) } public func ==(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) { lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) } // make this higher precedence than exponents so the Doubles either end aren't pulled in // unexpectantly infix operator ± { precedence 170 } public func ±(lhs: Double, rhs: Double) -> (expected: Double, delta: Double) { return (expected: lhs, delta: rhs) }
mit
2c3bd16567b8b1904a30f4333c60f95a
38.983051
154
0.682916
4.848921
false
false
false
false
SlimGinz/HomeworkHelper
Homework Helper/LBHamburgerButton.swift
1
12934
// // LBHamburgerButton.swift // HamburgerButton // // Created by Bang Nguyen on 03/09/2014. // Copyright (c) Năm 2014 Bang Nguyen. All rights reserved. // // This code is distributed under the terms and conditions of the MIT license. // Copyright (c) 2014 Bang Nguyen // // 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 import QuartzCore /** * LBHamburgerButton is a sub-class of UIButton, displays a hamburger button * and other state button without using image * * This is a simple button with 2 state. At initialization, it has state "Hamburger" * which means 3 lines. After switch state, it has state "Not hamburger" and * displays a back button/a close button. * * This button support 2 type: * - BackButton - display <- after switch state * - CloseButton - display X after switch state * * Those type can be setted when initialization or manually at any time/any event. * */ enum LBHamburgerButtonType { case /** Show back (<-) button after switch state/animate. */ BackButton, /** Show close (X) button after switch state/animate. */ CloseButton // other type } enum LBHamburgerButtonState { case /** Initialize state, with 3 lines (hamburger). */ Hamburger, /** State happened after animate. */ NotHamburger } class LBHamburgerButton: UIButton { /** * Current state of hamburger button. */ var hamburgerState = LBHamburgerButtonState.Hamburger /** * Type of hamburger button. */ var hamburgerType = LBHamburgerButtonType.BackButton /** * Time for animation. Default is 0.5f. */ var hamburgerAnimationDuration = 0.4 private var _lineHeight : CGFloat = 50/6, _lineWidth : CGFloat = 50, _lineSpacing : CGFloat = 5 private var _lineCenter : CGPoint private var _lineArray : [ CAShapeLayer ] = [] private var _lineCreated = false // MARK: // MARK: Public functions required init(coder: NSCoder) { fatalError("NSCoding not supported") } init(frame:CGRect, type:LBHamburgerButtonType, lineWidth:CGFloat, lineHeight:CGFloat, lineSpacing:CGFloat, lineCenter:CGPoint, color:UIColor) { _lineCenter = lineCenter super.init(frame: frame) self.setUpHamburger(type: type, lineWidth: lineWidth, lineHeight: lineHeight, lineSpacing: lineSpacing, lineCenter: lineCenter, color: color) } func setUpHamburger(#type:LBHamburgerButtonType, lineWidth:CGFloat, lineHeight:CGFloat, lineSpacing:CGFloat, lineCenter:CGPoint, color:UIColor) { if (_lineCreated) { // Lines have been created, do nothing. return; } hamburgerType = type _lineWidth = lineWidth _lineHeight = lineHeight _lineSpacing = lineSpacing _lineCenter = lineCenter var topLine = CAShapeLayer(frame: CGRectMake(0, 0, lineWidth, lineHeight), color: color, position: CGPointMake(lineCenter.x, lineCenter.y - lineHeight - lineSpacing)) var middleLine = CAShapeLayer(frame: CGRectMake(0, 0, lineWidth, lineHeight), color: color, position: lineCenter) var bottomLine = CAShapeLayer(frame: CGRectMake(0, 0, lineWidth, lineHeight), color: color, position: CGPointMake(lineCenter.x, lineCenter.y + lineHeight + lineSpacing)) _lineArray = [ topLine, middleLine, bottomLine] for layer in _lineArray { self.layer.addSublayer(layer) } _lineCreated = true; } func switchState() { animateButton(forward: hamburgerState == .Hamburger) hamburgerState = (hamburgerState == .Hamburger) ? .NotHamburger : .Hamburger } // MARK: // MARK: Private functions private func animateButton(#forward:Bool) { var anims = [ keyframeAnimations(lineIndex: 0, forward: forward), keyframeAnimations(lineIndex: 1, forward: forward), keyframeAnimations(lineIndex: 2, forward: forward) ] CATransaction.begin() CATransaction.setAnimationDuration(hamburgerAnimationDuration) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0)) var index = 0 for animations in anims { var layer = _lineArray[index] for anim in animations! { if !anim.removedOnCompletion { layer.addAnimation(anim, forKey: anim.keyPath) } else { layer.addAnimation(anim, value: anim.values.last as! NSValue, keyPath: anim.keyPath) } } index++ } CATransaction.commit() } private func keyframeAnimations(#lineIndex:Int, forward:Bool) -> [CAKeyframeAnimation]? { switch hamburgerType { case .BackButton: switch lineIndex { case 0: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (M_PI*5/4) ] : [ (M_PI*5/4), 0] animRotate.calculationMode = kCAAnimationCubic animRotate.keyTimes = [ 0, 0.33, 0.73, 1.0] var startPoint = forward ? CGPointMake(_lineCenter.x, _lineCenter.y - _lineHeight - _lineSpacing) : CGPointMake(_lineCenter.x - scale(10), _lineCenter.y + _lineHeight + scale(7.2)) var endPoint = forward ? CGPointMake(_lineCenter.x - scale(10), _lineCenter.y + _lineHeight + scale(7.2)) : CGPointMake(_lineCenter.x, _lineCenter.y - _lineHeight - _lineSpacing) var controlPoint = CGPointMake(_lineCenter.x + scale(15), _lineCenter.y) var animPosition = CAKeyframeAnimation(keyPath: "position") animPosition.path = UIBezierPath.animateBezierPath(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint).CGPath animPosition.removedOnCompletion = false animPosition.fillMode = kCAFillModeForwards return [ animRotate, animPosition ] case 1: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (M_PI) ] : [ (M_PI), 0] return [ animRotate ] case 2: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (-M_PI*5/4) ] : [ (-M_PI*5/4), 0] animRotate.calculationMode = kCAAnimationCubic animRotate.keyTimes = [ 0, 0.33, 0.73, 1.0] var startPoint = forward ? CGPointMake(_lineCenter.x, _lineCenter.y + _lineHeight + _lineSpacing) : CGPointMake(_lineCenter.x - scale(10), _lineCenter.y - _lineHeight - scale(7.2)) var endPoint = forward ? CGPointMake(_lineCenter.x - scale(10), _lineCenter.y - _lineHeight - scale(7.2)) : CGPointMake(_lineCenter.x, _lineCenter.y + _lineHeight + _lineSpacing) var controlPoint = CGPointMake(_lineCenter.x + scale(15), _lineCenter.y) var animPosition = CAKeyframeAnimation(keyPath: "position") animPosition.path = UIBezierPath.animateBezierPath(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint).CGPath animPosition.removedOnCompletion = false animPosition.fillMode = kCAFillModeForwards return [ animRotate, animPosition ] default: return nil } case .CloseButton: switch lineIndex { case 0: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (-M_PI*5/4) ] : [ (-M_PI*5/4), 0] animRotate.calculationMode = kCAAnimationCubic animRotate.keyTimes = [ 0, 0.33, 0.73, 1.0] var startPoint = forward ? CGPointMake(_lineCenter.x, _lineCenter.y - _lineHeight - _lineSpacing) : _lineCenter var endPoint = forward ? _lineCenter : CGPointMake(_lineCenter.x, _lineCenter.y - _lineHeight - _lineSpacing) var controlPoint = CGPointMake(_lineCenter.x + scale(20), _lineCenter.y - _lineHeight - scale(5)) var animPosition = CAKeyframeAnimation(keyPath: "position") animPosition.path = UIBezierPath.animateBezierPath(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint).CGPath animPosition.removedOnCompletion = false animPosition.fillMode = kCAFillModeForwards return [ animRotate, animPosition ] case 1: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (M_PI) ] : [ (M_PI), 0] var animScale = CAKeyframeAnimation(keyPath: "transform.scale.x") animScale.values = forward ? [ 1, 0.1 ] : [ 0.1, 1 ] return [ animRotate, animScale ] case 2: var animRotate = CAKeyframeAnimation(keyPath: "transform.rotation") animRotate.values = forward ? [ 0, (M_PI*5/4) ] : [ (M_PI*5/4), 0] animRotate.calculationMode = kCAAnimationCubic animRotate.keyTimes = [ 0, 0.33, 0.73, 1.0] var startPoint = forward ? CGPointMake(_lineCenter.x, _lineCenter.y + _lineHeight + _lineSpacing) : _lineCenter var endPoint = forward ? _lineCenter : CGPointMake(_lineCenter.x, _lineCenter.y + _lineHeight + _lineSpacing) var controlPoint = CGPointMake(_lineCenter.x - scale(20), _lineCenter.y + _lineHeight + scale(5)) var animPosition = CAKeyframeAnimation(keyPath: "position") animPosition.path = UIBezierPath.animateBezierPath(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint).CGPath animPosition.removedOnCompletion = false animPosition.fillMode = kCAFillModeForwards return [ animRotate, animPosition ] default: return nil } } } private func scale(value:CGFloat) -> CGFloat { return value/(50/_lineWidth) } } // MARK: // MARK: Supporting Extension // MARK: // MARK: CAShapeLayer extension extension CAShapeLayer { convenience init(frame:CGRect, color:UIColor, position:CGPoint) { self.init() var path = UIBezierPath() path.moveToPoint(CGPointMake(0, 0)) path.addLineToPoint(CGPointMake(frame.size.width, 0)) self.path = path.CGPath self.lineWidth = frame.size.height self.strokeColor = color.CGColor var bound : CGPathRef = CGPathCreateCopyByStrokingPath(self.path, nil, self.lineWidth, kCGLineCapButt, kCGLineJoinMiter, self.miterLimit) self.bounds = CGPathGetBoundingBox(bound) self.position = position } } // MARK: CALayer extension extension CALayer { func addAnimation(anim:CAAnimation!, value:NSValue!, keyPath:String!) { self.addAnimation(anim, forKey: keyPath) self.setValue(value, forKeyPath: keyPath) } } // MARK: UIBezierPath extension extension UIBezierPath { class func animateBezierPath(#startPoint:CGPoint, endPoint:CGPoint, controlPoint:CGPoint) -> UIBezierPath { var path = UIBezierPath() path.moveToPoint(startPoint) path.addQuadCurveToPoint(endPoint, controlPoint: controlPoint) return path } }
gpl-2.0
5541d8b78fe6cab716bdf46ef3060255
40.99026
196
0.624836
4.740836
false
false
false
false
apple/swift-atomics
Tests/AtomicsTests/LifetimeTracked.swift
1
2350
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Atomics open source project // // Copyright (c) 2014 - 2020 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 type that tracks the number of live instances. /// /// To be useful in more contexts, `LifetimeTracked` conforms to various /// protocols in trivial ways. /// /// `LifetimeTracked` is useful to check for leaks in algorithms and data /// structures. `StdlibUnittest` harness automatically checks that after each /// test has done executing, no `LifetimeTracked` instances exist. public final class LifetimeTracked { public init(_ value: Int, identity: Int = 0) { LifetimeTracked.instances += 1 LifetimeTracked._nextSerialNumber += 1 serialNumber = LifetimeTracked._nextSerialNumber self.value = value self.identity = identity } deinit { assert(serialNumber > 0, "double destruction!") LifetimeTracked.instances -= 1 serialNumber = -serialNumber } public static var instances: Int = 0 internal static var _nextSerialNumber = 0 public let value: Int public var identity: Int public var serialNumber: Int = 0 } extension LifetimeTracked : Equatable { public static func == (x: LifetimeTracked, y: LifetimeTracked) -> Bool { return x.value == y.value } } extension LifetimeTracked : Hashable { public var hashValue: Int { return value } public func hash(into hasher: inout Hasher) { hasher.combine(value) } } extension LifetimeTracked : Strideable { public func distance(to other: LifetimeTracked) -> Int { return self.value.distance(to: other.value) } public func advanced(by n: Int) -> LifetimeTracked { return LifetimeTracked(self.value.advanced(by: n)) } } extension LifetimeTracked : CustomStringConvertible { public var description: String { assert(serialNumber > 0, "dead Tracked!") return value.description } } public func < (x: LifetimeTracked, y: LifetimeTracked) -> Bool { return x.value < y.value }
apache-2.0
032fd65bd96438143b98033d660968ab
29.128205
80
0.66766
4.671968
false
false
false
false
TabletopAssistant/DiceKit
DiceKitTests/FrequencyDistribution_Tests.swift
1
16431
// // FrequencyDistribution_Tests.swift // DiceKit // // Created by Brentley Jones on 7/25/15. // Copyright © 2015 Brentley Jones. All rights reserved. // import XCTest import Nimble import SwiftCheck import DiceKit /// Tests the `FrequencyDistribution` type class FrequencyDistribution_Tests: XCTestCase { typealias SwiftCheckFrequenciesPerOutcome = DictionaryOf<FrequencyDistribution<Int>.Outcome, FrequencyDistribution<Int>.Frequency> let operationFixture1 = FrequencyDistribution([1: 2.0, 4: 3.0, 11: 1.0]) let operationFixture2 = FrequencyDistribution([1: 1.5, 2: 7.0]) let operationFixture3 = FrequencyDistribution([1: 6]) } // MARK: - init() tests extension FrequencyDistribution_Tests { func test_init_shouldSucceedWithFrequenciesPerOutcome() { property("init") <- forAll { (a: SwiftCheckFrequenciesPerOutcome) in let a = a.getDictionary let freqDist = FrequencyDistribution(a) return freqDist.frequenciesPerOutcome == a } } func test_init_shouldFilterZeroFrequencies() { let inputFrequenciesPerOutcome = [1: 1.0, 2: 0.0, 3: 1.23] let expected = [1: 1.0, 3: 1.23] let result = FrequencyDistribution(inputFrequenciesPerOutcome).frequenciesPerOutcome expect(result) == expected } } // MARK: - Equatable extension FrequencyDistribution_Tests { func test_shouldBeReflexive() { property("reflexive") <- forAll { (a: SwiftCheckFrequenciesPerOutcome) in let a = a.getDictionary return EquatableTestUtilities.checkReflexive { FrequencyDistribution(a) } } } func test_shouldBeSymmetric() { property("symmetric") <- forAll { (a: SwiftCheckFrequenciesPerOutcome) in let a = a.getDictionary return EquatableTestUtilities.checkSymmetric { FrequencyDistribution(a) } } } func test_shouldBeTransitive() { property("transitive") <- forAll { (a: SwiftCheckFrequenciesPerOutcome) in let a = a.getDictionary return EquatableTestUtilities.checkTransitive { FrequencyDistribution(a) } } } func test_shouldBeAbleToNotEquate() { property("non-equal") <- forAll { (a: SwiftCheckFrequenciesPerOutcome, b: SwiftCheckFrequenciesPerOutcome) in let a = a.getDictionary let b = b.getDictionary return (a != b) ==> { return EquatableTestUtilities.checkNotEquate( { FrequencyDistribution(a) }, { FrequencyDistribution(b) } ) } } } } // MARK: - Indexable extension FrequencyDistribution_Tests { func test_indexable_forIn() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1, 2:1, 3:4, 6:1] let expectedElements: [FrequencyDistribution<Int>._Element] = [(1, 1), (2, 1), (3, 4), (6, 1)] let freqDist = FrequencyDistribution(frequenciesPerOutcome) var elements: [FrequencyDistribution<Int>._Element] = [] for element in freqDist { elements.append(element) } for (index, element) in elements.enumerate() { let expectedElement = expectedElements[index] expect(element.0) == expectedElement.0 expect(element.1) == expectedElement.1 } } func test_indexForOutcome_shouldReturnIndexForValidOutcome() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1, 2:1, 3:4, 5:1] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let expectedStartIndex = freqDist.startIndex let startIndex = freqDist.indexForOutcome(1) let otherIndex = freqDist.indexForOutcome(5) expect(startIndex) == expectedStartIndex expect(otherIndex).toNot(beNil()) } func test_indexForOutcome_shouldReturnNilForInvalidOutcome() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1, 2:1, 3:4, 5:1] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let index = freqDist.indexForOutcome(77) expect(index).to(beNil()) } } // MARK: - Foundational Operations extension FrequencyDistribution_Tests { func test_mapOutcomes() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [ 7: 3.0, 6: 2.5, 5: 1.5, 4: 1.0, ] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [ 3: 5.5, 2: 2.5, ] // /2 let mappedOutcomes = freqDist.mapOutcomes { $0 / 2 } expect(mappedOutcomes.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_mapFrequencies() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [ 7: 3.0, 6: 2.5, 5: 1.5, 4: 1.0, ] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [ 7: 6.0, 6: 5.0, 5: 3.0, 4: 2.0, ] // *2 let mappedFrequencies = freqDist.mapFrequencies { $0 * 2 } expect(mappedFrequencies.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } } // MARK: - Primitive Operations extension FrequencyDistribution_Tests { func test_subscript() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let value = 3 let expectedOutcome = frequenciesPerOutcome[value] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let outcome = freqDist[value] expect(outcome) == expectedOutcome } func test_approximatelyEqual_shouldNotEqualForDifferentNumberOfValues() { let delta = 2e-15 // 64-bit. What about 32-bit? let outcome = 1.0 let x = FrequencyDistribution([1: outcome]) let y = FrequencyDistribution([1: outcome, 2: outcome]) let areApproxEqual = x.approximatelyEqual(y, delta: delta) expect(areApproxEqual) == false } func test_approximatelyEqual_shouldEqualForSame() { let delta = 2e-15 // 64-bit. What about 32-bit? let xOutcome = 1.0 let yOutcome = 1.0 let x = FrequencyDistribution([1: xOutcome]) let y = FrequencyDistribution([1: yOutcome]) let areApproxEqual = x.approximatelyEqual(y, delta: delta) expect(areApproxEqual) == true } func test_approximatelyEqual_shouldEqualWithinDelta() { let delta = 2e-15 // 64-bit. What about 32-bit? let xOutcome = 1.0 let yOutcome = 1.0 + delta - delta/10 let x = FrequencyDistribution([1: xOutcome]) let y = FrequencyDistribution([1: yOutcome]) let areApproxEqual = x.approximatelyEqual(y, delta: delta) expect(areApproxEqual) == true } func test_approximatelyEqual_shouldNotEqualOutsideDelta() { let delta = 2e-15 // 64-bit. What about 32-bit? let xOutcome = 1.0 let yOutcome = 1.0 + delta + delta/10 let x = FrequencyDistribution([1: xOutcome]) let y = FrequencyDistribution([1: yOutcome]) let areApproxEqual = x.approximatelyEqual(y, delta: delta) expect(areApproxEqual) != true } func test_negateOutcomes() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [-1:1.0, -2:1.0, -3:4.0, -4:1.0] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let negated = freqDist.negateOutcomes() expect(negated.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_shiftValues() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [4:1.0, 5:1.0, 6:4.0, 7:1.0] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let shifted = freqDist.shiftOutcomes(3) expect(shifted.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_scaleOutcomes() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.5, 2:1.5, 3:6.0, 4:1.5] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let scaled = freqDist.scaleFrequencies(1.5) expect(scaled.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_normalizeFrequencies() { // TODO: SwiftCheck let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0/7.0, 2:1.0/7.0, 3:4.0/7.0, 4:1.0/7.0] let freqDist = FrequencyDistribution(frequenciesPerOutcome) let normalized = freqDist.normalizeFrequencies() expect(normalized.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_minimumOutcome_shouldReturnMinimumOutcomeWithOutcomes() { let x = operationFixture1 let expectedMinimumOutcome = 1 let min = x.minimumOutcome() expect(min) == expectedMinimumOutcome } func test_maximumOutcome_shouldReturnMaximumOutcomeWithOutcomes() { let x = operationFixture1 let expectedMaximumOutcome = 11 let max = x.maximumOutcome() expect(max) == expectedMaximumOutcome } func test_singleOutcomeDistribution_shouldHaveEqualMinimumMaximumOutcomes() { let x = operationFixture3 let min = x.minimumOutcome() let max = x.maximumOutcome() expect(min) == max } func test_filterZeroFrequencies() { let delta: Double = ProbabilityMassConfig.probabilityEqualityDelta let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:0.0, 3:100.0, 4:(delta * 0.9), 5: -42.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 3:100.0, 5: -42.0] let result = FrequencyDistribution(frequenciesPerOutcome).filterZeroFrequencies(delta) expect(result.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } } // MARK: - Advanced Operations extension FrequencyDistribution_Tests { func test_add() { // TODO: SwiftCheck let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let yFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [4:6.0, 7:1.0, 8:0.5, 22:3.0] let expectedFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:7.0, 7:1.0, 8:0.5, 22:3.0] let x = FrequencyDistribution(xFrequenciesPerOutcome) let y = FrequencyDistribution(yFrequenciesPerOutcome) let z = x.add(y) expect(z.frequenciesPerOutcome) == expectedFrequenciesPerOutcome } func test_subtract() { let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:1.0, 2:1.0, 3:4.0, 4:1.0] let yFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [4:6.0, 7:1.0, 8:0.5, 22:3.0] let x = FrequencyDistribution(xFrequenciesPerOutcome) let y = FrequencyDistribution(yFrequenciesPerOutcome) let z = x.add(y) // x + y - y = x let result = z.subtract(y) expect(result.frequenciesPerOutcome) == x.frequenciesPerOutcome } func test_multiply() { // TODO: SwiftCheck /* 1 2 6 * 2 3 7 3 2 1 2 2 1 = 3 4 8 + 4 5 9 + 8 9 13 6 6 3 4 4 2 2 2 1 = 3 4 5 8 9 13 6 10 4 5 4 1 */ let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:3.0, 2:2.0, 6:1.0] let yFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 7:1.0] let zFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [3:6.0, 4:10.0, 5:4.0, 8:5.0, 9:4.0, 13:1.0] let x = FrequencyDistribution(xFrequenciesPerOutcome) let y = FrequencyDistribution(yFrequenciesPerOutcome) let expected = FrequencyDistribution(zFrequenciesPerOutcome) let z = x.multiply(y) expect(z) == expected } func test_divide() { //Does the reverse of multiply let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [1:3.0, 2:2.0, 6:1.0] let yFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 7:1.0] let zFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [3:6.0, 4:10.0, 5:4.0, 8:5.0, 9:4.0, 13:1.0] let z = FrequencyDistribution(zFrequenciesPerOutcome) let y = FrequencyDistribution(yFrequenciesPerOutcome) let expected = FrequencyDistribution(xFrequenciesPerOutcome) let x = z.divide(y) expect(x) == expected } func test_power_shouldReturnMultiplicativeIdentityFor0() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 6:1.0] let expected = FrequencyDistribution<Int>.multiplicativeIdentity let x = FrequencyDistribution(frequenciesPerOutcome) let freqDist = x.power(0) expect(freqDist) == expected } func test_power_shouldReturnSelfFor1() { let frequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 6:1.0] let x = FrequencyDistribution(frequenciesPerOutcome) let expected = x let freqDist = x.power(1) expect(freqDist) == expected } func test_power_shouldReturnCorrectlyForGreaterThan1() { // TODO: SwiftCheck let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 6:1.0] let power = 5 let x = FrequencyDistribution(xFrequenciesPerOutcome) let expected = (1..<power).reduce(x) { (acc, _) in acc.multiply(x) } let z = x.power(power) expect(z) == expected } // TODO: Test negative powers (when we know what that means) func todo_test_power_shouldReturnCorrectlyForLessThan0() { } func test_powerMultiply() { let xFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 6:1.0] let yFrequenciesPerOutcome: FrequencyDistribution.FrequenciesPerOutcome = [2:2.0, 3:2.0, 7:1.0] let x = FrequencyDistribution(xFrequenciesPerOutcome) let y = FrequencyDistribution(yFrequenciesPerOutcome) let expected = xFrequenciesPerOutcome.reduce(FrequencyDistribution<Int>.additiveIdentity) { let (outcome, frequency) = $1 let addend = y.power(outcome).normalizeFrequencies().scaleFrequencies(frequency) return $0.add(addend) } let z = x.power(y) expect(z) == expected } }
apache-2.0
8f8f73df9ac60b263467ea64a4570a88
34.95186
139
0.625076
4.408371
false
true
false
false
Rapid-SDK/ios
Source/Networking/RapidSocketManager.swift
1
28475
// // SocketManager.swift // Rapid // // Created by Jan Schwarz on 16/03/2017. // Copyright © 2017 Rapid. All rights reserved. // import Foundation /// Class for websocket communication management class RapidSocketManager { typealias Event = RapidSerializable & RapidClientMessage typealias Request = RapidClientRequest & Event /// Network communication handler let networkHandler: RapidNetworkHandler weak var cacheHandler: RapidCacheHandler? /// Optional timeout for timeoutable requests var timeout: TimeInterval? /// State of a websocket connection internal var state: RapidConnectionState = .disconnected internal(set) var auth: RapidAuthorization? /// Dedicated threads internal let websocketQueue: OperationQueue internal let parseQueue: OperationQueue internal let mainQueue = DispatchQueue.main /// Queue of events that are about to be sent to the server internal var eventQueue: [Event] = [] /// Dictionary of events that have been already sent to the server and a response is awaited. Events are identified by an event ID. internal var pendingRequests: [String: (request: Request, timestamp: TimeInterval)] = [:] /// Dictionary of registered subscriptions. Either active or those that are waiting for acknowledgement from the server. Subscriptions are identified by a subscriptioon hash internal var activeSubscriptions: [String: RapidSubscriptionManager] = [:] internal var pendingFetches: [String: RapidFetchInstance] = [:] internal var pendingExecutionRequests: [String: RapidExecution] = [:] internal var pendingTimeRequests: [RapidTimeOffset] = [] internal var onConnectActions: [String: RapidOnConnectAction] = [:] internal var onDisconnectActions: [String: RapidOnDisconnectAction] = [:] /// Timer that limits maximum time without any websocket communication to reveal disconnections internal var nopTimer: Timer? init(networkHandler: RapidNetworkHandler) { self.websocketQueue = OperationQueue() self.websocketQueue.name = "RapidWebsocketQueue-\(networkHandler.socketURL.lastPathComponent)" self.websocketQueue.maxConcurrentOperationCount = 1 self.websocketQueue.underlyingQueue = DispatchQueue(label: "RapidWebsocketQueue-\(networkHandler.socketURL.lastPathComponent)", attributes: []) self.parseQueue = OperationQueue() self.parseQueue.name = "RapidParseQueue-\(networkHandler.socketURL.lastPathComponent)" self.parseQueue.maxConcurrentOperationCount = 1 self.parseQueue.underlyingQueue = DispatchQueue(label: "RapidParseQueue-\(networkHandler.socketURL.lastPathComponent)", attributes: []) self.networkHandler = networkHandler self.networkHandler.delegate = self self.networkHandler.goOnline() self.state = .connecting } deinit { sendDisconnectionRequest() } func authorize(authRequest: RapidAuthRequest) { websocketQueue.async { [weak self] in self?.auth = authRequest.auth self?.post(event: authRequest) } } func deauthorize(deauthRequest: RapidDeauthRequest) { websocketQueue.async { [weak self] in self?.auth = nil self?.post(event: deauthRequest) } } /// Reconnect previously configured websocket func goOnline() { websocketQueue.async { [weak self] in self?.networkHandler.goOnline() if let state = self?.state, state != .connected { self?.state = .connecting } } } /// Disconnect existing websocket func goOffline() { websocketQueue.async { [weak self] in self?.networkHandler.goOffline() self?.state = .disconnected } } /// Send mutation event /// /// - Parameter mutationRequest: Mutation object func mutate<T: RapidMutationRequest>(mutationRequest: T) { mutationRequest.register(delegate: self) websocketQueue.async { [weak self] in self?.post(event: mutationRequest) } } func publish(publishRequest: RapidChannelPublish) { websocketQueue.async { [weak self] in self?.post(event: publishRequest) } } func execute<T: RapidExecution>(execution: T) { websocketQueue.async { [weak self] in self?.pendingExecutionRequests[execution.identifier] = execution self?.fetch(execution.fetchRequest) } } func fetch(_ fetch: RapidFetchInstance) { websocketQueue.async { [weak self] in self?.pendingFetches[fetch.fetchID] = fetch self?.post(event: fetch) } } func requestTimestamp(_ request: RapidTimeOffset) { websocketQueue.async { [weak self] in self?.pendingTimeRequests.append(request) self?.post(event: request) } } func registerOnConnectAction(_ action: RapidOnConnectAction) { let actionID = Rapid.uniqueID action.register(actionID: actionID, delegate: self) websocketQueue.async { [weak self] in self?.onConnectActions[actionID] = action if self?.state == .connected { self?.post(event: action) } } } func registerOnDisconnectAction(_ action: RapidOnDisconnectAction) { let actionID = Rapid.uniqueID action.register(actionID: actionID, delegate: self) websocketQueue.async { [weak self] in self?.onDisconnectActions[actionID] = action self?.post(event: action) } } /// Send register collection subscription event /// /// - Parameter subscription: Subscription object func subscribe(toCollection subscription: RapidColSubInstance) { subscription.registerUnsubscribeHandler { [weak self] (subscription) in self?.websocketQueue.async { self?.unsubscribe(subscription) } } websocketQueue.async { [weak self] in // If a subscription that listens to the same set of data has been already registered just register the new listener locally if let activeSubscription = self?.activeSubscription(withHash: subscription.subscriptionHash) as? RapidColSubManager { activeSubscription.registerSubscription(subscription: subscription) } else { // Create an unique ID that identifies the subscription let subscriptionID = Rapid.uniqueID // Create a handler for the subscription let subscriptionHandler = RapidColSubManager(withSubscriptionID: subscriptionID, subscription: subscription, delegate: self) // Add handler to the dictionary of registered subscriptions self?.activeSubscriptions[subscriptionID] = subscriptionHandler self?.post(event: subscriptionHandler) } } } /// Send register channel subscription event /// /// - Parameter subscription: Subscription object func subscribe(toChannel subscription: RapidChanSubInstance) { subscription.registerUnsubscribeHandler { [weak self] (subscription) in self?.websocketQueue.async { self?.unsubscribe(subscription) } } websocketQueue.async { [weak self] in // If a subscription that listens to the same set of data has been already registered just register the new listener locally if let activeSubscription = self?.activeSubscription(withHash: subscription.subscriptionHash) as? RapidChanSubManager { activeSubscription.registerSubscription(subscription: subscription) } else { // Create an unique ID that identifies the subscription let subscriptionID = Rapid.uniqueID // Create a handler for the subscription let subscriptionHandler = RapidChanSubManager(withSubscriptionID: subscriptionID, subscription: subscription, delegate: self) // Add handler to the dictionary of registered subscriptions self?.activeSubscriptions[subscriptionID] = subscriptionHandler self?.post(event: subscriptionHandler) } } } /// Remove all subscriptions func unsubscribeAll() { websocketQueue.async { [weak self] in for (_, subscription) in self?.activeSubscriptions ?? [:] { let handler = RapidUnsubscriptionManager(subscription: subscription) self?.unsubscribe(handler) } } } /// Get a subscription handler if exists /// /// Every subscription is identified by a hash. Subscriptions that listens to the same set of data have equal hashes. /// /// - Parameter hash: Subscription hash /// - Returns: Subscription handler that takes care about subscriptions with specified hash func activeSubscription(withHash hash: String) -> RapidSubscriptionManager? { for (_, subscription) in activeSubscriptions where subscription.subscriptionHash == hash { return subscription } return nil } /// Get an event ID for a request that has been sent to the server /// /// - Parameter request: Request that has been sent to the server /// - Returns: Event ID of the request func eventID(forPendingRequest request: RapidClientRequest) -> String? { let pendingTuples = pendingRequests.filter({ $0.value.request === request }) return pendingTuples.first?.key } } // MARK: internal methods internal extension RapidSocketManager { func handleDidConnect() { for (_, action) in onConnectActions { post(event: action) } } /// Handle a situation when socket was unintentionally disconnected func handleDidDisconnect(withError error: RapidError?) { RapidLogger.developerLog(message: "Did disconnect with error \(String(describing: error))") // Get all relevant events that were about to be sent let currentQueue = eventQueue.filter({ // Do not include requests that are relevant to one physical websocket connection return $0.shouldSendOnReconnect }) // Get all relevant requests that had been sent, but they were still waiting for an acknowledgement let pendingArray = (Array(pendingRequests.values) as [(request: Request, timestamp: TimeInterval)]).filter({ // Do not include requests that are relevant to one physical websocket connection return $0.request.shouldSendOnReconnect }) let sortedPendingArray = pendingArray.sorted(by: { $0.timestamp < $1.timestamp }).map({ $0.request }) as [Event] eventQueue.removeAll(keepingCapacity: true) pendingRequests.removeAll() // Resubscribe all subscriptions let resubscribe = activeSubscriptions.map({ $0.value }) for handler in resubscribe { eventQueue.append(handler) } // Re-register all on-disconnect actions let reregister = onDisconnectActions.map({ $0.value }) as [Event] eventQueue.append(contentsOf: reregister) // Then append requests that had been sent, but they were still waiting for an acknowledgement eventQueue.append(contentsOf: sortedPendingArray) // Finally append events that were waiting to be sent eventQueue.append(contentsOf: currentQueue) // Create new connection networkHandler.goOnline() state = .connecting } } // MARK: Socket communication methods internal extension RapidSocketManager { /// Create abstract connection /// /// When socket is connected physically, the client still needs to identify itself by its connection ID. /// This creates an abstract connection which is not dependent on a physical one func sendConnectionRequest() { let authorization: RapidAuthRequest? let connection = RapidConnectionRequest(connectionID: Rapid.uniqueID, delegate: self) // Client needs to reauthorize when creating a new connection if let token = self.auth?.token { authorization = RapidAuthRequest(token: token) } else { authorization = nil } post(event: connection, prioritize: true) if let authorization = authorization, !eventQueue.contains(where: { authorization.auth.token == ($0 as? RapidAuthRequest)?.auth.token }) { post(event: authorization, prioritize: true) } } /// Destroy abstract connection /// /// Inform the server that it no longer needs to keep an abstract connection with the client func sendDisconnectionRequest() { networkHandler.write(event: RapidDisconnectionRequest(), withID: Rapid.uniqueID) } /// Acknowledge a server event /// /// - Parameter eventID: Event ID of the event to be acknowledged func acknowledge(eventWithID eventID: String) { let acknowledgement = RapidClientAcknowledgement(eventID: eventID) post(event: acknowledgement) } /// Unregister subscription /// /// When a subscription has no handler assigned yet (because of async calls) the unsubscription process is handled by this method /// /// - Parameter subscription: Subscription instance func unsubscribe(_ subscription: RapidSubscriptionInstance) { if activeSubscription(withHash: subscription.subscriptionHash) != nil { subscription.unsubscribe() } } /// Unregister subscription /// /// - Parameter handler: Unsubscription handler func unsubscribe(_ handler: RapidUnsubscriptionManager) { RapidLogger.log(message: "Unsubscribe \(handler.subscription.subscriptionHash)", level: .info) activeSubscriptions[handler.subscription.subscriptionID] = nil // If the subscription is still in queue just remove it // Otherwise, send usubscription request if let subscriptionIndex = eventQueue.flatMap({ $0 as? RapidSubscriptionManager }).index(where: { $0.subscriptionID == handler.subscription.subscriptionID }) { eventQueue.remove(at: subscriptionIndex) } else { post(event: handler) } } func cancel(request: Request) { let index = eventQueue.index(where: { if let queuedRequest = $0 as? RapidClientRequest { return request === queuedRequest } return false }) if let index = index { eventQueue.remove(at: index) } let pending = pendingRequests.filter({ return $0.value.request === request }) if let (eventID, _) = pending.first { pendingRequests[eventID] = nil } request.eventFailed(withError: RapidErrorInstance(eventID: Rapid.uniqueID, error: .cancelled)) } /// Enque a event to the queue /// /// - Parameter serializableRequest: Request to be queued func post(event: Event, prioritize: Bool = false) { // Inform a timoutable request that it should start a timeout count down // User events can be timeouted only if user sets `Rapid.timeout` // System events work always with timeout and they use either a custom `Rapid.timeout` if set or a default `Rapid.defaultTimeout` if let timeoutRequest = event as? RapidTimeoutRequest, let timeout = timeout { timeoutRequest.requestSent(withTimeout: timeout, delegate: self) } else if let timeoutRequest = event as? RapidTimeoutRequest, timeoutRequest.alwaysTimeout { timeoutRequest.requestSent(withTimeout: Rapid.defaultTimeout, delegate: self) } if prioritize && !eventQueue.isEmpty { var index = 0 let requestPriority = (event as? RapidPriorityRequest)?.priority ?? .low while index < eventQueue.count && ((eventQueue[index] as? RapidPriorityRequest)?.priority.rawValue ?? Int.max) <= requestPriority.rawValue { index += 1 } eventQueue.insert(event, at: index) } else { eventQueue.append(event) } flushQueue() } /// SenD all requests in the queue func flushQueue() { // Check connection state guard state == .connected else { return } let queueCopy = eventQueue // Empty the queue eventQueue.removeAll() for event in queueCopy { // Generate unique event ID let eventID = Rapid.uniqueID if let request = event as? Request { registerPendingRequest(request, withID: eventID) } networkHandler.write(event: event, withID: eventID) } // Restart heartbeat timer rescheduleHeartbeatTimer() } /// Add request among pending requests which wait for an acknowledgement from server /// /// - Parameters: /// - request: Sent request /// - eventID: Event ID associated with the request func registerPendingRequest(_ request: Request, withID eventID: String) { pendingRequests[eventID] = (request, Date().timeIntervalSince1970) } /// Handle an event sent from the server /// /// - Parameter response: Event sent from the server func handle(message: RapidServerMessage) { switch message { // Event failed case let message as RapidErrorInstance: let tuple = pendingRequests[message.eventID] tuple?.request.eventFailed(withError: message) // If subscription registration failed remove if from the list of active subscriptions if let subscription = tuple?.request as? RapidSubscriptionManager { activeSubscriptions[subscription.subscriptionID] = nil } // If fetch failed remove it from the list of pending fetches else if let fetch = tuple?.request as? RapidFetchInstance { pendingFetches[fetch.fetchID] = nil } // If time request failed remove it from the list of pending time requests else if tuple?.request is RapidTimeOffset && pendingTimeRequests.count > 0 { pendingTimeRequests.removeFirst() } // If on disconnect action failed remove it from the list of pending disconnect actions else if let action = tuple?.request as? RapidOnDisconnectAction, let actionID = action.actionID { onDisconnectActions[actionID] = nil } // If on connect action failed because of permission denied remove it from the list of pending connect actions else if let action = tuple?.request as? RapidOnConnectAction, let actionID = action.actionID, case .permissionDenied = message.error { onDisconnectActions[actionID] = nil } else if let request = tuple?.request as? RapidAuthRequest, self.auth?.token == request.auth.token { self.auth = nil } pendingRequests[message.eventID] = nil // Event acknowledged case let message as RapidServerAcknowledgement: let tuple = pendingRequests[message.eventID] tuple?.request.eventAcknowledged(message) pendingRequests[message.eventID] = nil // Subscription event case let message as RapidSubscriptionBatch: if let subscription = activeSubscriptions[message.subscriptionID] as? RapidColSubManager { subscription.receivedSubscriptionEvent(message) } // Subscription cancel case let message as RapidSubscriptionCancelled: let subscription = activeSubscriptions[message.subscriptionID] let eventID = message.eventIDsToAcknowledge.first ?? Rapid.uniqueID let error = RapidErrorInstance(eventID: eventID, error: .permissionDenied(message: "No longer authorized to read data")) subscription?.eventFailed(withError: error) activeSubscriptions[message.subscriptionID] = nil // On-disconnect action cancelled case let message as RapidOnDisconnectActionCancelled: let action = onDisconnectActions[message.actionID] let eventID = message.eventIDsToAcknowledge.first ?? Rapid.uniqueID let error = RapidErrorInstance(eventID: eventID, error: .permissionDenied(message: "No longer authorized to write data")) action?.eventFailed(withError: error) onDisconnectActions[message.actionID] = nil // Fetch response case let message as RapidFetchResponse: let fetch = pendingFetches[message.fetchID] fetch?.receivedData(message.documents) pendingFetches[message.fetchID] = nil // Channel message case let message as RapidChannelMessage: if let subscription = activeSubscriptions[message.subscriptionID] as? RapidChanSubManager { subscription.receivedMessage(message) } // Server timestamp case let message as RapidServerTimestamp: if pendingTimeRequests.count > 0 { let request = pendingTimeRequests.removeFirst() request.receivedTimestamp(message) } default: RapidLogger.developerLog(message: "Unrecognized response") } if let event = message as? RapidServerEvent { for eventID in event.eventIDsToAcknowledge { acknowledge(eventWithID: eventID) } } } } // MARK: Subscription handler delegate extension RapidSocketManager: RapidSubscriptionManagerDelegate { func unsubscribe(handler: RapidUnsubscriptionManager) { websocketQueue.async { [weak self] in self?.unsubscribe(handler) } } } // MARK: Mutation request delegate extension RapidSocketManager: RapidMutationRequestDelegate { func cancelMutationRequest<T>(_ request: T) where T : RapidMutationRequest { websocketQueue.async { [weak self] in self?.cancel(request: request) } } } // MARK: On-connect action delegate extension RapidSocketManager: RapidOnConnectActionDelegate { func cancelOnConnectAction(withActionID actionID: String) { websocketQueue.async { [weak self] in if let action = self?.onConnectActions[actionID] { self?.onConnectActions[actionID] = nil self?.cancel(request: action) } } } } // MARK: On-disconnect action delegate extension RapidSocketManager: RapidOnDisconnectActionDelegate { func cancelOnDisconnectAction(withActionID actionID: String) { websocketQueue.async { [weak self] in if let action = self?.onDisconnectActions[actionID] { self?.onDisconnectActions[actionID] = nil self?.cancel(request: action) self?.post(event: action.cancelRequest()) } } } } // MARK: Heartbeat extension RapidSocketManager { /// Send empty request to test the connection func sendEmptyRequest() { websocketQueue.async { [weak self] in let request = RapidEmptyRequest() self?.post(event: request) } } /// Invalidate previous heartbeat timer and start a new one func rescheduleHeartbeatTimer() { mainQueue.async { [weak self] in self?.nopTimer?.invalidate() self?.nopTimer = Timer.scheduledTimer(timeInterval: Rapid.heartbeatInterval, userInfo: nil, repeats: false, block: { [weak self] _ in self?.sendEmptyRequest() }) } } } // MARK: Connection request delegate extension RapidSocketManager: RapidConnectionRequestDelegate { /// Connection request was acknowledged /// /// - Parameter request: Connection request that was acknowledged func connectionEstablished(_ request: RapidConnectionRequest) { RapidLogger.log(message: "Rapid connected", level: .info) } /// Connection request failed /// /// - Parameters: /// - request: Connection request that failed /// - error: Reason of failure func connectingFailed(_ request: RapidConnectionRequest, error: RapidErrorInstance) { RapidLogger.log(message: "Rapid connection failed", level: .info) websocketQueue.async { [weak self] in self?.networkHandler.restartSocket(afterError: error.error) } } } // MARK: Timout request delegate extension RapidSocketManager: RapidTimeoutRequestDelegate { /// Request timeout /// /// - Parameter request: Request that timeouted func requestTimeout(_ request: RapidTimeoutRequest) { RapidLogger.developerLog(message: "Request timeout \(request)") websocketQueue.async { [weak self] in // If the request is pending complete it with timeout error // Otherwise, if the request is still in the queue move it to pending requests and complete it with timeout error if let eventID = self?.eventID(forPendingRequest: request) { let error = RapidErrorInstance(eventID: eventID, error: .timeout) self?.handle(message: error) } else if let index = self?.eventQueue.flatMap({ $0 as? Request }).index(where: { request === $0 }), let request = request as? Request { self?.eventQueue.remove(at: index) let eventID = Rapid.uniqueID self?.registerPendingRequest(request, withID: eventID) let error = RapidErrorInstance(eventID: eventID, error: .timeout) self?.handle(message: error) } } } } // MARK: Concurrency optimistic mutation delegate extension RapidSocketManager: RapidExectuionDelegate { func executionCompleted(_ execution: RapidExecution) { websocketQueue.async { [weak self] in self?.pendingExecutionRequests[execution.identifier] = nil } } func sendMutationRequest<T: RapidMutationRequest>(_ request: T) { mutate(mutationRequest: request) } func sendFetchRequest(_ request: RapidFetchInstance) { fetch(request) } } // MARK: Network manager delegate extension RapidSocketManager: RapidNetworkHandlerDelegate { func socketDidConnect() { websocketQueue.async { [weak self] in self?.sendConnectionRequest() self?.state = .connected self?.handleDidConnect() self?.flushQueue() } } func socketDidDisconnect(withError error: RapidError?) { websocketQueue.async { [weak self] in self?.state = .disconnected self?.handleDidDisconnect(withError: error) } } func handlerDidReceive(message: RapidServerMessage) { websocketQueue.async { [weak self] in // Restart heartbeat timer self?.rescheduleHeartbeatTimer() self?.handle(message: message) } } }
mit
a6e9bd35668f13f0fd510200e8c07c18
36.31848
177
0.625097
5.377526
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/InstagramAPI/Instagram/Models/InstagramLike.swift
2
358
// // InstagramLike.swift // ConceptOffice // // Created by Denis on 03.04.16. // Copyright © 2016 Den Ree. All rights reserved. // import ObjectMapper struct InstagramLike: AnyInstagramModel { // MARK: - Properties var id: String = "" var username: String = "" var firstName: String = "" var lastName: String = "" var type: String = "" }
mit
9e2fd04fd5f8335715bbad129d802a1c
18.833333
50
0.652661
3.5
false
false
false
false
pkrll/ComicZipper-2
ComicZipper/Views/DropView.swift
2
3607
// // DropView.swift // ComicZipper // // Created by Ardalan Samimi on 31/12/15. // Copyright © 2015 Ardalan Samimi. All rights reserved. // import Cocoa class DropView: NSView { internal weak var delegate: DropViewDelegate? internal var dragMode: Bool { return self.delegate?.inDragMode(self) ?? true } private var highlighted: Bool { get { return self.delegate?.isHighlighted(self) ?? false } set { self.delegate?.dropView(self, shouldHighlight: newValue) } } private var numberOfValidItemsForDrop: Int = 0 private var droppedItems: [DropItem] = [] /** * Checks if the user has dropped any valid items. * - Returns: True, if the dropped items array contains objects. */ private var hasDroppedItems: Bool { return self.droppedItems.count > 0 } override func awakeFromNib() { self.registerForDraggedTypes([NSFilenamesPboardType]) } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { // Abort drag operation if the view should not be in drop mode (in compression mode no objects should be added). if self.dragMode == false { return NSDragOperation.None } // Turn on the highlight if self.highlighted == false { self.highlighted = true } sender.enumerateDraggingItemsWithOptions( .ClearNonenumeratedImages, forView: self, classes: [DropItem.self], searchOptions: [:]) { (draggingItem: NSDraggingItem, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in let item = draggingItem.item as! DropItem // Files already in the list should not be included in drag operation if self.delegate?.dropView(self, isItemInList: item.itemPath) == false { self.droppedItems.append(item) self.numberOfValidItemsForDrop += 1 } else { draggingItem.imageComponentsProvider = nil } } // Inform the sender of the number of valid items to drop, so that the drop manager can update the badge count. sender.numberOfValidItemsForDrop = self.numberOfValidItemsForDrop if self.numberOfValidItemsForDrop > 0 { return NSDragOperation.Copy } self.highlighted = false return NSDragOperation.None } override func draggingExited(sender: NSDraggingInfo?) { if self.highlighted { self.highlighted = false } // Cleanup must be done on draggingExited(_:) so as to empty the array. Otherwise the droppedItems array will just keep growing. self.resetProperties() } override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool { sender.animatesToDestination = false return true } override func performDragOperation(sender: NSDraggingInfo) -> Bool { if self.highlighted { self.highlighted = false } // The drop view delegate will take over the items, making it safe for resetting the droppedItems array in the resetProperties() method. if self.hasDroppedItems { self.delegate?.dropView(self, didReceiveFiles: self.droppedItems) } return true } override func concludeDragOperation(sender: NSDraggingInfo?) { self.resetProperties() } } // MARK: - Private Methods private extension DropView { /** * Clean up after a drag operation has concluced. * * Invoked once drag operation has finished, releasing any unecessary objects and resetting the number of valid items for drop count. * */ func resetProperties() { self.droppedItems.removeAll() self.numberOfValidItemsForDrop = 0 } }
mit
5ac0dd7ace827b46d68ddc44a3ee90e6
28.809917
140
0.684969
4.501873
false
false
false
false
ipagong/PGVerticalOpenTransition
Pod/Classes/VerticalOpenTransition.swift
1
27475
// // VerticalOpenTransition.swift // PGTransitionExample // // Created by ipagong on 2017. 3. 22.. // Copyright © 2017년 ipagong. All rights reserved. // import UIKit import ObjectiveC public typealias VerticalOpenVoidBlock = (Bool) -> () @objc public protocol VerticalOpenTransitionDelegate : NSObjectProtocol { @objc optional func canPresentWith(transition:VerticalOpenTransition) -> Bool @objc optional func canDismissWith(transition:VerticalOpenTransition) -> Bool @objc optional func startPresentProcessWith(transition:VerticalOpenTransition, targetView:UIView?) -> Double @objc optional func startDismissProcessWith(transition:VerticalOpenTransition, targetView:UIView?) -> Double @objc optional func lockPresentWith(transition:VerticalOpenTransition, distance:CGFloat, velocity:CGPoint, state:UIGestureRecognizerState) -> Bool @objc optional func lockDismissWith(transition:VerticalOpenTransition, distance:CGFloat, velocity:CGPoint, state:UIGestureRecognizerState) -> Bool @objc optional func initialCenterViewWith(transition:VerticalOpenTransition) -> UIView! @objc optional func destinationCnterViewWith(transition:VerticalOpenTransition) -> UIView! @objc optional func customAnimationSetupWith(transition:VerticalOpenTransition, type:VerticalOpenTransition.TransitionType, time:VerticalOpenTransition.AnimationTime, from:UIView, to:UIView) @objc optional func verticalTransition(_ transition:VerticalOpenTransition, gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool } @objc public class VerticalOpenTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { public var raiseViews:Array<UIView>? { didSet { updateMaxDistance() } } public var lowerViews:Array<UIView>? { didSet { updateMaxDistance() } } public private(set) var contentView:UIView? public var enablePresent:Bool = true public var enableDismiss:Bool = true public var presentDuration:TimeInterval = 0.3 public var dismissDuration:TimeInterval = 0.3 public var onCenterContent:Bool = false public var onCenterFade:Bool = true public var dismissTouchHeight:CGFloat = 200.0 public weak var openDelegate:VerticalOpenTransitionDelegate? public weak var target:UIViewController! public weak var presenting:UIViewController? { willSet { guard self.isPresented == false else { return } guard self.presenting?.view.gestureRecognizers?.contains(self.dismissGesture) == true else { return } self.presenting?.view.removeGestureRecognizer(self.dismissGesture) } didSet { guard self.isPresented == false else { self.presenting = oldValue return } self.presenting?.view.addGestureRecognizer(self.dismissGesture) } } private var current:UIViewController? private var hasInteraction:Bool = false private var didActionStart:Bool = false private var didLocked:Bool? { willSet { if newValue == true && didLocked == false { self.cancel() } } } private var beganPanPoint:CGPoint = .zero private var openPresentationStyle:UIModalPresentationStyle { return .custom } private var presentBlock:VerticalOpenVoidBlock? private var dismissBlock:VerticalOpenVoidBlock? private var canPresent:Bool { guard ((raiseViews?.count ?? 0) + (lowerViews?.count ?? 0)) > 0 else { return false } return self.openDelegate?.canPresentWith?(transition: self) ?? true } private var canDismiss:Bool { return self.openDelegate?.canDismissWith?(transition: self) ?? true } private var maxDistance:CGFloat = 0 private var initialCenterView:UIView? { return self.openDelegate?.initialCenterViewWith?(transition: self) } private var initialCenterViewFrame:CGRect? private var initialCenterViewBounds:CGRect? private var destinationCenterView:UIView? { return self.openDelegate?.destinationCnterViewWith?(transition: self) } private var destinationCenterViewFrame:CGRect? private var destinationCenterViewBounds:CGRect? private var raiseSnapshots:Array<VerticalOpenSnapshotView>? private var lowerSnapshots:Array<VerticalOpenSnapshotView>? private var initialCenterSnapshot:VerticalOpenSnapshotView? private var destinationCenterSnapshot:VerticalOpenSnapshotView? private var onCenterContentMode:Bool { guard self.onCenterContent == true else { return false } guard let _ = self.initialCenterView else { return false } guard let _ = self.destinationCenterView else { return false } return true } private var onCenterFadeMode:Bool { guard onCenterContentMode == true else { return false } return onCenterFade } @objc override init() { super.init() } @objc public init(target:UIViewController!) { super.init() self.target = target target.view.addGestureRecognizer(self.presentGesture) self.current = target } @objc public init(target:UIViewController!, presenting:UIViewController!) { super.init() self.target = target target.view.addGestureRecognizer(self.presentGesture) self.presenting = presenting presenting.view.addGestureRecognizer(self.dismissGesture) self.current = target } lazy public var presentGesture:UIPanGestureRecognizer = { let gesutre = UIPanGestureRecognizer(target: self, action: #selector(onPresentWith(gesture:))) gesutre.delegate = self return gesutre }() lazy public var dismissGesture:UIPanGestureRecognizer = { let gesutre = UIPanGestureRecognizer(target: self, action: #selector(onDismissWith(gesture:))) gesutre.delegate = self return gesutre }() private var isPresented:Bool { return current != target } private func updateMaxDistance() { guard let window = target.view.window else { return } maxDistance = 0 raiseViews?.forEach { $0.maxOpenDistance = $0.convert(CGPoint(x:0, y:$0.frame.height), to: window).y if maxDistance < $0.maxOpenDistance { maxDistance = $0.maxOpenDistance } } lowerViews?.forEach { $0.maxOpenDistance = window.frame.height - $0.convert(CGPoint.zero, to: window).y if maxDistance < $0.maxOpenDistance { maxDistance = $0.maxOpenDistance } } } public func onPresentWith(gesture:UIPanGestureRecognizer) { guard let _ = self.presenting else { return } guard canPresent == true else { return } guard enablePresent == true else { return } guard isPresented == false else { return } guard let window = target.view.window else { return } let location = gesture.location(in: window) let velocity = gesture.velocity(in: window) didLocked = self.openDelegate?.lockPresentWith?(transition: self, distance: location.y - self.beganPanPoint.y, velocity: velocity, state: gesture.state) if gesture.state != .began && didLocked == true { return } switch gesture.state { case .began: if maxDistance == 0 { updateMaxDistance() } self.beganPanPoint = location self.didLocked = nil self.hasInteraction = true updateSnapshots() case .changed: let percentage = ((location.y - self.beganPanPoint.y) / maxDistance) if (percentage > 0) { self.presentOpenAction() } self.update(percentage) case .ended: guard self.hasInteraction == true else { return } if (self.didLocked == true) { self.cancel() } else if (velocity.y > 0) { self.finish() } else { self.cancel() } self.hasInteraction = false self.beganPanPoint = .zero default: break } } public func onDismissWith(gesture:UIPanGestureRecognizer) { guard let _ = presenting else { return } guard canDismiss == true else { return } guard enableDismiss == true else { return } guard isPresented == true else { return } guard let window = presenting!.view.window else { return } let location = gesture.location(in: window) let velocity = gesture.velocity(in: window) didLocked = self.openDelegate?.lockDismissWith?(transition: self, distance: self.beganPanPoint.y - location.y, velocity: velocity, state: gesture.state) if gesture.state != .began && didLocked == true { return } switch gesture.state { case .began: guard location.y > (window.frame.height - self.dismissTouchHeight) else { self.beganPanPoint = .zero return } self.hasInteraction = true self.beganPanPoint = location self.didLocked = nil updateSnapshots() case .changed: guard self.beganPanPoint.equalTo(.zero) == false else { return } let percentage = (self.beganPanPoint.y - location.y) / maxDistance if (percentage > 0) { self.dismissAction() } self.update(percentage) case .ended: guard self.beganPanPoint.equalTo(.zero) == false else { return } guard hasInteraction == true else { return } if (self.didLocked == true) { self.cancel() } else if (velocity.y < 0) { self.finish() } else { self.cancel() } self.hasInteraction = false self.beganPanPoint = .zero default: break } } private func presentAnimation(from:UIViewController, to:UIViewController, container:UIView, context: UIViewControllerContextTransitioning) { container.addSubview(to.view) to.view.setNeedsLayout() to.view.layoutIfNeeded() if maxDistance == 0 { updateMaxDistance() } if (self.onCenterFadeMode == true) { self.initialCenterSnapshot?.addOpenTransitionAt(to.view, contentMode: .scaleAspectFill) } if self.onCenterContentMode == true { self.destinationCenterView!.frame = self.initialCenterViewFrame! self.destinationCenterView!.bounds = self.initialCenterViewBounds! } self.lowerSnapshots?.forEach({ $0.addOpenTransitionAt(to.view) }) self.raiseSnapshots?.forEach({ $0.addOpenTransitionAt(to.view) }) self.raiseViews?.forEach { $0.alpha = 0 } self.lowerViews?.forEach { $0.alpha = 0 } self.initialCenterView?.alpha = 0 self.openDelegate?.customAnimationSetupWith?(transition: self, type: .present, time: .previous, from: from.view, to: to.view) UIView.animateKeyframes(withDuration: self.transitionDuration(using: context), delay: 0, options: [], animations: { if (self.onCenterFadeMode == true) { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: { self.initialCenterSnapshot!.alpha = 0 }) } self.raiseSnapshots?.forEach { self.presentTransform(view: $0, viewTransform: { $0.transform = CGAffineTransform(translationX: 0, y: -$0.maxOpenDistance) }) } self.lowerSnapshots?.forEach { self.presentTransform(view: $0, viewTransform: { $0.transform = CGAffineTransform(translationX: 0, y: $0.maxOpenDistance) }) } if (self.onCenterFadeMode == true) { self.initialCenterSnapshot!.frame = self.destinationCenterViewFrame! } if self.onCenterContentMode == true { self.destinationCenterView!.bounds = self.destinationCenterViewBounds! self.destinationCenterView!.frame = self.destinationCenterViewFrame! } self.initialCenterSnapshot?.alpha = 0 self.openDelegate?.customAnimationSetupWith?(transition: self, type: .present, time: .animated, from: from.view, to: to.view) }, completion: { _ in let canceled = context.transitionWasCancelled self.openDelegate?.customAnimationSetupWith?(transition: self, type: .present, time: canceled ? .canceled : .completed, from: from.view, to: to.view) self.raiseViews?.forEach { $0.alpha = 1 } self.lowerViews?.forEach { $0.alpha = 1 } self.initialCenterView?.alpha = 1 if self.onCenterContentMode == true { self.destinationCenterView!.bounds = self.destinationCenterViewBounds! self.destinationCenterView!.frame = self.destinationCenterViewFrame! } to.modalPresentationStyle = self.openPresentationStyle self.initialCenterSnapshot?.removeFromSuperview() self.destinationCenterSnapshot?.removeFromSuperview() self.raiseSnapshots?.forEach { $0.removeFromSuperview() } self.lowerSnapshots?.forEach { $0.removeFromSuperview() } if canceled == true { self.current = self.target context.completeTransition(false) } else { self.current = self.presenting context.completeTransition(true) } self.presentBlock?(!canceled) self.didActionStart = false }) } private func dismissAnimation(from:UIViewController, to:UIViewController, container:UIView, context: UIViewControllerContextTransitioning) { to.view.setNeedsLayout() to.view.layoutIfNeeded() self.destinationCenterSnapshot?.addOpenTransitionAt(from.view) self.initialCenterSnapshot?.addOpenTransitionAt(from.view, contentMode: .scaleAspectFill) self.lowerSnapshots?.forEach{ $0.addOpenTransitionAt(from.view) $0.transform = CGAffineTransform(translationX: 0, y: $0.maxOpenDistance) } self.raiseSnapshots?.forEach{ $0.addOpenTransitionAt(from.view) $0.transform = CGAffineTransform(translationX: 0, y: -$0.maxOpenDistance) } if self.onCenterContentMode == true { initialCenterSnapshot!.frame = destinationCenterView!.frame initialCenterSnapshot?.alpha = 0 } self.raiseViews?.forEach { $0.alpha = 0 } self.lowerViews?.forEach { $0.alpha = 0 } self.destinationCenterView?.alpha = 0 self.openDelegate?.customAnimationSetupWith?(transition: self, type: .dismiss, time: .previous, from: from.view, to: to.view) UIView.animateKeyframes(withDuration: self.transitionDuration(using: context), delay: 0, options: [], animations: { if (self.onCenterFadeMode == true) { UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 1, animations: { self.initialCenterSnapshot?.alpha = 1 }) } self.raiseSnapshots?.forEach { self.dismissTransform(view: $0, viewTransform: { $0.transform = CGAffineTransform(translationX: 0, y: 0) }) } self.lowerSnapshots?.forEach { self.dismissTransform(view: $0, viewTransform: { $0.transform = CGAffineTransform(translationX: 0, y: 0) }) } if self.onCenterContentMode == true { self.initialCenterSnapshot!.frame = self.initialCenterView!.frame self.destinationCenterSnapshot!.frame = self.initialCenterView!.frame self.destinationCenterSnapshot!.bounds = self.initialCenterView!.frame self.destinationCenterSnapshot!.bounds.origin = CGPoint(x: self.destinationCenterView!.bounds.width/2 - self.initialCenterView!.frame.width/2, y: self.destinationCenterView!.bounds.height/2 - self.initialCenterView!.frame.height/2) } self.openDelegate?.customAnimationSetupWith?(transition: self, type: .dismiss, time: .animated, from: from.view, to: to.view) }, completion: { _ in let canceled = context.transitionWasCancelled self.openDelegate?.customAnimationSetupWith?(transition: self, type: .dismiss, time: canceled ? .canceled : .completed, from: from.view, to: to.view) self.raiseViews?.forEach { $0.alpha = 1 } self.lowerViews?.forEach { $0.alpha = 1 } self.destinationCenterView?.alpha = 1 self.raiseSnapshots?.forEach { $0.removeFromSuperview() } self.lowerSnapshots?.forEach { $0.removeFromSuperview() } self.destinationCenterSnapshot?.removeFromSuperview() self.initialCenterSnapshot?.removeFromSuperview() to.modalPresentationStyle = self.openPresentationStyle if canceled == true { self.current = self.presenting context.completeTransition(false) } else { self.current = self.target context.completeTransition(true) } self.dismissBlock?(!canceled) self.didActionStart = false }) } private func presentOpenAction() { guard let _ = presenting else { return } guard canPresent == true else { return } guard enablePresent == true else { return } guard percentComplete == 0 else { return } guard didActionStart == false else { return } self.didActionStart = true presenting!.modalPresentationStyle = self.openPresentationStyle presenting!.transitioningDelegate = self self.target.present(presenting!, animated: true, completion: nil) } private func dismissAction() { guard canDismiss == true else { return } guard enableDismiss == true else { return } guard percentComplete == 0 else { return } guard didActionStart == false else { return } self.didActionStart = true presenting!.dismiss(animated: true, completion: nil) } override public func finish() { guard didActionStart else { return } super.finish() } override public func cancel() { guard didActionStart else { return } super.cancel() } override public func update(_ percentComplete: CGFloat) { guard percentComplete > 0 else { return } guard percentComplete < 1 else { return } super.update(percentComplete) } private func presentTransform(view:VerticalOpenSnapshotView, viewTransform:@escaping (UIView) -> (Void)) { let startTime = self.openDelegate?.startPresentProcessWith?(transition: self, targetView: view.targetView ) ?? 0.0 UIView.addKeyframe(withRelativeStartTime: startTime, relativeDuration: 1, animations: { viewTransform(view) }) } private func dismissTransform(view:VerticalOpenSnapshotView, viewTransform:@escaping (UIView) -> (Void)) { let startTime = self.openDelegate?.startDismissProcessWith?(transition: self, targetView: view.targetView) ?? 0.0 UIView.addKeyframe(withRelativeStartTime: startTime, relativeDuration: 1, animations: { viewTransform(view) }) } private func createTransitionSnapshot(_ targetView:UIView?, afterScreenUpdates update:Bool? = false) -> VerticalOpenSnapshotView? { guard let _ = targetView else { return nil } guard let snapshot = VerticalOpenSnapshotView.createWith(targetView!, afterScreenUpdates: update) else { return nil } snapshot.maxOpenDistance = targetView!.maxOpenDistance return snapshot } private func updateSnapshots() { destinationCenterSnapshot = self.createTransitionSnapshot(self.destinationCenterView) destinationCenterViewFrame = self.destinationCenterView?.frame destinationCenterViewBounds = self.destinationCenterView?.bounds initialCenterSnapshot = self.createTransitionSnapshot(self.initialCenterView) initialCenterViewFrame = self.initialCenterView?.frame initialCenterViewBounds = self.initialCenterView?.bounds lowerSnapshots = self.lowerViews?.flatMap({ self.createTransitionSnapshot($0) }) raiseSnapshots = self.raiseViews?.flatMap({ self.createTransitionSnapshot($0) }) } //MARK: - UIVieControllerTransitioningDelegate methods public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return (self.hasInteraction == true ? self : nil) } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return (self.hasInteraction == true ? self : nil) } //MARK: - UIViewControllerAnimatedTransitioning methods public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return isPresented ? dismissDuration : presentDuration } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVc = transitionContext.viewController(forKey: .from) else { return } guard let toVc = transitionContext.viewController(forKey: .to) else { return } if (toVc === self.presenting) { self.presentAnimation(from: fromVc, to: toVc, container: transitionContext.containerView, context: transitionContext) } else { self.dismissAnimation(from: fromVc, to: toVc, container: transitionContext.containerView, context: transitionContext) } } //MARK: - public methods @objc public func presentVerticalOpenViewController() { self.presentVerticalOpenViewController(animated: true, completion: nil) } @objc public func presentVerticalOpenViewController(animated:Bool) { self.presentVerticalOpenViewController(animated: animated, completion: nil) } @objc public func presentVerticalOpenViewController(animated:Bool, completion:VerticalOpenVoidBlock?) { guard let _ = self.presenting else { return } guard canPresent == true else { return } guard enablePresent == true else { return } guard isPresented == false else { return } guard percentComplete == 0 else { return } updateSnapshots() presenting!.modalPresentationStyle = self.openPresentationStyle presenting!.transitioningDelegate = self self.target.present(presenting!, animated: animated) { completion?(true) } } @objc public func dismissVerticalOpenViewController() { self.dismissVerticalOpenViewController(animated: true, completion: nil) } @objc public func dismissVerticalOpenViewController(animated:Bool) { self.dismissVerticalOpenViewController(animated: animated, completion: nil) } @objc public func dismissVerticalOpenViewController(animated:Bool, completion:VerticalOpenVoidBlock?) { guard let _ = self.presenting else { return } guard canDismiss == true else { return } guard enableDismiss == true else { return } guard isPresented == true else { return } guard percentComplete == 0 else { return } updateSnapshots() presenting!.modalPresentationStyle = self.openPresentationStyle presenting!.transitioningDelegate = self presenting!.dismiss(animated: animated) { completion?(true) } } @objc public func setPresentCompletion(block:VerticalOpenVoidBlock?) { self.presentBlock = block } @objc public func setDismissCompletion(block:VerticalOpenVoidBlock?) { self.dismissBlock = block } } extension VerticalOpenTransition : UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard let view = gestureRecognizer.view else { return false } if let enable = self.openDelegate?.verticalTransition?(self, gestureRecognizer: gestureRecognizer, shouldReceive: touch) { return enable } guard gestureRecognizer == self.dismissGesture else { return true } if (touch.location(in: view).y < (view.frame.height - self.dismissTouchHeight)) { return false } return true } } private var maxOpenDistanceAssociatedKey: UInt8 = 0 extension UIView { public var maxOpenDistance:CGFloat { get { return objc_getAssociatedObject(self, &maxOpenDistanceAssociatedKey) as? CGFloat ?? 0 } set(newValue) { objc_setAssociatedObject(self, &maxOpenDistanceAssociatedKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } extension VerticalOpenTransition { @objc public enum TransitionType : NSInteger { case present case dismiss } @objc public enum AnimationTime : NSInteger { case previous case animated case completed case canceled } }
mit
7c6a8878ea5eafa4f98a95c2bc5408d5
38.528058
179
0.624672
5.259812
false
false
false
false
MAARK/Charts
Source/Charts/Highlight/HorizontalBarHighlighter.swift
8
2115
// // HorizontalBarHighlighter.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 @objc(HorizontalBarChartHighlighter) open class HorizontalBarHighlighter: BarHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { guard let barData = self.chart?.data as? BarChartData else { return nil } let pos = getValsForTouch(x: y, y: x) guard let high = getHighlight(xValue: Double(pos.y), x: y, y: x) else { return nil } if let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet, set.isStacked { return getStackedHighlight(high: high, set: set, xValue: Double(pos.y), yValue: Double(pos.x)) } return high } internal override func buildHighlights( dataSet set: IChartDataSet, dataSetIndex: Int, xValue: Double, rounding: ChartDataSetRounding) -> [Highlight] { guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return [] } var entries = set.entriesForXValue(xValue) if entries.count == 0, let closest = set.entryForXValue(xValue, closestToY: .nan, rounding: rounding) { // Try to find closest x-value and take all entries for that x-value entries = set.entriesForXValue(closest.x) } return entries.map { e in let px = chart.getTransformer(forAxis: set.axisDependency) .pixelForValues(x: e.y, y: e.x) return Highlight(x: e.x, y: e.y, xPx: px.x, yPx: px.y, dataSetIndex: dataSetIndex, axis: set.axisDependency) } } internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return abs(y1 - y2) } }
apache-2.0
f83e274d2670582ac2b6ddc826c3b6af
32.571429
120
0.602837
4.424686
false
false
false
false
clrung/DCMetroWidget
DCMetroWidget/TodayViewController.swift
1
1801
// // TodayViewController.swift // DC Metro // // Created by Christopher Rung on 9/3/16. // Copyright © 2016 Christopher Rung. All rights reserved. // import Foundation import Cocoa class TodayViewController: NSViewController { @IBOutlet var mainViewController: MainViewController! @IBOutlet var settingsViewController: SettingsViewController! override func viewDidLoad() { super.viewDidLoad() mainViewController.view.translatesAutoresizingMaskIntoConstraints = false settingsViewController.view.translatesAutoresizingMaskIntoConstraints = false self.view.translatesAutoresizingMaskIntoConstraints = false switchFromViewController(nil, toViewController: mainViewController) } // MARK: Editing var widgetAllowsEditing: Bool { return true } func widgetDidBeginEditing() { switchFromViewController(mainViewController, toViewController: settingsViewController) } func widgetDidEndEditing() { switchFromViewController(settingsViewController, toViewController: mainViewController) } func switchFromViewController(_ fromViewController: NSViewController?, toViewController: NSViewController?) { if fromViewController != nil { fromViewController?.removeFromParentViewController() fromViewController?.view.removeFromSuperview() } if toViewController != nil { self.addChildViewController(toViewController!) let view = toViewController!.view self.view.addSubview(view) let views: [String:AnyObject] = ["view" : view] self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: views)) } self.view.layoutSubtreeIfNeeded() } }
mit
3e76813ef2f14d59bda17bd2aba65fed
30.034483
132
0.777778
4.972376
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Schedule/Filter/ScheduleFilterViewModel.swift
1
6383
// // Copyright (c) 2017 Google 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. // import Foundation public struct ScheduleFilterViewModel { private enum Constants { static let topicsTitle = NSLocalizedString("Topics", comment: "Title of schedule filter header item for topics.") static let levelsTitle = NSLocalizedString("Levels", comment: "Title of schedule filter header item for levels.") static let typesTitle = NSLocalizedString("Event Types", comment: "Title of schedule filter header item for event types.") static let tagKey = "tag" static let levelKey = "level" static let typeKey = "type" } var filterSections = [ScheduleFilterSectionViewModel]() var filterSectionsByType = [String: ScheduleFilterSectionViewModel]() var filterString: String? { // Build a string to display the selected filters. var filters = [String]() filters.append(contentsOf: selectedTags) filters.append(contentsOf: selectedTypes) filters.append(contentsOf: selectedLevels) return filters.count > 0 ? filters.joined(separator: ", ") : nil } var selectedTags: [String] { guard let tagsSection = filterSectionsByType[Constants.tagKey] else { return [] } let selectedTags = tagsSection.items.filter { tag -> Bool in return tag.selected } return selectedTags.map { tag in return tag.name } } var selectedTypes: [String] { guard let tagsSection = filterSectionsByType[Constants.typeKey] else { return [] } let selectedTags = tagsSection.items.filter { tag -> Bool in return tag.selected } return selectedTags.map { tag in return tag.name } } var selectedLevels: [String] { guard let tagsSection = filterSectionsByType[Constants.levelKey] else { return [] } let selectedTags = tagsSection.items.filter { tag -> Bool in return tag.selected } return selectedTags.map { tag in return tag.name } } init() { // Types section. let typeTags = EventTag.allTypes let typeItems: [ScheduleFilterItemViewModel] = typeTags.map { typeTag in return ScheduleFilterItemViewModel(name: typeTag.name, color: typeTag.colorString, orderInCategory: typeTag.orderInCategory) }.sorted(by: { (type1, type2) -> Bool in return type1.orderInCategory ?? 0 < type2.orderInCategory ?? 0 }) let typesFilterSection = ScheduleFilterSectionViewModel(name: Constants.typesTitle, items: typeItems) filterSectionsByType[Constants.typeKey] = typesFilterSection filterSections.append(typesFilterSection) // Levels section. let levelTags = EventTag.allLevels let levelItems: [ScheduleFilterItemViewModel] = levelTags.map { levelTag in return ScheduleFilterItemViewModel(name: levelTag.name, color: levelTag.colorString, orderInCategory: levelTag.orderInCategory) }.sorted(by: { (level1, level2) -> Bool in return level1.orderInCategory ?? 0 < level2.orderInCategory ?? 0 }) let levelsFilterSection = ScheduleFilterSectionViewModel(name: Constants.levelsTitle, items: levelItems) filterSectionsByType[Constants.levelKey] = levelsFilterSection filterSections.append(levelsFilterSection) // Topics section. let trackTags = EventTag.allTopics let topicItems: [ScheduleFilterItemViewModel] = trackTags.map { trackTag in return ScheduleFilterItemViewModel(name: trackTag.name, color: trackTag.colorString) }.sorted(by: { (topic1, topic2) -> Bool in return topic1.name < topic2.name }) let tagsFilterSection = ScheduleFilterSectionViewModel(name: Constants.topicsTitle, items: topicItems) filterSectionsByType[Constants.tagKey] = tagsFilterSection filterSections.append(tagsFilterSection) } func shouldShow(topics: [EventTag], levels: [EventTag], types: [EventTag]) -> Bool { // If we passed the live stream/session filters, each section is an AND if any items are selected. // Within a section the items match with OR. let topicsMatch = tagsMatch(selectedTags: selectedTags, eventTags: topics.map { tag in return tag.name }) let levelsMatch = tagsMatch(selectedTags: selectedLevels, eventTags: levels.map { tag in return tag.name }) let typesMatch = tagsMatch(selectedTags: selectedTypes, eventTags: types.map { tag in return tag.name }) return topicsMatch && levelsMatch && typesMatch } func tagsMatch(selectedTags: [String], eventTags: [String]) -> Bool { if selectedTags.isEmpty { return true } return eventTags.reduce(false, {(sum, tag) in return sum || selectedTags.contains(tag) }) } func reset() { for section in filterSections { for item in section.items { item.selected = false } } } var isEmpty: Bool { for section in filterSections { for item in section.items where item.selected { return false } } return true } } class ScheduleFilterSectionViewModel { let name: String? let items: [ScheduleFilterItemViewModel] init(name: String?, items: [ScheduleFilterItemViewModel]) { self.name = name self.items = items } } class ScheduleFilterItemViewModel { let name: String var selected: Bool var color: String? var orderInCategory: Int? init(name: String, color: String?, orderInCategory: Int? = nil) { self.name = name self.color = color self.orderInCategory = orderInCategory selected = false } }
apache-2.0
0f0cf14a7719895e9e0cc2e62b365e7a
34.859551
108
0.663951
4.441893
false
false
false
false
ceicke/HomeControl
HomeControl/Loxone.swift
1
1857
// // Loxone.swift // HomeControl // // Created by Christoph Eicke on 25.11.15. // Copyright © 2015 Christoph Eicke. All rights reserved. // import Foundation class Loxone { func tellLoxone(actor:NSString, uuid:NSString, onOff:NSString, scene:NSString = "", dimmValue:Int = -1) { let loxoneLocalIP:NSString = NSUserDefaults.standardUserDefaults().valueForKey("serverUrl") as! NSString let username:NSString = NSUserDefaults.standardUserDefaults().valueForKey("username") as! NSString let password:NSString = NSUserDefaults.standardUserDefaults().valueForKey("password") as! NSString var url:NSURL = NSURL(string: "")! if scene == "" { if dimmValue == -1 { url = NSURL(string: "http://\(username):\(password)@\(loxoneLocalIP)/dev/sps/io/\(uuid)/\(onOff)")! } else { url = NSURL(string: "http://\(username):\(password)@\(loxoneLocalIP)/dev/sps/io/\(uuid)/\(dimmValue)")! } } else { if dimmValue == -1 { url = NSURL(string: "http://\(username):\(password)@\(loxoneLocalIP)/dev/sps/io/\(uuid)/\(scene)/\(onOff)")! } else { url = NSURL(string: "http://\(username):\(password)@\(loxoneLocalIP)/dev/sps/io/\(uuid)/\(scene)/\(dimmValue)")! } } print(url) if url != "" { let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode != 200 { NSLog("ERROR \(httpResponse.statusCode)") } } } task.resume() } } }
mit
7dab3f363577402be71562b065d9c183
35.411765
128
0.532328
4.537897
false
false
false
false
ipraba/Bean
Example/Bean/Constants.swift
1
728
// // Constants.swift // Bean // // Created by Prabaharan Elangovan on 20/12/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Foundation import UIKit struct FlickrConstants { static let apiKey = "9492ad2565e147c97138efcedf5d4d6a" static let apiSecret = "ef85ad4b9712e87f" } struct Colors { static let EmeraldColor = UIColor(red: (46/255), green: (204/255), blue: (113/255), alpha: 1.0) static let SunflowerColor = UIColor(red: (241/255), green: (196/255), blue: (15/255), alpha: 1.0) static let PumpkinColor = UIColor(red: (211/255), green: (84/255), blue: (0/255), alpha: 1.0) static let PomegranateColor = UIColor(red: (192/255), green: (57/255), blue: (43/255), alpha: 1.0) }
mit
687a25f5211a499054633fb98e0628fe
30.652174
102
0.678129
2.817829
false
false
false
false
xwu/swift
test/Concurrency/Runtime/async_task_locals_spawn_let.swift
1
2391
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.5, *) enum TL { @TaskLocal static var number: Int = 0 } @available(SwiftStdlib 5.5, *) @discardableResult func printTaskLocal<V>( _ key: TaskLocal<V>, _ expected: V? = nil, file: String = #file, line: UInt = #line ) -> V? { let value = key.get() print("\(key) (\(value)) at \(file):\(line)") if let expected = expected { assert("\(expected)" == "\(value)", "Expected [\(expected)] but found: \(value), at \(file):\(line)") } return expected } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.5, *) func async_let_nested() async { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) async let x1: () = TL.$number.withValue(2) { async let x2 = printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) @Sendable func test() async { printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) async let x31 = printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) _ = await x31 } async let x3: () = test() _ = await x2 await x3 } _ = await x1 printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (0) } @available(SwiftStdlib 5.5, *) func async_let_nested_skip_optimization() async { async let x1: Int? = TL.$number.withValue(2) { async let x2: Int? = { () async -> Int? in async let x3: Int? = { () async -> Int? in async let x4: Int? = { () async -> Int? in async let x5: Int? = { () async -> Int? in assert(TL.$number.get() == 2) async let xx = printTaskLocal(TL.$number) // CHECK: TaskLocal<Int>(defaultValue: 0) (2) return await xx }() return await x5 }() return await x4 }() return await x3 }() return await x2 } _ = await x1 } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await async_let_nested() await async_let_nested_skip_optimization() } }
apache-2.0
e41038930cd42f2785e6fc0b6cd95eca
26.802326
130
0.583438
3.600904
false
false
false
false
pmlbrito/WeatherExercise
WeatherExercise/Presentation/City/CityLocationDetailViewController.swift
1
2667
// // CityLocationDetailViewController.swift // WeatherExercise // // Created by Pedro Brito on 12/05/2017. // Copyright © 2017 BringGlobal. All rights reserved. // import UIKit protocol CityLocationDetailProtocol: BaseViewControllerProtocol { func setupLocation(location: LocationModel) func renderLocationWeather(weather: TodayWeatherModel) } class CityLocationDetailViewController: UIViewController, CityLocationDetailProtocol { var selectedLocation: LocationModel? var presenter: CityLocationDetailPresenter? @IBOutlet weak var locationNameLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var tempMinLabel: UILabel! @IBOutlet weak var tempCurrLabel: UILabel! @IBOutlet weak var tempMaxLabel: UILabel! @IBOutlet weak var windSpeedLabel: UILabel! @IBOutlet weak var windDirectionLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var rainLabel: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.setupView() self.loadWeather() } func setupView() { self.presenter = CityLocationDetailPresenter() self.presenter?.bindView(view: self) } //MARK: Private Helpers fileprivate func loadWeather(){ if self.selectedLocation != nil { self.presenter?.loadWeather(location: self.selectedLocation!) } } } extension CityLocationDetailViewController { func setupLocation(location: LocationModel) { self.selectedLocation = location } func renderLocationWeather(weather: TodayWeatherModel) { self.locationNameLabel.text = weather.location?.locationName self.statusLabel.text = String(format:"%@ - %@", weather.mainStatus != nil ? weather.mainStatus! : "", weather.mainDescription != nil ? weather.mainDescription! : "") self.tempMinLabel.text = weather.temp_min != nil ? "\(weather.temp_min!)" : "n/a" self.tempCurrLabel.text = weather.temp != nil ? "\(weather.temp!)" : "n/a" self.tempMaxLabel.text = weather.temp_max != nil ? "\(weather.temp_max!)" : "n/a" self.windSpeedLabel.text = weather.wind_speed != nil ? "\(weather.wind_speed!)" : "n/a" self.windDirectionLabel.text = weather.wind_direction != nil ? "\(weather.wind_direction!)" : "n/a" self.humidityLabel.text = weather.humidity != nil ? "\(weather.humidity!)" : "n/a" self.rainLabel.text = weather.rain != nil ? "\(weather.rain!)" : "n/a" } }
mit
e1cd801c3c2a30691e1d5708d32c5ed3
34.078947
174
0.666917
4.356209
false
false
false
false
ahoppen/swift
test/IRGen/abitypes.swift
8
49145
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir -enable-objc-interop | %FileCheck -check-prefix=%target-cpu-%target-os-abi %s // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux, windows, openbsd import gadget import Foundation @objc protocol P1 {} @objc protocol P2 {} @objc protocol Work { func doStuff(_ x: Int64) } // armv7s-ios: [[ARMV7S_MYRECT:%.*]] = type { float, float, float, float } // arm64-ios: [[ARM64_MYRECT:%.*]] = type { float, float, float, float } // arm64e-ios: [[ARM64E_MYRECT:%.*]] = type { float, float, float, float } // arm64-tvos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float } // armv7k-watchos: [[ARMV7K_MYRECT:%.*]] = type { float, float, float, float } // arm64_32-watchos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float } // arm64-macosx: [[ARM64_MYRECT:%.*]] = type { float, float, float, float } class Foo { // x86_64-macosx: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-macosx: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // x86_64-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-ios: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // i386-ios: define hidden swiftcc void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // i386-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2) {{[#0-9]*}} { // armv7-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // armv7-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2) {{[#0-9]*}} { // armv7s-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // armv7s-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2) {{[#0-9]*}} { // arm64-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // arm64-ios: define hidden [[ARM64_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // x86_64-tvos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-tvos: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // arm64-tvos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // arm64-tvos: define hidden [[ARM64_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // i386-watchos: define hidden swiftcc void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // i386-watchos: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2) {{[#0-9]*}} { // armv7k-watchos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // armv7k-watchos: define hidden [[ARMV7K_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // armv64_32-watchos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // armv64_32-watchos: define hidden [[ARMV7K_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { // x86_64-watchos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-watchos: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { @objc dynamic func bar() -> MyRect { return MyRect(x: 1, y: 2, width: 3, height: 4) } // x86_64-macosx: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // x86_64-macosx: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, %TSo6CGRectV* byval({{.*}}) align 8 %2) {{[#0-9]*}} { // armv7-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7-ios: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} { // armv7s-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7s-ios: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} { // armv7k-watchos: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7k-watchos: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x float] %2) {{[#0-9]*}} { @objc dynamic func getXFromNSRect(_ r: NSRect) -> Double { return Double(r.origin.x) } // x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // x86_64-macosx: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, <2 x float> %2, <2 x float> %3) {{[#0-9]*}} { // armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7-ios: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} { // armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7s-ios: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} { // armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // armv7k-watchos: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x float] %2) {{[#0-9]*}} { // arm64_32-watchos: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { // arm64_32-watchos: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x float] %2) {{[#0-9]*}} { @objc dynamic func getXFromRect(_ r: MyRect) -> Float { return r.x } // Call from Swift entrypoint with exploded Rect to @objc entrypoint // with unexploded ABI-coerced type. // x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{.*}}"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} { // x86_64-macosx: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 8 // x86_64-macosx: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 8 // x86_64-macosx: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to { <2 x float>, <2 x float> }* // x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0 // x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]] // x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1 // x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]] // x86_64-macosx: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8* // x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, <2 x float>, <2 x float>)*)(i8* [[SELFCAST]], i8* [[SEL]], <2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]]) // armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} { // armv7-ios: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4 // armv7-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]* // armv7-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]] // armv7-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8* // armv7-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]]) // armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} { // armv7s-ios: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7s-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7s-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4 // armv7s-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]* // armv7s-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]] // armv7s-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8* // armv7s-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]]) // armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} { // armv7k-watchos: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7k-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // armv7k-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4 // armv7k-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]* // armv7k-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]] // armv7k-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8* // armv7k-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]]) // arm64_32-watchos: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} { // arm64_32-watchos: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // arm64_32-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4 // arm64_32-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4 // arm64_32-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]* // arm64_32-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]] // arm64_32-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8* // arm64_32-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]]) func getXFromRectSwift(_ r: MyRect) -> Float { return getXFromRect(r) } // Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments // x86_64-macosx: define hidden float @"$s8abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, float %2, float %3, float %4, float %5, float %6, float %7, float %8, %TSo6MyRectV* byval({{.*}}) align 8 %9) {{[#0-9]*}} { @objc dynamic func getXFromRectIndirectByVal(_: Float, second _: Float, third _: Float, fourth _: Float, fifth _: Float, sixth _: Float, seventh _: Float, withRect r: MyRect) -> Float { return r.x } // Make sure the caller-side from Swift also uses indirect-byval for the argument // x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC25getXFromRectIndirectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} { func getXFromRectIndirectSwift(_ r: MyRect) -> Float { let f : Float = 1.0 // x86_64-macosx: alloca // x86_64-macosx: alloca // x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 8 // x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval({{.*}}) align 8 [[TEMP]]) // x86_64-macosx: ret float [[RESULT]] return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r); } // x86_64 returns an HA of four floats directly in two <2 x float> // x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: load i8*, i8** @"\01L_selector(newRect)", align 8 // x86_64-macosx: [[RESULT:%.*]] = call { <2 x float>, <2 x float> } bitcast (void ()* @objc_msgSend // x86_64-macosx: store { <2 x float>, <2 x float> } [[RESULT]] // x86_64-macosx: [[CAST:%.*]] = bitcast { <2 x float>, <2 x float> }* // x86_64-macosx: load { float, float, float, float }, { float, float, float, float }* [[CAST]] // x86_64-macosx: ret float // // armv7 returns an HA of four floats indirectly // armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4 // armv7-ios: load i8*, i8** @"\01L_selector(newRect)", align 4 // armv7-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret({{.*}}) %call.aggresult // armv7-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1 // armv7-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0 // armv7-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4 // armv7-ios: ret float [[RETVAL]] // // armv7s returns an HA of four floats indirectly // armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7s-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4 // armv7s-ios: load i8*, i8** @"\01L_selector(newRect)", align 4 // armv7s-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret({{.*}}) %call.aggresult // armv7s-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1 // armv7s-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0 // armv7s-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4 // armv7s-ios: ret float [[RETVAL]] // // armv7k returns an HA of four floats directly // armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7k-watchos: load i8*, i8** @"\01L_selector(newRect)", align 4 // armv7k-watchos: [[RESULT:%.*]] = call [[ARMV7K_MYRECT]] bitcast (void ()* @objc_msgSend // armv7k-watchos: store [[ARMV7K_MYRECT]] [[RESULT]] // armv7k-watchos: [[CAST:%.*]] = bitcast [[ARMV7K_MYRECT]]* // armv7k-watchos: load { float, float, float, float }, { float, float, float, float }* [[CAST]] // armv7k-watchos: ret float func barc(_ p: StructReturns) -> Float { return p.newRect().y } // x86_64-macosx: define hidden swiftcc { double, double, double } @"$s8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-macosx: define hidden void @"$s8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}FTo"(%TSo4TrioV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2) {{[#0-9]*}} { @objc dynamic func baz() -> Trio { return Trio(i: 1.0, j: 2.0, k: 3.0) } // x86_64-macosx: define hidden swiftcc double @"$s8abitypes3FooC4bazc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: load i8*, i8** @"\01L_selector(newTrio)", align 8 // x86_64-macosx: [[CAST:%[0-9]+]] = bitcast {{%.*}}* %0 // x86_64-macosx: call void bitcast (void ()* @objc_msgSend_stret to void (%TSo4TrioV*, [[OPAQUE:.*]]*, i8*)*) func bazc(_ p: StructReturns) -> Double { return p.newTrio().j } // x86_64-macosx: define hidden swiftcc i64 @"$s8abitypes3FooC7getpair{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: [[RESULT:%.*]] = call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*) // x86_64-macosx: [[GEP1:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0 // x86_64-macosx: store i64 [[RESULT]], i64* [[GEP1]] // x86_64-macosx: [[GEP2:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0 // x86_64-macosx: load i64, i64* [[GEP2]] // x86_64-macosx: ret i64 func getpair(_ p: StructReturns) -> IntPair { return p.newPair() } // x86_64-macosx: define hidden i64 @"$s8abitypes3FooC8takepair{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i64 %2) {{[#0-9]*}} { @objc dynamic func takepair(_ p: IntPair) -> IntPair { return p } // x86_64-macosx: define hidden swiftcc i64 @"$s8abitypes3FooC9getnested{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*) // x86_64-macosx: bitcast // x86_64-macosx: call void @llvm.lifetime.start // x86_64-macosx: store i32 {{.*}} // x86_64-macosx: store i32 {{.*}} // x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { i64 }, { i64 } // x86_64-macosx: load i64, i64* [[T0]], align 8 // x86_64-macosx: bitcast // x86_64-macosx: call void @llvm.lifetime.end // x86_64-macosx: ret i64 func getnested(_ p: StructReturns) -> NestedInts { return p.newNestedInts() } // x86_64-macosx: define hidden i8* @"$s8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} { // x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]]* @"$s8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[T0:%.*]] = call [[OBJC:%objc_class]]* @swift_getObjCClassFromMetadata([[TYPE]]* [[VALUE]]) // x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T0]] to i8* // x86_64-macosx: ret i8* [[RESULT]] @objc dynamic func copyClass(_ a: AnyClass) -> AnyClass { return a } // x86_64-macosx: define hidden i8* @"$s8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} { // x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$s8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8* // x86_64-macosx: ret i8* [[RESULT]] @objc dynamic func copyProto(_ a: AnyObject) -> AnyObject { return a } // x86_64-macosx: define hidden i8* @"$s8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} { // x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$s8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8* // x86_64-macosx: ret i8* [[RESULT]] @objc dynamic func copyProtoComp(_ a: P1 & P2) -> P1 & P2 { return a } // x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: define hidden signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) {{[#0-9]*}} { // x86_64-macosx: [[R1:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[R2:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[R3:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]] // x86_64-macosx: ret i8 [[R3]] // // x86_64-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* %1) {{.*}} { // x86_64-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // x86_64-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2) // x86_64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // x86_64-ios-fixme: [[R3:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]) // x86_64-ios-fixme: ret i1 [[R3]] // // armv7-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* %1) {{.*}} { // armv7-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) {{[#0-9]*}} { // armv7-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF" // armv7-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // armv7-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]] // armv7-ios-fixme: ret i8 [[R3]] // // armv7s-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // armv7s-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) {{[#0-9]*}} { // armv7s-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF" // armv7s-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // armv7s-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]] // armv7s-ios-fixme: ret i8 [[R3]] // // arm64-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // arm64-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // arm64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F" // arm64-ios-fixme: ret i1 [[R2]] // // arm64e-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // arm64e-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // arm64e-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F" // arm64e-ios-fixme: ret i1 [[R2]] // // i386-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // i386-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) {{[#0-9]*}} { // i386-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // i386-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // i386-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]] // i386-ios-fixme: ret i8 [[R3]] // // x86_64-tvos-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // x86_64-tvos-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // x86_64-tvos-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2) // x86_64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // x86_64-tvos-fixme: [[R3:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]) // x86_64-tvos-fixme: ret i1 [[R3]] // // arm64-tvos-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} { // arm64-tvos-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // arm64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F" // arm64-tvos-fixme: ret i1 [[R2]] // i386-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) // i386-watchos: define hidden zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo" // i386-watchos: [[R1:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBoolySbAA0cD0VF"(i1 %2) // i386-watchos: [[R2:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]] // i386-watchos: [[R3:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBoolyAA0eF0VSbF"(i1 [[R2]]) // i386-watchos: ret i1 [[R3]] @objc dynamic func negate(_ b: Bool) -> Bool { return !b } // x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0) // x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8 // x86_64-macosx: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]]) // x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]]) // x86_64-macosx: ret i1 [[TOBOOL]] // // x86_64-macosx: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) // x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // x86_64-macosx: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]] // x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // x86_64-macosx: ret i8 [[TOOBJCBOOL]] // // x86_64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8 // x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // x86_64-ios: ret i1 [[NEG]] // // x86_64-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // x86_64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // x86_64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // x86_64-ios: ret i1 [[TOOBJCBOOL]] // // armv7-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0) // armv7-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4 // armv7-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]]) // armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]]) // armv7-ios: ret i1 [[TOBOOL]] // // armv7-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) // armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // armv7-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]] // armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // armv7-ios: ret i8 [[TOOBJCBOOL]] // // armv7s-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0) // armv7s-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4 // armv7s-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]]) // armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]]) // armv7s-ios: ret i1 [[TOBOOL]] // // armv7s-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) // armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // armv7s-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]] // armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // armv7s-ios: ret i8 [[TOOBJCBOOL]] // // arm64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // arm64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8 // arm64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // arm64-ios: ret i1 [[NEG]] // // arm64-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // arm64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // arm64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // arm64-ios: ret i1 [[TOOBJCBOOL]] // // arm64e-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // arm64e-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // arm64e-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // arm64e-ios: ret i1 [[TOOBJCBOOL]] // // i386-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0) // i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4 // i386-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]]) // i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]]) // i386-ios: ret i1 [[TOBOOL]] // // i386-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) // i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F" // i386-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]] // i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // i386-ios: ret i8 [[TOOBJCBOOL]] // // x86_64-tvos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8 // x86_64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // x86_64-tvos: ret i1 [[NEG]] // // x86_64-tvos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // x86_64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // x86_64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // x86_64-tvos: ret i1 [[TOOBJCBOOL]] // // arm64-tvos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // arm64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8 // arm64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // arm64-tvos: ret i1 [[NEG]] // // arm64-tvos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // arm64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // arm64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // arm64-tvos: ret i1 [[TOOBJCBOOL]] // i386-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // i386-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4 // i386-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // i386-watchos: ret i1 [[NEG]] // // i386-watchos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // i386-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // i386-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // i386-watchos: ret i1 [[TOOBJCBOOL]] // // armv7k-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // armv7k-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4 // armv7k-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0) // armv7k-watchos: ret i1 [[NEG]] // // armv7k-watchos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // armv7k-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // armv7k-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // armv7k-watchos: ret i1 [[TOOBJCBOOL]] // // arm64-macosx: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2) // arm64-macosx: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 // arm64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]]) // arm64-macosx: ret i1 [[TOOBJCBOOL]] @objc dynamic func negate2(_ b: Bool) -> Bool { var g = Gadget() return g.negate(b) } // x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8 // x86_64-macosx: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0) // x86_64-macosx: ret i1 [[NEG]] // x86_64-macosx: } // x86_64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8 // x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0) // x86_64-ios: ret i1 [[NEG]] // x86_64-ios: } // i386-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} { // i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 4 // i386-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0) // i386-ios: ret i1 [[NEG]] // i386-ios: } @objc dynamic func negate3(_ b: Bool) -> Bool { var g = Gadget() return g.invert(b) } // x86_64-macosx: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture swifterror dereferenceable(8) %2) {{.*}} { // x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8 // x86_64-macosx: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}}) // x86_64-macosx: } // x86_64-ios: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture swifterror dereferenceable(8) %2) {{.*}} { // x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8 // x86_64-ios: call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext {{%[0-9]+}}, %2** {{%[0-9]+}}) // x86_64-ios: } // i386-ios: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture dereferenceable(4) %2) {{.*}} { // i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 4 // i386-ios: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}}) // i386-ios: } @objc dynamic func throwsTest(_ b: Bool) throws { var g = Gadget() try g.negateThrowing(b) } // x86_64-macosx: define hidden i32* @"$s8abitypes3FooC24copyUnsafeMutablePointer{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i32* %2) {{[#0-9]*}} { @objc dynamic func copyUnsafeMutablePointer(_ p: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Int32> { return p } // x86_64-macosx: define hidden i64 @"$s8abitypes3FooC17returnNSEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { @objc dynamic func returnNSEnumValue() -> ByteCountFormatter.CountStyle { return .file } // x86_64-macosx: define hidden zeroext i16 @"$s8abitypes3FooC20returnOtherEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i16 zeroext %2) {{[#0-9]*}} { @objc dynamic func returnOtherEnumValue(_ choice: ChooseTo) -> ChooseTo { switch choice { case .takeIt: return .leaveIt case .leaveIt: return .takeIt } } // x86_64-macosx: define hidden swiftcc i32 @"$s8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} { // x86_64-macosx: define hidden i32 @"$s8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} { @objc dynamic func getRawEnum() -> RawEnum { return Intergalactic } var work : Work init (work: Work) { self.work = work } // x86_64-macosx: define hidden void @"$s8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} { @objc dynamic func testArchetype(_ work: Work) { work.doStuff(1) // x86_64-macosx: [[OBJCPTR:%.*]] = bitcast i8* %2 to %objc_object* // x86_64-macosx: call swiftcc void @"$s8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}F"(%objc_object* [[OBJCPTR]], %T8abitypes3FooC* swiftself %{{.*}}) } @objc dynamic func foo(_ x: @convention(block) (Int) -> Int) -> Int { // FIXME: calling blocks is currently unimplemented // return x(5) return 1 } // x86_64-macosx: define hidden swiftcc void @"$s8abitypes3FooC20testGenericTypeParam{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T, %T8abitypes3FooC* swiftself %1) {{.*}} { func testGenericTypeParam<T: Pasta>(_ x: T) { // x86_64-macosx: [[CAST:%.*]] = bitcast %objc_object* %0 to i8* // x86_64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[CAST]], i8* %{{.*}}) x.alDente() } // arm64-ios: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} { // arm64-ios: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{[#0-9]*}} { // // arm64e-ios: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} { // arm64e-ios: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{.*}} { // // arm64-tvos: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} { // arm64-tvos: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{[#0-9]*}} { // arm64-macosx: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} { // arm64-macosx: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret({{.*}}) %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{.*}} { @objc dynamic func callJustReturn(_ r: StructReturns, with v: BigStruct) -> BigStruct { return r.justReturn(v) } // Test that the makeOne() that we generate somewhere below doesn't // use arm_aapcscc for armv7. func callInline() -> Float { return makeOne(3,5).second } } // armv7-ios: define internal void @makeOne(%struct.One* noalias sret({{.*}}) align 4 %agg.result, float %f, float %s) // armv7s-ios: define internal void @makeOne(%struct.One* noalias sret({{.*}}) align 4 %agg.result, float %f, float %s) // armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s) // rdar://17631440 - Expand direct arguments that are coerced to aggregates. // x86_64-macosx: define{{( protected)?}} swiftcc float @"$s8abitypes13testInlineAggySfSo6MyRectVF"(float %0, float %1, float %2, float %3) {{.*}} { // x86_64-macosx: [[COERCED:%.*]] = alloca %TSo6MyRectV, align 8 // x86_64-macosx: store float %0, // x86_64-macosx: store float %1, // x86_64-macosx: store float %2, // x86_64-macosx: store float %3, // x86_64-macosx: [[CAST:%.*]] = bitcast %TSo6MyRectV* [[COERCED]] to { <2 x float>, <2 x float> }* // x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0 // x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8 // x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1 // x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8 // x86_64-macosx: [[RESULT:%.*]] = call float @MyRect_Area(<2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]]) // x86_64-macosx: ret float [[RESULT]] public func testInlineAgg(_ rect: MyRect) -> Float { return MyRect_Area(rect) } // We need to allocate enough memory on the stack to hold the argument value we load. // arm64-ios: define swiftcc void @"$s8abitypes14testBOOLStructyyF"() // arm64-ios: [[COERCED:%.*]] = alloca i64 // arm64-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV // arm64-ios: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0 // arm64-ios: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0 // arm64-ios: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0 // arm64-ios: [[BYTE_ADDR:%.*]] = bitcast i1* [[PTR2]] to i8* // arm64-ios: store i8 0, i8* [[BYTE_ADDR]], align 8 // arm64-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]] // arm64-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]]) // // arm64e-ios: define swiftcc void @"$s8abitypes14testBOOLStructyyF"() // arm64e-ios: [[COERCED:%.*]] = alloca i64 // arm64e-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV // arm64e-ios: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0 // arm64e-ios: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0 // arm64e-ios: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0 // arm64e-ios: [[BYTE_ADDR:%.*]] = bitcast i1* [[PTR2]] to i8* // arm64e-ios: store i8 0, i8* [[BYTE_ADDR]], align 8 // arm64e-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]] // arm64e-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]]) // arm64-macosx: define swiftcc void @"$s8abitypes14testBOOLStructyyF"() // arm64-macosx: [[COERCED:%.*]] = alloca i64 // arm64-macosx: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV // arm64-macosx: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0 // arm64-macosx: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0 // arm64-macosx: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0 // arm64-macosx: [[BYTE_ADDR:%.*]] = bitcast i1* [[PTR2]] to i8* // arm64-macosx: store i8 0, i8* [[BYTE_ADDR]], align 8 // arm64-macosx: [[ARG:%.*]] = load i64, i64* [[COERCED]] // arm64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]]) public func testBOOLStruct() { let s = FiveByteStruct() MyClass.mymethod(s) }
apache-2.0
bc793987efeeff032164fdf3f691a967
77.38118
379
0.596805
2.687428
false
false
false
false
leny/kouri-tes
kouri-tes.playground/section-1.swift
1
4187
// kouri tès - Simple Swift playground. // --- Simple Values // vars & constants var myVariable = 42 myVariable = 50 let myConstant = 42 let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble:Double = 70 let explicitFloat:Float = 4 // strings let label = "The width is " let width = 94 let widthLabel = label + String( width ) let apples = 3 let oranges = 5 let appleSummary = "I have \( apples ) apples." let fruitSummary = "I have \( apples + oranges ) pieces of fruit." let myName = "Leny" let myAge = 29.08 let greetings = "Hey, I'm \( myName ) and I am \( myAge ) ! (yes, it's a Floating age)" // arrays & dictionnaries var shoppingList = [ "catfish", "water", "tulips", "blue paint" ] shoppingList[ 1 ] = "bottle of water" var occupations = [ "Kirk": "Captain", "Sulu" : "Pilot" ] occupations[ "McCoy" ] = "Doctor" let emptyArrayOfStrings = String[]() // or [] let emptyDictionnaryOfFloats = Dictionary<String, Float>() // or [:] // --- Control Flow // for in let individualScores = [ 75, 43, 103, 87, 12 ] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } // optional-value variables var optionalString:String? = "Hello" optionalString = nil var optionalName:String? = "Doctor" // optionalName = nil var greeting:String if let name = optionalName { greeting = "Hello, \( name )" } else { greeting = "Hello, world!" } // switch let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix( "pepper" ): let vegetableComment = "Is it a spicy \( x ) ?" default: let vegetableComment = "Everything tastes good in soup." } // iterate over a dictionary let interestingNumbers = [ "Prime": [ 2, 3, 5, 7, 11, 13 ], "Fibonacci": [ 1, 1, 2, 3, 5, 8 ], "Square": [ 1, 4, 9, 16, 25 ] ] var largest = 0 var largestKind = "none" for ( kind, numbers ) in interestingNumbers { for number in numbers { if number > largest { largest = number largestKind = kind } } } largest largestKind // whiles var n = 2 while n < 100 { n *= 2 } n var m = 2 do { m *= 2 } while m < 100 m // ranges in for loops var rangedNumberExclusive = 0 for i in 0..5 { rangedNumberExclusive += i } rangedNumberExclusive var rangedNumberInclusive = 0 for i in 0...5 { rangedNumberInclusive += i } rangedNumberInclusive // --- Functions and Closures func greet( name:String, day:String ) -> String { return "Hello \( name ), today is \( day )." } greet( "Captain Kirk", "monday" ) // multiple returns func getGasPrices() -> (Double, Double, Double) { return ( 3.59, 3.69, 3.79 ); } getGasPrices() // splats func sumOf( numbers:Int... ) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf( 1, 2, 3, 4, 5 ) func avgOf( numbers:Int... ) -> Double { var sum:Double = 0 let amount = Double( numbers.count ) for number in numbers { sum += Double( number ) } return sum / amount } avgOf( 1, 2, 3, 4, 5 ) // nested, and first-class typed functions func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() func makeIncrementer() -> ( Int -> Int ) { func addOne( number:Int ) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment( 7 ) func hasAnyMatches( list:Int[], condition:Int -> Bool ) -> Bool { for item in list { if condition( item ) { return true } } return false } func lessThanTen( number:Int ) -> Bool { return number < 10 } var numbers = [ 20, 19, 7, 12 ] hasAnyMatches( numbers, lessThanTen ) // closures numbers.map( { ( number:Int ) -> Int in let result = 3 * number return result } ) numbers.map( { number in 3 * number } ) sort( [ 1, 5, 3, 12, 2 ] ) { $0 > $1 }
unlicense
d09849e9728bdbed8c9c802244000b55
18.294931
87
0.60559
3.364952
false
false
false
false
noppoMan/Prorsum
Sources/Prorsum/WebSocket/CloseCode.swift
1
3290
//The MIT License (MIT) // //Copyright (c) 2015 Zewo // //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. public enum CloseCode : Equatable { case normal case goingAway case protocolError case unsupported case noStatus case abnormal case unsupportedData case policyViolation case tooLarge case missingExtension case internalError case serviceRestart case tryAgainLater case tlsHandshake case raw(UInt16) init(code: UInt16) { switch code { case 1000: self = .normal case 1001: self = .goingAway case 1002: self = .protocolError case 1003: self = .unsupported case 1005: self = .noStatus case 1006: self = .abnormal case 1007: self = .unsupportedData case 1008: self = .policyViolation case 1009: self = .tooLarge case 1010: self = .missingExtension case 1011: self = .internalError case 1012: self = .serviceRestart case 1013: self = .tryAgainLater case 1015: self = .tlsHandshake default: self = .raw(UInt16(code)) } } var code: UInt16 { switch self { case .normal: return 1000 case .goingAway: return 1001 case .protocolError: return 1002 case .unsupported: return 1003 case .noStatus: return 1005 case .abnormal: return 1006 case .unsupportedData: return 1007 case .policyViolation: return 1008 case .tooLarge: return 1009 case .missingExtension: return 1010 case .internalError: return 1011 case .serviceRestart: return 1012 case .tryAgainLater: return 1013 case .tlsHandshake: return 1015 case .raw(let code): return code } } var isValid: Bool { let code = self.code if code >= 1000 && code <= 5000 { return code != 1004 && code != 1005 && code != 1006 && code != 1014 && code != 1015 && code != 1016 && code != 1100 && code != 2000 && code != 2999 } return false } } public func == (lhs: CloseCode, rhs: CloseCode) -> Bool { return lhs.code == rhs.code }
mit
fc73f6a9b8f67cf0b221b0a5345e3eb2
34
95
0.63617
4.588563
false
false
false
false
zach-freeman/swift-localview
ThirdPartyLib/Alamofire/Tests/MultipartFormDataTests.swift
1
36461
// // MultipartFormDataTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import XCTest struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func boundary(forBoundaryType boundaryType: BoundaryType, boundaryKey: String) -> String { let boundary: String switch boundaryType { case .initial: boundary = "--\(boundaryKey)\(EncodingCharacters.crlf)" case .encapsulated: boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)\(EncodingCharacters.crlf)" case .final: boundary = "\(EncodingCharacters.crlf)--\(boundaryKey)--\(EncodingCharacters.crlf)" } return boundary } static func boundaryData(boundaryType: BoundaryType, boundaryKey: String) -> Data { return BoundaryGenerator.boundary( forBoundaryType: boundaryType, boundaryKey: boundaryKey ).data(using: .utf8, allowLossyConversion: false)! } } private func temporaryFileURL() -> URL { return BaseTestCase.testDirectoryURL.appendingPathComponent(UUID().uuidString) } // MARK: - class MultipartFormDataPropertiesTestCase: BaseTestCase { func testThatContentTypeContainsBoundary() { // Given let multipartFormData = MultipartFormData() // When let boundary = multipartFormData.boundary // Then let expectedContentType = "multipart/form-data; boundary=\(boundary)" XCTAssertEqual(multipartFormData.contentType, expectedContentType, "contentType should match expected value") } func testThatContentLengthMatchesTotalBodyPartSize() { // Given let multipartFormData = MultipartFormData() let data1 = "Lorem ipsum dolor sit amet.".data(using: .utf8, allowLossyConversion: false)! let data2 = "Vim at integre alterum.".data(using: .utf8, allowLossyConversion: false)! // When multipartFormData.append(data1, withName: "data1") multipartFormData.append(data2, withName: "data2") // Then let expectedContentLength = UInt64(data1.count + data2.count) XCTAssertEqual(multipartFormData.contentLength, expectedContentLength, "content length should match expected value") } } // MARK: - class MultipartFormDataEncodingTestCase: BaseTestCase { let crlf = EncodingCharacters.crlf func testEncodingDataBodyPart() { // Given let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary let expectedData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + "Lorem ipsum dolor sit amet." + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: .utf8, allowLossyConversion: false)! XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") } } func testEncodingMultipleDataBodyParts() { // Given let multipartFormData = MultipartFormData() let frenchData = Data("français".utf8) let japaneseData = Data("日本語".utf8) let emojiData = Data("😃👍🏻🍻🎉".utf8) multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese", mimeType: "text/plain") multipartFormData.append(emojiData, withName: "emoji", mimeType: "text/plain") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary let expectedString = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + "français" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Type: text/plain\(crlf)" + "Content-Disposition: form-data; name=\"japanese\"\(crlf)\(crlf)" + "日本語" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Type: text/plain\(crlf)" + "Content-Disposition: form-data; name=\"emoji\"\(crlf)\(crlf)" + "😃👍🏻🍻🎉" + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ) let expectedData = Data(expectedString.utf8) XCTAssertEqual(encodedData, expectedData, "encoded data should match expected data") } } func testEncodingFileBodyPart() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") multipartFormData.append(unicornImageURL, withName: "unicorn") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleFileBodyParts() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingStreamBodyPart() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleStreamBodyParts() { // Given let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } func testEncodingMultipleBodyPartsWithVaryingTypes() { // Given let multipartFormData = MultipartFormData() let loremData = Data("Lorem ipsum.".utf8) let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append(loremData, withName: "lorem") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodedData: Data? // When do { encodedData = try multipartFormData.encode() } catch { // No-op } // Then XCTAssertNotNil(encodedData, "encoded data should not be nil") if let encodedData = encodedData { let boundary = multipartFormData.boundary var expectedData = Data() expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedData.append(Data( "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)".utf8 ) ) expectedData.append(loremData) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: unicornImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedData.append(try! Data(contentsOf: rainbowImageURL)) expectedData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(encodedData, expectedData, "data should match expected data") } } } // MARK: - class MultipartFormDataWriteEncodedDataToDiskTestCase: BaseTestCase { let crlf = EncodingCharacters.crlf func testWritingEncodedDataBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary let expectedFileData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"data\"\(crlf)\(crlf)" + "Lorem ipsum dolor sit amet." + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: .utf8, allowLossyConversion: false)! XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedDataBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let frenchData = "français".data(using: .utf8, allowLossyConversion: false)! let japaneseData = "日本語".data(using: .utf8, allowLossyConversion: false)! let emojiData = "😃👍🏻🍻🎉".data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(frenchData, withName: "french") multipartFormData.append(japaneseData, withName: "japanese") multipartFormData.append(emojiData, withName: "emoji") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary let expectedFileData = ( BoundaryGenerator.boundary(forBoundaryType: .initial, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"french\"\(crlf)\(crlf)" + "français" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"japanese\"\(crlf)\(crlf)" + "日本語" + BoundaryGenerator.boundary(forBoundaryType: .encapsulated, boundaryKey: boundary) + "Content-Disposition: form-data; name=\"emoji\"\(crlf)\(crlf)" + "😃👍🏻🍻🎉" + BoundaryGenerator.boundary(forBoundaryType: .final, boundaryKey: boundary) ).data(using: .utf8, allowLossyConversion: false)! XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingEncodedFileBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") multipartFormData.append(unicornImageURL, withName: "unicorn") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedFileBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingEncodedStreamBodyPartToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedStreamBodyPartsToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let unicornDataLength = UInt64((try! Data(contentsOf: unicornImageURL)).count) let unicornStream = InputStream(url: unicornImageURL)! let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append( unicornStream, withLength: unicornDataLength, name: "unicorn", fileName: "unicorn.png", mimeType: "image/png" ) multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } func testWritingMultipleEncodedBodyPartsWithVaryingTypesToDisk() { // Given let fileURL = temporaryFileURL() let multipartFormData = MultipartFormData() let loremData = Data("Lorem ipsum.".utf8) let unicornImageURL = url(forResource: "unicorn", withExtension: "png") let rainbowImageURL = url(forResource: "rainbow", withExtension: "jpg") let rainbowDataLength = UInt64((try! Data(contentsOf: rainbowImageURL)).count) let rainbowStream = InputStream(url: rainbowImageURL)! multipartFormData.append(loremData, withName: "lorem") multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append( rainbowStream, withLength: rainbowDataLength, name: "rainbow", fileName: "rainbow.jpg", mimeType: "image/jpeg" ) var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(encodingError, "encoding error should be nil") if let fileData = try? Data(contentsOf: fileURL) { let boundary = multipartFormData.boundary var expectedFileData = Data() expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .initial, boundaryKey: boundary)) expectedFileData.append(Data( "Content-Disposition: form-data; name=\"lorem\"\(crlf)\(crlf)".utf8 ) ) expectedFileData.append(loremData) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/png\(crlf)" + "Content-Disposition: form-data; name=\"unicorn\"; filename=\"unicorn.png\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: unicornImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .encapsulated, boundaryKey: boundary)) expectedFileData.append(Data(( "Content-Type: image/jpeg\(crlf)" + "Content-Disposition: form-data; name=\"rainbow\"; filename=\"rainbow.jpg\"\(crlf)\(crlf)").utf8 ) ) expectedFileData.append(try! Data(contentsOf: rainbowImageURL)) expectedFileData.append(BoundaryGenerator.boundaryData(boundaryType: .final, boundaryKey: boundary)) XCTAssertEqual(fileData, expectedFileData, "file data should match expected file data") } else { XCTFail("file data should not be nil") } } } // MARK: - class MultipartFormDataFailureTestCase: BaseTestCase { func testThatAppendingFileBodyPartWithInvalidLastPathComponentReturnsError() { // Given let fileURL = NSURL(string: "")! as URL let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFilenameInvalid) let expectedFailureReason = "The URL provided does not have a valid filename: \(fileURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsNotFileURLReturnsError() { // Given let fileURL = URL(string: "https://example.com/image.jpg")! let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartURLInvalid) let expectedFailureReason = "The URL provided is not a file URL: \(fileURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "error failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsNotReachableReturnsError() { // Given let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("does_not_exist.jpg") let fileURL = URL(fileURLWithPath: filePath) let multipartFormData = MultipartFormData() multipartFormData.append(fileURL, withName: "empty_data") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFileNotReachableWithError) } else { XCTFail("Error should be AFError.") } } func testThatAppendingFileBodyPartThatIsDirectoryReturnsError() { // Given let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let multipartFormData = MultipartFormData() multipartFormData.append(directoryURL, withName: "empty_data", fileName: "empty", mimeType: "application/octet") var encodingError: Error? // When do { _ = try multipartFormData.encode() } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let error = encodingError as? AFError { XCTAssertTrue(error.isBodyPartFileIsDirectory) let expectedFailureReason = "The URL provided is a directory: \(directoryURL)" XCTAssertEqual(error.localizedDescription, expectedFailureReason, "error failure reason does not match expected value") } else { XCTFail("Error should be AFError.") } } func testThatWritingEncodedDataToExistingFileURLFails() { // Given let fileURL = temporaryFileURL() var writerError: Error? do { try "dummy data".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } catch { writerError = error } let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNil(writerError, "writer error should be nil") XCTAssertNotNil(encodingError, "encoding error should not be nil") if let encodingError = encodingError as? AFError { XCTAssertTrue(encodingError.isOutputStreamFileAlreadyExists) } } func testThatWritingEncodedDataToBadURLFails() { // Given let fileURL = URL(string: "/this/is/not/a/valid/url")! let multipartFormData = MultipartFormData() let data = "Lorem ipsum dolor sit amet.".data(using: .utf8, allowLossyConversion: false)! multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multipartFormData.writeEncodedData(to: fileURL) } catch { encodingError = error } // Then XCTAssertNotNil(encodingError, "encoding error should not be nil") if let encodingError = encodingError as? AFError { XCTAssertTrue(encodingError.isOutputStreamURLInvalid) } } }
mit
fb4508a6f3b8aa269acfeecb31c7a2ac
36.731328
131
0.620598
5.202088
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/NewsFeedController.swift
1
5619
// // NewsFeedController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 6/19/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit class NewsFeedController: UITableViewController, NewsFeedDataDelegate { var selectedPlaylist:Playlist? 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() AccountManager.sharedInstance.newsFeedDataDelegate = self //self.tableView.rowHeight = UITableViewAutomaticDimension //self.tableView.estimatedRowHeight = 118 self.tableView.tableFooterView = UIView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return AccountManager.sharedInstance.newsFeedItems.count } func newActivityDataReceived() { self.tableView.reloadData() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityUpdateCell", for: indexPath) as! ActivityUpdateCell // Configure the cell... let index = indexPath.row let item = AccountManager.sharedInstance.newsFeedItems[index] //Set as User Icon Eventually //cell.userIcon.image = UIImage(named: "") let width = cell.userIcon.frame.width/2 cell.userIcon.layer.cornerRadius = width cell.playlistThumbnail.layer.cornerRadius = 5 cell.playlistThumbnail.image = UIImage(named: "album03") //Set Details On Cell cell.displayNameLabel.text = item.author cell.timestampLabel.text = item.timeStringFromNow() cell.backgroundColor = UIColor.clear switch item.type { case .Activity: break case .CreatedPlaylist: cell.typeLabel.text = "Created the playlist" cell.contentLabel.text = item.playlist?.name break case .SharedPlaylist: cell.typeLabel.text = "Shared the playlist" cell.contentLabel.text = item.playlist?.name break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let index = indexPath.row let event = AccountManager.sharedInstance.newsFeedItems[index] switch event.type { case .Activity: break case .CreatedPlaylist: let vc = self.storyboard?.instantiateViewController(withIdentifier: "PlaylistDetailController") as! PlaylistDetailViewController self.selectedPlaylist = event.playlist! vc.playlist = self.selectedPlaylist self.show(vc, sender: self) break case .SharedPlaylist: break } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.destination is PlaylistDetailViewController { let vc = segue.destination as! PlaylistDetailViewController vc.playlist = self.selectedPlaylist } } } protocol NewsFeedDataDelegate { func newActivityDataReceived() }
gpl-3.0
35cb6fc7ffc102ebd31d8fd732108ae8
33.256098
140
0.653257
5.433269
false
false
false
false
luksfarris/SwiftRandomForest
SwiftRandomForest/Algorithms/Metrics.swift
1
2947
//MIT License // //Copyright (c) 2017 Lucas Farris // //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. enum MetricType { case accuracy case kappa } class Metrics<T:Numeric> { public static func metric(_ type:MetricType, actual:Array<T>, predicted:Array<T>) -> Double { switch type { case .accuracy: return accuracyMetric(actual: actual, predicted: predicted) case .kappa: return kappaMetric(actual: actual, predicted: predicted) } } private static func kappaMetric(actual:Array<T>, predicted:Array<T>) -> Double { var truePositive = 0.0, falsePositive = 0.0, falseNegative = 0.0, trueNegative = 0.0 let falseValue = T.parse(text: "\(0)") let trueValue = T.parse(text: "\(1)") for i in 0..<actual.count { if actual[i] == falseValue && predicted[i] == falseValue { falseNegative += 1 } else if actual[i] == falseValue && predicted[i] == trueValue { falsePositive = 1 } else if actual[i] == trueValue && predicted[i] == trueValue { truePositive += 1 } else { trueNegative += 1 } } let a:Double=truePositive, b:Double=trueNegative, c:Double=falsePositive, d:Double=falseNegative let p0:Double = (a+d)/(a+b+c+d) let marginalA:Double = (a+b)*(a+c)/(a+b+c+d) let marginalB:Double = (c+b)*(c+d)/(a+b+c+d) let pE:Double = (marginalA+marginalB)/(a+b+c+d) let k:Double = (p0-pE)/(1-pE) return k } private static func accuracyMetric(actual:Array<T>, predicted:Array<T>) -> Double { var correct = 0 for i in 0..<actual.count { if actual[i] == predicted[i] { correct += 1 } } return Double(correct)/Double(actual.count) } }
mit
b39644474f4c7eb2a26c97fd0592140d
37.272727
104
0.625382
4.042524
false
false
false
false
mlpqaz/V2ex
ZZV2ex/ZZV2ex/View/HomeTopicListTableViewCell.swift
1
6360
// // HomeTopicListTableViewCell.swift // ZZV2ex // // Created by ios on 2017/4/29. // Copyright © 2017年 张璋. All rights reserved. // import UIKit import YYText class HomeTopicListTableViewCell: UITableViewCell { /// 节点信息label的圆角背景图 fileprivate static var nodeBackgroundImage_Default = createImageWithColor(V2EXDefaultColor.sharedInstance.v2_NodeBackgroundColor, size: CGSize(width: 10, height: 20)).roundedCornerImageWithCornerRadius(2).stretchableImage(withLeftCapWidth: 3, topCapHeight: 3) fileprivate static var nodeBackgroundImage_Dark = createImageWithColor(V2EXDarkColor.sharedInstance.v2_NodeBackgroundColor, size: CGSize(width: 10, height: 20)).roundedCornerImageWithCornerRadius(2).stretchableImage(withLeftCapWidth: 3, topCapHeight: 3) /// 头像 var avatarImageView: UIImageView = { let imageview = UIImageView() imageview.contentMode = UIViewContentMode.scaleAspectFit return imageview }() /// 用户名 var userNameLable: UILabel = { let label = UILabel() label.font = v2Font(14) return label; }() /// 日期 和 最后发送人 var dateAndLastPostUserLabel: UILabel = { let label = UILabel() label.font = v2Font(12) return label }() /// 评论数量 var replyCountLabel: UILabel = { let label = UILabel() label.font = v2Font(12) return label }() var replyCountIconImageView: UIImageView = { let imageview = UIImageView(image: UIImage(named: "reply_n")) imageview.contentMode = .scaleAspectFit return imageview }() /// 节点 var nodeNameLabel: UILabel = { let label = UILabel(); label.font = v2Font(11) return label }() var nodeBackgroundImageView: UIImageView = UIImageView() /// 帖子标题 var topicTitleLabel: YYLabel = { let label = YYLabel() label.textVerticalAlignment = .top label.font = v2Font(18) label.displaysAsynchronously = true label.numberOfLines = 0 return label }() /// 装上面定义的那些元素的容器 var contentPanel:UIView = UIView() var itemModel:TopicListModel? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() -> Void { self.contentView.addSubview(self.contentPanel); self.contentPanel.addSubview(self.avatarImageView); self.contentPanel.addSubview(self.userNameLable); self.contentPanel.addSubview(self.dateAndLastPostUserLabel); self.contentPanel.addSubview(self.replyCountLabel); self.contentPanel.addSubview(self.replyCountIconImageView); self.contentPanel.addSubview(self.nodeBackgroundImageView); self.contentPanel.addSubview(self.nodeNameLabel); self.contentPanel.addSubview(self.topicTitleLabel); self.setupLayout() } fileprivate func setupLayout(){ self.contentPanel.snp.makeConstraints{ (make) -> Void in make.top.left.right.equalTo(self.contentView); } self.avatarImageView.snp.makeConstraints{ (make) -> Void in make.left.top.equalTo(self.contentView).offset(12); make.width.height.equalTo(35); } self.userNameLable.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.avatarImageView.snp.right).offset(10); make.top.equalTo(self.avatarImageView); } self.dateAndLastPostUserLabel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.avatarImageView); make.left.equalTo(self.userNameLable); } self.replyCountLabel.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.userNameLable); make.right.equalTo(self.contentPanel).offset(12); } self.replyCountIconImageView.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.replyCountLabel); make.width.height.equalTo(18); make.right.equalTo(replyCountLabel.snp.left).offset(-2); } self.nodeNameLabel.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.replyCountLabel); make.right.equalTo(self.replyCountIconImageView.snp.left).offset(-9) make.bottom.equalTo(self.replyCountLabel).offset(1); make.top.equalTo(self.replyCountLabel).offset(-1); } self.nodeBackgroundImageView.snp.makeConstraints{ (make) -> Void in make.top.bottom.equalTo(self.nodeNameLabel) make.left.equalTo(self.nodeNameLabel).offset(-5) make.right.equalTo(self.nodeNameLabel).offset(5) } self.contentPanel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.contentView.snp.bottom).offset(-8); } } func superBind(_ model: TopicListModel) { self.userNameLable.text = model.userName; if let layout = model.topicTitleLayout { if layout.text.string == self.itemModel?.topicTitleLayout?.text.string { return }else{ self.topicTitleLabel.textLayout = layout } } if let avata = model.avata { self.avatarImageView.fin_setImageWithUrl(URL(string: "https:" + avata)!, placeholderImage: nil,imageModificationClosure: fin_defaultImageModification() ) } self.replyCountLabel.text = model.replies; self.itemModel = model } func bind(_ model:TopicListModel) { self.superBind(model) self.dateAndLastPostUserLabel.text = model.date self.nodeNameLabel.text = model.nodeName } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
8e22d6292ee037bd37911c476b927324
33.59116
263
0.639514
4.607064
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/01309-resolvetypedecl.swift
65
628
// 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 // RUN: not %target-swift-frontend %s -typecheck protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { P { } struct d<f : e, g: e where g.h == f.h> { } class A { class func a() -> String { struct c { static let d: String = { } } } func b<T>(t: s d<c>: NSO
apache-2.0
6326cbb357b1ea33a75b258fe9895a86
24.12
79
0.673567
3.033816
false
false
false
false
forgo/BabySync
bbsync/mobile/iOS/Baby Sync/Baby Sync/BabyCollectionViewCell.swift
1
725
// // BabyCollectionViewCell.swift // Baby Sync // // Created by Elliott Richerson on 9/29/15. // Copyright © 2015 Elliott Richerson. All rights reserved. // import UIKit class BabyCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageBaby: UIImageView! @IBOutlet weak var labelBaby: UILabel! var baby: Baby? { didSet { if let b = self.baby { self.imageBaby.layer.masksToBounds = true self.imageBaby.image = UIImage(named: "Boy") self.labelBaby.text = b.name if(self.isSelected) { self.labelBaby.backgroundColor = UIColor.orange } } } } }
mit
b9817618e3bd6f541f10a5a3defe4d04
24.857143
67
0.573204
4.335329
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/ViewControllers/ShotDetailsViewControllerExtension.swift
1
7406
// // ShotDetailsViewControllerExtension.swift // Inbbbox // // Created by Peter Bruz on 02/05/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import ImageViewer import MessageUI import TTTAttributedLabel import PromiseKit // MARK: Protocols protocol UICollectionViewCellWithLabelContainingClickableLinksDelegate: class { func labelContainingClickableLinksDidTap(_ gestureRecognizer: UITapGestureRecognizer, textContainer: NSTextContainer, layoutManager: NSLayoutManager) func urlInLabelTapped(_ url: URL) } // MARK: KeyboardResizableViewDelegate extension ShotDetailsViewController: KeyboardResizableViewDelegate { func keyboardResizableView(_ view: KeyboardResizableView, willRelayoutSubviewsWithState state: KeyboardState) { let round = state == .willAppear shotDetailsView.commentComposerView.animateByRoundingCorners(round) } } // MARK: ModalByDraggingClosable extension ShotDetailsViewController: ModalByDraggingClosable { var scrollViewToObserve: UIScrollView { return shotDetailsView.collectionView } } // MARK: CommentComposerViewDelegate extension ShotDetailsViewController: CommentComposerViewDelegate { func didTapSendButtonInComposerView(_ view: CommentComposerView, comment: String) { view.startAnimation() let isAllowedToDisplaySeparator = viewModel.isAllowedToDisplaySeparator firstly { viewModel.postComment(comment) }.then { () -> Void in let numberOfItemsInFirstSection = self.shotDetailsView.collectionView.numberOfItems(inSection: 0) var indexPaths = [IndexPath(item: numberOfItemsInFirstSection, section: 0)] if isAllowedToDisplaySeparator != self.viewModel.isAllowedToDisplaySeparator { indexPaths.append(IndexPath(item: numberOfItemsInFirstSection + 1, section: 0)) } self.shotDetailsView.collectionView.performBatchUpdates({ () -> Void in self.shotDetailsView.collectionView.insertItems(at: indexPaths) }, completion: { _ -> Void in self.shotDetailsView.collectionView.scrollToItem(at: indexPaths[0], at: .centeredVertically, animated: true) }) }.always { view.stopAnimation() }.catch { error -> Void in FlashMessage.sharedInstance.showNotification(inViewController: self, title: FlashMessageTitles.addingCommentFailed, canBeDismissedByUser: true) } } func commentComposerViewDidBecomeActive(_ view: CommentComposerView) { scroller.scrollToBottomAnimated(true) } } // MARK: UIScrollViewDelegate extension ShotDetailsViewController: UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { animateHeader(start: false) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { !decelerate ? { animateHeader(start: true) checkForCommentsLikes() }() : {}() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { animateHeader(start: true) checkForCommentsLikes() } fileprivate func checkForCommentsLikes() { let visibleCells = shotDetailsView.collectionView.indexPathsForVisibleItems for indexPath in visibleCells { let index = viewModel.indexInCommentArrayBasedOnItemIndex(indexPath.row) if index >= 0 && index < viewModel.comments.count { firstly { viewModel.checkLikeStatusForComment(atIndexPath: indexPath, force: false) }.then { isLiked -> Void in self.viewModel.setLikeStatusForComment(atIndexPath: indexPath, withValue: isLiked) if isLiked { self.shotDetailsView.collectionView.reloadItems(at: [indexPath]) } }.catch { _ in } } } } } // MARK: MFMailComposeViewControllerDelegate extension ShotDetailsViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) { self.hideUnusedCommentEditingViews() } switch result { case MFMailComposeResult.sent: let contentReportedAlert = UIAlertController.inappropriateContentReported() present(contentReportedAlert, animated: true, completion: nil) default: break } } } // MARK: TTTAttributedLabelDelegate extension ShotDetailsViewController: TTTAttributedLabelDelegate { func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { if let user = viewModel.userForURL(url) { presentProfileViewControllerForUser(user) } else { firstly { viewModel.userForId(url.absoluteString) }.then { [weak self] user in self?.presentProfileViewControllerForUser(user) }.catch { _ in } } } } // MARK: AvatarViewDelegate extension ShotDetailsViewController: AvatarViewDelegate { func avatarView(_ avatarView: AvatarView, didTapButton avatarButton: UIButton) { var user: UserType? if avatarView.superview == header { user = viewModel.shot.user } else if avatarView.superview?.superview is ShotDetailsCommentCollectionViewCell { guard let cell = avatarView.superview?.superview as? ShotDetailsCommentCollectionViewCell else { return } if let indexPath = shotDetailsView.collectionView.indexPath(for: cell) { let index = viewModel.indexInCommentArrayBasedOnItemIndex(indexPath.row) user = viewModel.comments[index].user } } if let user = user { presentProfileViewControllerForUser(user) } } } // MARK: UICollectionViewCellWithLabelContainingClickableLinksDelegate extension ShotDetailsViewController: UICollectionViewCellWithLabelContainingClickableLinksDelegate { func labelContainingClickableLinksDidTap(_ gestureRecognizer: UITapGestureRecognizer, textContainer: NSTextContainer, layoutManager: NSLayoutManager) { guard let url = URLDetector.detectUrlFromGestureRecognizer(gestureRecognizer, textContainer: textContainer, layoutManager: layoutManager) else { return } handleTappedUrl(url) } func urlInLabelTapped(_ url: URL) { handleTappedUrl(url) } fileprivate func handleTappedUrl(_ url: URL) { if viewModel.shouldOpenUserDetailsFromUrl(url) { if let identifier = url.absoluteString.components(separatedBy: "/").last { firstly { viewModel.userForId(identifier) }.then { [weak self] user in self?.presentProfileViewControllerForUser(user) }.catch { _ in } } } else { UIApplication.shared.openURL(url) } } }
gpl-3.0
8eca68ee69e614049be3a47efbbc142d
34.600962
155
0.66077
5.687404
false
false
false
false
WLChopSticks/weibo-swift-
weibo(swift)/weibo(swift)/Classes/Tools/Common.swift
2
916
// // Common.swift // weibo(swift) // // Created by 王 on 15/12/15. // Copyright © 2015年 王. All rights reserved. // import UIKit //app基本信息 let client_id = "3754893333" let client_secret = "d0f495da519ae1132e38b48084ce3fb9" let redirect_uri = "http://www.baidu.com" //定义系统的主色调 let themeColor = UIColor.orangeColor() //定义切换控制器的通知名称 let changeRootViewController = "changeRootViewController" //定义屏幕的宽度 let screenWidth: CGFloat = UIScreen.mainScreen().bounds.width let screenHeight: CGFloat = UIScreen.mainScreen().bounds.height //定义微博状态cell的间距 let statusCellMargin: CGFloat = 10 //随机颜色 func randomColor() -> UIColor { let r = CGFloat((random() % 256)) / 255.0 let g = CGFloat((random() % 256)) / 255.0 let b = CGFloat((random() % 256)) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: 1) }
mit
6fc651493e5d39cd9da98c52a68e02b8
21.216216
63
0.694275
3.098113
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/demo/controllers/AccountDetailViewController.swift
1
2129
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class AccountDetailViewController: UIViewController { var header = AccountDetailHeaderView() var tableViewController = AccountDetailListViewController() //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var dataProvider : AccountObject? { didSet { header.dataProvider = self.dataProvider tableViewController.dataProvider = self.dataProvider } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.view.addSubview(header) self.view.constrainChild(header, xAlignment: .left, yAlignment: .top, width: self.view.frame.width, height: 120, yOffset: 64) self.view.addSubview(tableViewController.view) self.tableViewController.view.constrainBelow(self.header, xAlignment: .center, width: self.view.frame.width, height: self.view.frame.height - 240) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– }
bsd-3-clause
2fdb9a74b1e0e0f88933a58759b75ddb
35.911111
90
0.433474
6.892116
false
false
false
false
tardieu/swift
test/SILGen/complete_object_init.swift
1
2012
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-silgen | %FileCheck %s struct X { } class A { // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A } // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A // CHECK: store [[SELF_PARAM]] to [init] [[SELF]] : $*A // CHECK: [[SELFP:%[0-9]+]] = load_borrow [[SELF]] : $*A // CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A // CHECK: store [[INIT_RESULT]] to [init] [[SELF]] : $*A // CHECK: [[RESULT:%[0-9]+]] = load [copy] [[SELF]] : $*A // CHECK: destroy_value [[SELF_BOX]] : ${ var A } // CHECK: return [[RESULT]] : $A // CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A convenience init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type): // CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A // CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A // CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A // CHECK: return [[RESULT]] : $A self.init(x: X()) } init(x: X) { } }
apache-2.0
151903e6e82c7ed721a83df7c147470f
56.485714
152
0.54175
2.782849
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/Keyknox/Client/KeynoxClient+Queries.swift
1
15563
// // Copyright (C) 2015-2020 Virgil Security Inc. // // 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 nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation // MARK: - Queries extension KeyknoxClient: KeyknoxClientProtocol { /// Header key for blob hash @objc public static let virgilKeyknoxHashKey = "Virgil-Keyknox-Hash" /// Header key for previous blob hash @objc public static let virgilKeyknoxPreviousHashKey = "Virgil-Keyknox-Previous-Hash" /// Default root value @objc public static let keyStorageRoot = "DEFAULT_ROOT" /// Default path value @objc public static let keyStoragePath = "DEFAULT_PATH" /// Default key value @objc public static let keyStorageKey = "DEFAULT_KEY" private func createRetry() -> RetryProtocol { return ExpBackoffRetry(config: self.retryConfig) } // TODO: Remove this workaround for old API support private func extractIdentity(operation: GenericOperation<Response>) throws -> String { guard let networkOperation = operation as? NetworkRetryOperation, let token = networkOperation.token else { fatalError("Keyknox operations typing failed") } return token.identity() } /// Push value to Keyknox service /// /// - Parameters: /// - params: params /// - meta: meta data /// - value: encrypted blob /// - previousHash: hash of previous blob /// - Returns: EncryptedKeyknoxValue /// - Throws: /// - KeyknoxClientError.emptyIdentities, if identities are empty /// - KeyknoxClientError.constructingUrl, if url initialization failed /// - KeyknoxClientError.invalidOptions, if internal options error occured /// - ServiceError, if service returned correctly-formed error json /// - NSError with KeyknoxClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func pushValue(params: KeyknoxPushParams? = nil, meta: Data, value: Data, previousHash: Data?) throws -> EncryptedKeyknoxValue { let headers: [String: String] if let previousHash = previousHash { headers = [KeyknoxClient.virgilKeyknoxPreviousHashKey: previousHash.base64EncodedString()] } else { headers = [:] } let request: ServiceRequest var queryParams: [String: Encodable] = [ "meta": meta.base64EncodedString(), "value": value.base64EncodedString() ] if let params = params { guard !params.identities.isEmpty else { throw KeyknoxClientError.emptyIdentities } guard let url = URL(string: "keyknox/v2/push", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } try queryParams.merge([ "root": params.root, "path": params.path, "key": params.key, "identities": params.identities ]) { _, _ -> Encodable in throw KeyknoxClientError.invalidOptions } request = try ServiceRequest(url: url, method: .post, params: queryParams, headers: headers) } else { guard let url = URL(string: "keyknox/v1", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } request = try ServiceRequest(url: url, method: .put, params: queryParams, headers: headers) } let tokenContext = TokenContext(service: "keyknox", operation: "put") let networkOperation = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) let response = try networkOperation.startSync().get() let keyknoxValue: EncryptedKeyknoxValue if params == nil { let keyknoxData: KeyknoxData = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) let identity = try self.extractIdentity(operation: networkOperation) keyknoxValue = EncryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash, identity: identity) } else { let keyknoxData: KeyknoxDataV2 = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) keyknoxValue = EncryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash) } return keyknoxValue } /// Pulls values from Keyknox service /// /// - Parameter params: Pull params /// - Returns: EncryptedKeyknoxValue /// - Throws: /// - KeyknoxClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with KeyknoxClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func pullValue(params: KeyknoxPullParams? = nil) throws -> EncryptedKeyknoxValue { let request: ServiceRequest if let params = params { guard let url = URL(string: "keyknox/v2/pull", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } let queryParams = [ "root": params.root, "path": params.path, "key": params.key, "identity": params.identity ] request = try ServiceRequest(url: url, method: .post, params: queryParams) } else { guard let url = URL(string: "keyknox/v1", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } request = try ServiceRequest(url: url, method: .get) } let tokenContext = TokenContext(service: "keyknox", operation: "get") let networkOperation = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) let response = try networkOperation.startSync().get() let keyknoxValue: EncryptedKeyknoxValue if params == nil { let keyknoxData: KeyknoxData = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) let identity = try self.extractIdentity(operation: networkOperation) keyknoxValue = EncryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash, identity: identity) } else { let keyknoxData: KeyknoxDataV2 = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) keyknoxValue = EncryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash) } return keyknoxValue } /// Get keys for given root /// /// - Parameter params: Get keys params /// - Returns: Array of keys /// - Throws: /// - KeyknoxClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with KeyknoxClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc public func getKeys(params: KeyknoxGetKeysParams) throws -> Set<String> { guard let url = URL(string: "keyknox/v2/keys", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } var queryParams: [String: String] = [:] if let identity = params.identity { queryParams["identity"] = identity } if let root = params.root { queryParams["root"] = root } if let path = params.path { queryParams["path"] = path } let request = try ServiceRequest(url: url, method: .post, params: queryParams) let tokenContext = TokenContext(service: "keyknox", operation: "get") let response = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) .startSync() .get() let keys: [String] = try self.processResponse(response) return Set(keys) } /// Resets Keyknox value (makes it empty) /// /// - Parameter params: Reset params /// - Returns: DecryptedKeyknoxValue /// - Throws: /// - KeyknoxClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with KeyknoxClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc open func resetValue(params: KeyknoxResetParams? = nil) throws -> DecryptedKeyknoxValue { let request: ServiceRequest if let params = params { guard let url = URL(string: "keyknox/v2/reset", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } var queryParams: [String: String] = [:] if let root = params.root { queryParams["root"] = root } if let path = params.path { queryParams["path"] = path } if let key = params.key { queryParams["key"] = key } request = try ServiceRequest(url: url, method: .post, params: queryParams) } else { guard let url = URL(string: "keyknox/v1/reset", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } request = try ServiceRequest(url: url, method: .post) } let tokenContext = TokenContext(service: "keyknox", operation: "delete") let networkOperation = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) let response = try networkOperation.startSync().get() let keyknoxValue: DecryptedKeyknoxValue if params == nil { let keyknoxData: KeyknoxData = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) let identity = try self.extractIdentity(operation: networkOperation) keyknoxValue = DecryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash, identity: identity) } else { let keyknoxData: KeyknoxDataV2 = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) keyknoxValue = DecryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash) } return keyknoxValue } /// Deletes recipient /// /// - Parameter params: Delete recipient params /// - Returns: DecryptedKeyknoxValue /// - Throws: /// - KeyknoxClientError.constructingUrl, if url initialization failed /// - ServiceError, if service returned correctly-formed error json /// - NSError with KeyknoxClient.serviceErrorDomain error domain, /// http status code as error code, and description string if present in http body /// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient` @objc open func deleteRecipient(params: KeyknoxDeleteRecipientParams) throws -> DecryptedKeyknoxValue { guard let url = URL(string: "keyknox/v2/reset", relativeTo: self.serviceUrl) else { throw KeyknoxClientError.constructingUrl } var queryParams = [ "identity": params.identity, "root": params.root, "path": params.path ] if let key = params.key { queryParams["key"] = key } let request = try ServiceRequest(url: url, method: .post, params: queryParams) let tokenContext = TokenContext(service: "keyknox", operation: "delete") let networkOperation = try self.sendWithRetry(request, retry: self.createRetry(), tokenContext: tokenContext) let response = try networkOperation.startSync().get() let keyknoxData: KeyknoxDataV2 = try self.processResponse(response) let keyknoxHash = try self.extractKeyknoxHash(response: response) return DecryptedKeyknoxValue(keyknoxData: keyknoxData, keyknoxHash: keyknoxHash) } private func extractKeyknoxHash(response: Response) throws -> Data { let responseHeaders = response.response.allHeaderFields as NSDictionary guard let keyknoxHashStr = responseHeaders[KeyknoxClient.virgilKeyknoxHashKey] as? String, let keyknoxHash = Data(base64Encoded: keyknoxHashStr) else { throw KeyknoxClientError.invalidPreviousHashHeader } return keyknoxHash } }
bsd-3-clause
1c53152d4a4b1b40b5b8acc9534739eb
39.423377
120
0.626036
4.943774
false
false
false
false
hughbe/swift
test/SILOptimizer/definite_init_diagnostics.swift
4
33725
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-sil %s -parse-stdlib -o /dev/null -verify import Swift func markUsed<T>(_ t: T) {} // These are tests for definite initialization, which is implemented by the // memory promotion pass. func test1() -> Int { // expected-warning @+1 {{variable 'a' was never mutated; consider changing to 'let' constant}} {{3-6=let}} var a : Int // expected-note {{variable defined here}} return a // expected-error {{variable 'a' used before being initialized}} } func takes_inout(_ a: inout Int) {} func takes_inout_any(_ a: inout Any) {} func takes_closure(_ fn: () -> ()) {} class SomeClass { var x : Int // expected-note {{'self.x' not initialized}} var computedProperty : Int { return 42 } init() { x = 0 } init(b : Bool) { if (b) {} } // expected-error {{return from initializer without initializing all stored properties}} func baseMethod() {} } struct SomeStruct { var x = 1 } func test2() { // inout. var a1 : Int // expected-note {{variable defined here}} takes_inout(&a1) // expected-error {{variable 'a1' passed by reference before being initialized}} var a2 = 4 takes_inout(&a2) // ok. var a3 : Int a3 = 4 takes_inout(&a3) // ok. // Address-of with Builtin.addressof. var a4 : Int // expected-note {{variable defined here}} Builtin.addressof(&a4) // expected-error {{address of variable 'a4' taken before it is initialized}} // expected-warning @-1 {{result of call to 'addressof' is unused}} // Closures. // expected-warning @+1 {{variable 'b1' was never mutated}} {{3-6=let}} var b1 : Int // expected-note {{variable defined here}} takes_closure { // expected-error {{variable 'b1' captured by a closure before being initialized}} markUsed(b1) } var b1a : Int // expected-note {{variable defined here}} takes_closure { // expected-error {{variable 'b1a' captured by a closure before being initialized}} b1a += 1 markUsed(b1a) } var b2 = 4 takes_closure { // ok. markUsed(b2) } b2 = 1 var b3 : Int b3 = 4 takes_closure { // ok. markUsed(b3) } var b4 : Int? takes_closure { // ok. markUsed(b4!) } b4 = 7 let b5: Any b5 = "x" { takes_inout_any(&b5) }() // expected-error {{immutable value 'b5' may not be passed inout}} ({ takes_inout_any(&b5) })() // expected-error {{immutable value 'b5' may not be passed inout}} // Structs var s1 : SomeStruct s1 = SomeStruct() // ok _ = s1 var s2 : SomeStruct // expected-note {{variable defined here}} s2.x = 1 // expected-error {{struct 's2' must be completely initialized before a member is stored to}} // Classes // expected-warning @+1 {{variable 'c1' was never mutated}} {{3-6=let}} var c1 : SomeClass // expected-note {{variable defined here}} markUsed(c1.x) // expected-error {{variable 'c1' used before being initialized}} let c2 = SomeClass() markUsed(c2.x) // ok // Weak weak var w1 : SomeClass? _ = w1 // ok: default-initialized weak var w2 = SomeClass() _ = w2 // ok // Unowned. This is immediately crashing code (it causes a retain of a // released object) so it should be diagnosed with a warning someday. // expected-warning @+1 {{variable 'u1' was never mutated; consider changing to 'let' constant}} {{11-14=let}} unowned var u1 : SomeClass // expected-note {{variable defined here}} _ = u1 // expected-error {{variable 'u1' used before being initialized}} unowned let u2 = SomeClass() _ = u2 // ok } // Tuple field sensitivity. func test4() { // expected-warning @+1 {{variable 't1' was never mutated; consider changing to 'let' constant}} {{3-6=let}} var t1 = (1, 2, 3) markUsed(t1.0 + t1.1 + t1.2) // ok // expected-warning @+1 {{variable 't2' was never mutated; consider changing to 'let' constant}} {{3-6=let}} var t2 : (Int, Int, Int) // expected-note 3 {{variable defined here}} markUsed(t2.0) // expected-error {{variable 't2.0' used before being initialized}} markUsed(t2.1) // expected-error {{variable 't2.1' used before being initialized}} markUsed(t2.2) // expected-error {{variable 't2.2' used before being initialized}} var t3 : (Int, Int, Int) // expected-note {{variable defined here}} t3.0 = 1; t3.2 = 42 markUsed(t3.0) markUsed(t3.1) // expected-error {{variable 't3.1' used before being initialized}} markUsed(t3.2) // Partially set, wholly read. var t4 : (Int, Int, Int) // expected-note 1 {{variable defined here}} t4.0 = 1; t4.2 = 42 _ = t4 // expected-error {{variable 't4.1' used before being initialized}} // Subelement sets. var t5 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}} t5.a = (1,2) markUsed(t5.a.0) markUsed(t5.a.1) markUsed(t5.b) // expected-error {{variable 't5.b' used before being initialized}} var t6 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}} t6.b = 12; t6.a.1 = 1 markUsed(t6.a.0) // expected-error {{variable 't6.a.0' used before being initialized}} markUsed(t6.a.1) markUsed(t6.b) } func tupleinout(_ a: inout (lo: Int, hi: Int)) { markUsed(a.0) // ok markUsed(a.1) // ok } // Address only types func test5<T>(_ x: T, y: T) { var a : ((T, T), T) // expected-note {{variable defined here}} a.0 = (x, y) _ = a // expected-error {{variable 'a.1' used before being initialized}} } struct IntFloatStruct { var a = 1, b = 2.0 } func test6() -> Int { var a = IntFloatStruct() a.a = 1 a.b = 2 return a.a } // Control flow. func test7(_ cond: Bool) { var a : Int if cond { a = 42 } else { a = 17 } markUsed(a) // ok var b : Int // expected-note {{variable defined here}} if cond { } else { b = 17 } markUsed(b) // expected-error {{variable 'b' used before being initialized}} } protocol SomeProtocol { func protoMe() } protocol DerivedProtocol : SomeProtocol {} func existentials(_ i: Int, dp: DerivedProtocol) { // expected-warning @+1 {{variable 'a' was written to, but never read}} var a : Any = () a = i // expected-warning @+1 {{variable 'b' was written to, but never read}} var b : Any b = () // expected-warning @+1 {{variable 'c' was never used}} {{7-8=_}} var c : Any // no uses. // expected-warning @+1 {{variable 'd1' was never mutated}} {{3-6=let}} var d1 : Any // expected-note {{variable defined here}} _ = d1 // expected-error {{variable 'd1' used before being initialized}} // expected-warning @+1 {{variable 'e' was never mutated}} {{3-6=let}} var e : SomeProtocol // expected-note {{variable defined here}} e.protoMe() // expected-error {{variable 'e' used before being initialized}} var f : SomeProtocol = dp // ok, init'd by existential upcast. // expected-warning @+1 {{variable 'g' was never mutated}} {{3-6=let}} var g : DerivedProtocol // expected-note {{variable defined here}} f = g // expected-error {{variable 'g' used before being initialized}} _ = f } // Tests for top level code. var g1 : Int // expected-note {{variable defined here}} var g2 : Int = 42 func testTopLevelCode() { // expected-error {{variable 'g1' used by function definition before being initialized}} markUsed(g1) markUsed(g2) } var (g3,g4) : (Int,Int) // expected-note 2 {{variable defined here}} class DITLC_Class { init() { // expected-error {{variable 'g3' used by function definition before being initialized}} markUsed(g3) } deinit { // expected-error {{variable 'g4' used by function definition before being initialized}} markUsed(g4) } } struct EmptyStruct {} func useEmptyStruct(_ a: EmptyStruct) {} func emptyStructTest() { // <rdar://problem/20065892> Diagnostic for an uninitialized constant calls it a variable let a : EmptyStruct // expected-note {{constant defined here}} useEmptyStruct(a) // expected-error {{constant 'a' used before being initialized}} var (b,c,d) : (EmptyStruct,EmptyStruct,EmptyStruct) // expected-note 2 {{variable defined here}} c = EmptyStruct() useEmptyStruct(b) // expected-error {{variable 'b' used before being initialized}} useEmptyStruct(c) useEmptyStruct(d) // expected-error {{variable 'd' used before being initialized}} var (e,f) : (EmptyStruct,EmptyStruct) (e, f) = (EmptyStruct(),EmptyStruct()) useEmptyStruct(e) useEmptyStruct(f) var g : (EmptyStruct,EmptyStruct) g = (EmptyStruct(),EmptyStruct()) useEmptyStruct(g.0) useEmptyStruct(g.1) } func takesTuplePair(_ a : inout (SomeClass, SomeClass)) {} // This tests cases where a store might be an init or assign based on control // flow path reaching it. func conditionalInitOrAssign(_ c : Bool, x : Int) { var t : Int // Test trivial types. if c { t = 0 } if c { t = x } t = 2 _ = t // Nontrivial type var sc : SomeClass if c { sc = SomeClass() } sc = SomeClass() _ = sc // Tuple element types var tt : (SomeClass, SomeClass) if c { tt.0 = SomeClass() } else { tt.1 = SomeClass() } tt.0 = SomeClass() tt.1 = tt.0 var t2 : (SomeClass, SomeClass) // expected-note {{variable defined here}} t2.0 = SomeClass() takesTuplePair(&t2) // expected-error {{variable 't2.1' passed by reference before being initialized}} } enum NotInitializedUnion { init() { } // expected-error {{return from enum initializer method without storing to 'self'}} case X case Y } extension NotInitializedUnion { init(a : Int) { } // expected-error {{return from enum initializer method without storing to 'self'}} } enum NotInitializedGenericUnion<T> { init() { } // expected-error {{return from enum initializer method without storing to 'self'}} case X } class SomeDerivedClass : SomeClass { var y : Int override init() { y = 42 // ok super.init() } init(a : Bool) { super.init() // expected-error {{property 'self.y' not initialized at super.init call}} } init(a : Bool, b : Bool) { // x is a superclass member. It cannot be used before we are initialized. x = 17 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}} y = 42 super.init() } init(a : Bool, b : Bool, c : Bool) { y = 42 super.init() } init(a : Bool, b : Bool, c : Bool, d : Bool) { y = 42 super.init() super.init() // expected-error {{super.init called multiple times in initializer}} } init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool) { super.init() // expected-error {{property 'self.y' not initialized at super.init call}} super.init() // expected-error {{super.init called multiple times in initializer}} } init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool, f : Bool) { y = 11 if a { super.init() } x = 42 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}} } // expected-error {{super.init isn't called on all paths before returning from initializer}} func someMethod() {} init(a : Int) { y = 42 super.init() } init(a : Int, b : Bool) { y = 42 someMethod() // expected-error {{use of 'self' in method call 'someMethod' before super.init initializes self}} super.init() } init(a : Int, b : Int) { y = 42 baseMethod() // expected-error {{use of 'self' in method call 'baseMethod' before super.init initializes self}} super.init() } init(a : Int, b : Int, c : Int) { y = computedProperty // expected-error {{use of 'self' in property access 'computedProperty' before super.init initializes self}} super.init() } } //===----------------------------------------------------------------------===// // Delegating initializers //===----------------------------------------------------------------------===// class DelegatingCtorClass { var ivar: EmptyStruct init() { ivar = EmptyStruct() } convenience init(x: EmptyStruct) { self.init() _ = ivar // okay: ivar has been initialized by the delegation above } convenience init(x: EmptyStruct, y: EmptyStruct) { _ = ivar // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}} ivar = x // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}} self.init() } convenience init(x: EmptyStruct, y: EmptyStruct, z: EmptyStruct) { self.init() self.init() // expected-error {{self.init called multiple times in initializer}} } convenience init(x: (EmptyStruct, EmptyStruct)) { method() // expected-error {{use of 'self' in method call 'method' before self.init initializes self}} self.init() } convenience init(c : Bool) { if c { return } self.init() } // expected-error {{self.init isn't called on all paths before returning from initializer}} convenience init(bool: Bool) { doesNotReturn() } convenience init(double: Double) { } // expected-error{{self.init isn't called on all paths before returning from initializer}} func method() {} } struct DelegatingCtorStruct { var ivar : EmptyStruct init() { ivar = EmptyStruct() } init(a : Double) { self.init() _ = ivar // okay: ivar has been initialized by the delegation above } init(a : Int) { _ = ivar // expected-error {{'self' used before self.init call}} self.init() } init(a : Float) { self.init() self.init() // expected-error {{self.init called multiple times in initializer}} } init(c : Bool) { if c { return } self.init() } // expected-error {{self.init isn't called on all paths before returning from initializer}} } enum DelegatingCtorEnum { case Dinosaur, Train, Truck init() { self = .Train } init(a : Double) { self.init() _ = self // okay: self has been initialized by the delegation above self = .Dinosaur } init(a : Int) { _ = self // expected-error {{'self' used before self.init call}} self.init() } init(a : Float) { self.init() self.init() // expected-error {{self.init called multiple times in initializer}} } init(c : Bool) { if c { return } self.init() } // expected-error {{self.init isn't called on all paths before returning from initializer}} } //===----------------------------------------------------------------------===// // Delegating initializers vs extensions //===----------------------------------------------------------------------===// protocol TriviallyConstructible { init() func go(_ x: Int) } extension TriviallyConstructible { init(down: Int) { go(down) // expected-error {{'self' used before self.init call}} self.init() } } //===----------------------------------------------------------------------===// // Various bugs //===----------------------------------------------------------------------===// // rdar://16119509 - Dataflow problem where we reject valid code. class rdar16119509_Buffer { init(x : Int) { } } class rdar16119509_Base {} class rdar16119509_Derived : rdar16119509_Base { override init() { var capacity = 2 while capacity < 2 { capacity <<= 1 } buffer = rdar16119509_Buffer(x: capacity) } var buffer : rdar16119509_Buffer } // <rdar://problem/16797372> Bogus error: self.init called multiple times in initializer extension Foo { convenience init() { for _ in 0..<42 { } self.init(a: 4) } } class Foo { init(a : Int) {} } func doesNotReturn() -> Never { while true {} } func doesReturn() {} func testNoReturn1(_ b : Bool) -> Any { var a : Any if b { a = 42 } else { doesNotReturn() } return a // Ok, because the noreturn call path isn't viable. } func testNoReturn2(_ b : Bool) -> Any { var a : Any // expected-note {{variable defined here}} if b { a = 42 } else { doesReturn() } // Not ok, since doesReturn() doesn't kill control flow. return a // expected-error {{variable 'a' used before being initialized}} } class PerpetualMotion { func start() -> Never { repeat {} while true } static func stop() -> Never { repeat {} while true } } func testNoReturn3(_ b : Bool) -> Any { let a : Int switch b { default: PerpetualMotion().start() } return a } func testNoReturn4(_ b : Bool) -> Any { let a : Int switch b { default: PerpetualMotion.stop() } return a } // <rdar://problem/16687555> [DI] New convenience initializers cannot call inherited convenience initializers class BaseWithConvenienceInits { init(int: Int) {} convenience init() { self.init(int: 3) } } class DerivedUsingConvenienceInits : BaseWithConvenienceInits { convenience init(string: String) { self.init() } } // <rdar://problem/16660680> QoI: _preconditionFailure() in init method complains about super.init being called multiple times class ClassWhoseInitDoesntReturn : BaseWithConvenienceInits { init() { _preconditionFailure("leave me alone dude"); } } // <rdar://problem/17233681> DI: Incorrectly diagnostic in delegating init with generic enum enum r17233681Lazy<T> { case Thunk(() -> T) case Value(T) init(value: T) { self = .Value(value) } } extension r17233681Lazy { init(otherValue: T) { self.init(value: otherValue) } } // <rdar://problem/17556858> delegating init that delegates to @_transparent init fails struct FortyTwo { } extension Double { init(v : FortyTwo) { self.init(0.0) } } // <rdar://problem/17686667> If super.init is implicitly inserted, DI diagnostics have no location info class r17686667Base {} class r17686667Test : r17686667Base { var x: Int override init() { // expected-error {{property 'self.x' not initialized at implicitly generated super.init call}} } } // <rdar://problem/18199087> DI doesn't catch use of super properties lexically inside super.init call class r18199087BaseClass { let data: Int init(val: Int) { data = val } } class r18199087SubClassA: r18199087BaseClass { init() { super.init(val: self.data) // expected-error {{use of 'self' in property access 'data' before super.init initializes self}} } } // <rdar://problem/18414728> QoI: DI should talk about "implicit use of self" instead of individual properties in some cases class rdar18414728Base { var prop:String? { return "boo" } // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let aaaaa:String // expected-note 3 {{'self.aaaaa' not initialized}} init() { if let p1 = prop { // expected-error {{use of 'self' in property access 'prop' before all stored properties are initialized}} aaaaa = p1 } aaaaa = "foo" // expected-error {{immutable value 'self.aaaaa' may only be initialized once}} } init(a : ()) { method1(42) // expected-error {{use of 'self' in method call 'method1' before all stored properties are initialized}} aaaaa = "foo" } init(b : ()) { final_method() // expected-error {{use of 'self' in method call 'final_method' before all stored properties are initialized}} aaaaa = "foo" } init(c : ()) { aaaaa = "foo" final_method() // ok } func method1(_ a : Int) {} final func final_method() {} } class rdar18414728Derived : rdar18414728Base { var prop2:String? { return "boo" } // expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let aaaaa2:String override init() { if let p1 = prop2 { // expected-error {{use of 'self' in property access 'prop2' before super.init initializes self}} aaaaa2 = p1 } aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}} super.init() } override init(a : ()) { method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}} aaaaa2 = "foo" super.init() } override init(b : ()) { aaaaa2 = "foo" method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}} super.init() } override init(c : ()) { super.init() // expected-error {{property 'self.aaaaa2' not initialized at super.init call}} aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}} method2() } func method2() {} } struct rdar18414728Struct { var computed:Int? { return 4 } var i : Int // expected-note 2 {{'self.i' not initialized}} var j : Int // expected-note {{'self.j' not initialized}} init() { j = 42 if let p1 = computed { // expected-error {{'self' used before all stored properties are initialized}} i = p1 } i = 1 } init(a : ()) { method(42) // expected-error {{'self' used before all stored properties are initialized}} i = 1 j = 2 } func method(_ a : Int) {} } extension Int { mutating func mutate() {} func inspect() {} } // <rdar://problem/19035287> let properties should only be initializable, not reassignable struct LetProperties { // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let arr : [Int] // expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let (u, v) : (Int, Int) // expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let w : (Int, Int) let x = 42 // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let y : Int let z : Int? // expected-note{{'self.z' not initialized}} // Let properties can be initialized naturally exactly once along any given // path through an initializer. init(cond : Bool) { if cond { w.0 = 4 (u,v) = (4,2) y = 71 } else { y = 13 v = 2 u = v+1 w.0 = 7 } w.1 = 19 z = nil arr = [] } // Multiple initializations are an error. init(a : Int) { y = a y = a // expected-error {{immutable value 'self.y' may only be initialized once}} u = a v = a u = a // expected-error {{immutable value 'self.u' may only be initialized once}} v = a // expected-error {{immutable value 'self.v' may only be initialized once}} w.0 = a w.1 = a w.0 = a // expected-error {{immutable value 'self.w.0' may only be initialized once}} w.1 = a // expected-error {{immutable value 'self.w.1' may only be initialized once}} arr = [] arr = [] // expected-error {{immutable value 'self.arr' may only be initialized once}} } // expected-error {{return from initializer without initializing all stored properties}} // inout uses of let properties are an error. init() { u = 1; v = 13; w = (1,2); y = 1 ; z = u var variable = 42 swap(&u, &variable) // expected-error {{immutable value 'self.u' may not be passed inout}} u.inspect() // ok, non mutating. u.mutate() // expected-error {{mutating method 'mutate' may not be used on immutable value 'self.u'}} arr = [] arr += [] // expected-error {{mutating operator '+=' may not be used on immutable value 'self.arr'}} arr.append(4) // expected-error {{mutating method 'append' may not be used on immutable value 'self.arr'}} arr[12] = 17 // expected-error {{mutating subscript 'subscript' may not be used on immutable value 'self.arr'}} } } // <rdar://problem/19215313> let properties don't work with protocol method dispatch protocol TestMutabilityProtocol { func toIntMax() mutating func changeToIntMax() } class C<T : TestMutabilityProtocol> { let x : T let y : T init(a : T) { x = a; y = a x.toIntMax() y.changeToIntMax() // expected-error {{mutating method 'changeToIntMax' may not be used on immutable value 'self.y'}} } } struct MyMutabilityImplementation : TestMutabilityProtocol { func toIntMax() { } mutating func changeToIntMax() { } } // <rdar://problem/16181314> don't require immediate initialization of 'let' values func testLocalProperties(_ b : Int) -> Int { // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let x : Int let y : Int // never assigned is ok expected-warning {{immutable value 'y' was never used}} {{7-8=_}} x = b x = b // expected-error {{immutable value 'x' may only be initialized once}} // This is ok, since it is assigned multiple times on different paths. let z : Int if true || false { z = b } else { z = b } _ = z return x } // Should be rejected as multiple assignment. func testAddressOnlyProperty<T>(_ b : T) -> T { // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let x : T let y : T let z : T // never assigned is ok. expected-warning {{immutable value 'z' was never used}} {{7-8=_}} x = b y = b x = b // expected-error {{immutable value 'x' may only be initialized once}} var tmp = b swap(&x, &tmp) // expected-error {{immutable value 'x' may not be passed inout}} return y } // <rdar://problem/19254812> DI bug when referencing let member of a class class r19254812Base {} class r19254812Derived: r19254812Base{ let pi = 3.14159265359 init(x : ()) { markUsed(pi) // ok, no diagnostic expected. } } // <rdar://problem/19259730> Using mutating methods in a struct initializer with a let property is rejected struct StructMutatingMethodTest { let a, b: String // expected-note 2 {{'self.b' not initialized}} init(x: String, y: String) { a = x b = y mutate() // ok } init(x: String) { a = x mutate() // expected-error {{'self' used before all stored properties are initialized}} b = x } init() { a = "" nonmutate() // expected-error {{'self' used before all stored properties are initialized}} b = "" } mutating func mutate() {} func nonmutate() {} } // <rdar://problem/19268443> DI should reject this call to transparent function class TransparentFunction { let x : Int let y : Int init() { x = 42 x += 1 // expected-error {{mutating operator '+=' may not be used on immutable value 'self.x'}} y = 12 myTransparentFunction(&y) // expected-error {{immutable value 'self.y' may not be passed inout}} } } @_transparent func myTransparentFunction(_ x : inout Int) {} // <rdar://problem/19782264> Immutable, optional class members can't have their subproperties read from during init() class MyClassWithAnInt { let channelCount : Int = 42 } class MyClassTestExample { let clientFormat : MyClassWithAnInt! init(){ clientFormat = MyClassWithAnInt() _ = clientFormat.channelCount } } // <rdar://problem/19746552> QoI: variable "used before being initialized" instead of "returned uninitialized" in address-only enum/struct struct AddressOnlyStructWithInit<T, U> { let a : T? let b : U? // expected-note {{'self.b' not initialized}} init(a : T) { self.a = a } // expected-error {{return from initializer without initializing all stored properties}} } enum AddressOnlyEnumWithInit<T> { case X(T), Y init() { } // expected-error {{return from enum initializer method without storing to 'self'}} } // <rdar://problem/20135113> QoI: enum failable init that doesn't assign to self produces poor error enum MyAwesomeEnum { case One, Two init?() { }// expected-error {{return from enum initializer method without storing to 'self'}} } // <rdar://problem/20679379> DI crashes on initializers on protocol extensions extension SomeProtocol { init?() { let a = self // expected-error {{variable 'self' used before being initialized}} self = a } init(a : Int) { } // expected-error {{protocol extension initializer never chained to 'self.init'}} init(c : Float) { protoMe() // expected-error {{variable 'self' used before being initialized}} } // expected-error {{protocol extension initializer never chained to 'self.init'}} } // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { // expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} let x = 0 // expected-note {{initial value already provided in 'let' declaration}} } extension LValueCheck { init(newY: Int) { x = 42 // expected-error {{immutable value 'self.x' may only be initialized once}} } } // <rdar://problem/20477982> Accessing let-property with default value in init() can throw spurious error struct DontLoadFullStruct { let x: Int = 1 let y: Int init() { y = x // ok! } } func testReassignment() { let c : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} c = 12 c = 32 // expected-error {{immutable value 'c' may only be initialized once}} _ = c } // <rdar://problem/21295093> Swift protocol cannot implement default initializer protocol ProtocolInitTest { init() init(a : Int) var i: Int { get set } } extension ProtocolInitTest { init() { } // expected-error {{protocol extension initializer never chained to 'self.init'}} init(b : Float) { self.init(a: 42) // ok } // <rdar://problem/21684596> QoI: Poor DI diagnostic in protocol extension initializer init(test1 ii: Int) { i = ii // expected-error {{'self' used before self.init call}} self.init() } init(test2 ii: Int) { self = unsafeBitCast(0, to: Self.self) i = ii } init(test3 ii: Int) { i = ii // expected-error {{'self' used before chaining to another self.init requirement}} self = unsafeBitCast(0, to: Self.self) } init(test4 ii: Int) { i = ii // expected-error {{'self' used before chaining to another self.init requirement}} } // expected-error {{protocol extension initializer never chained to 'self.init'}} } // <rdar://problem/22436880> Function accepting UnsafeMutablePointer is able to change value of immutable value func bug22436880(_ x: UnsafeMutablePointer<Int>) {} func test22436880() { let x: Int x = 1 bug22436880(&x) // expected-error {{immutable value 'x' may not be passed inout}} } // sr-184 let x: String? // expected-note 2 {{constant defined here}} print(x?.characters.count as Any) // expected-error {{constant 'x' used before being initialized}} print(x!) // expected-error {{constant 'x' used before being initialized}} // <rdar://problem/22723281> QoI: [DI] Misleading error from Swift compiler when using an instance method in init() protocol PMI { func getg() } extension PMI { func getg() {} } class WS: PMI { final let x: String // expected-note {{'self.x' not initialized}} init() { getg() // expected-error {{use of 'self' in method call 'getg' before all stored properties are initialized}} self.x = "foo" } } // <rdar://problem/23013334> DI QoI: Diagnostic claims that property is being used when it actually isn't class r23013334 { var B: Int // expected-note {{'self.B' not initialized}} var A: String init(A: String) throws { self.A = A self.A.withCString { cString -> () in // expected-error {{'self' captured by a closure before all members were initialized}} print(self.A) return () } self.B = 0 } } class r23013334Derived : rdar16119509_Base { var B: Int // expected-note {{'self.B' not initialized}} var A: String init(A: String) throws { self.A = A self.A.withCString { cString -> () in // expected-error {{'self' captured by a closure before all members were initialized}} print(self.A) return () } self.B = 0 } } // sr-1469 struct SR1469_Struct1 { let a: Int let b: Int // expected-note {{'self.b' not initialized}} init?(x: Int, y: Int) { self.a = x if y == 42 { return // expected-error {{return from initializer without initializing all stored properties}} } // many lines later self.b = y } } struct SR1469_Struct2 { let a: Int let b: Int // expected-note {{'self.b' not initialized}} init?(x: Int, y: Int) { self.a = x return // expected-error {{return from initializer without initializing all stored properties}} } } struct SR1469_Struct3 { let a: Int let b: Int // expected-note {{'self.b' not initialized}} init?(x: Int, y: Int) { self.a = x if y == 42 { self.b = y return } } // expected-error {{return from initializer without initializing all stored properties}} } enum SR1469_Enum1 { case A, B init?(x: Int) { if x == 42 { return // expected-error {{return from enum initializer method without storing to 'self'}} } // many lines later self = .A } } enum SR1469_Enum2 { case A, B init?() { return // expected-error {{return from enum initializer method without storing to 'self'}} } } enum SR1469_Enum3 { case A, B init?(x: Int) { if x == 42 { self = .A return } } // expected-error {{return from enum initializer method without storing to 'self'}} } class BadFooSuper { init() {} init(_ x: BadFooSuper) {} } class BadFooSubclass: BadFooSuper { override init() { super.init(self) // expected-error {{'self' used before super.init call}} } }
apache-2.0
8011bc67be8e4c3a2d753018200be15b
25.681171
138
0.618947
3.565387
false
false
false
false
cbpowell/MarqueeLabel
MarqueeLabel/MarqueeLabelDemoViewController.swift
1
12404
/** * Copyright (c) 2014 Charles Powell * * 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. */ // // MarqueeLabelDemoViewController.swift // MarqueeLabelDemo-Swift // import UIKit class MarqueeLabelDemoViewController : UIViewController { @IBOutlet weak var demoLabel1: MarqueeLabel! @IBOutlet weak var demoLabel2: MarqueeLabel! @IBOutlet weak var demoLabel3: MarqueeLabel! @IBOutlet weak var demoLabel4: MarqueeLabel! @IBOutlet weak var demoLabel5: MarqueeLabel! @IBOutlet weak var demoLabel6: MarqueeLabel! @IBOutlet weak var labelizeSwitch: UISwitch! @IBOutlet weak var holdLabelsSwitch: UISwitch! @IBOutlet weak var pauseLabelsSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Continuous Type demoLabel1.tag = 101 demoLabel1.type = .continuous demoLabel1.animationCurve = .easeInOut // Text string, fade length, leading buffer, trailing buffer, and scroll // duration for this label are set via Interface Builder's Attributes Inspector! // Reverse Continuous Type, with attributed string demoLabel2.tag = 201 demoLabel2.type = .continuousReverse demoLabel2.textAlignment = .right demoLabel2.lineBreakMode = .byTruncatingHead demoLabel2.speed = .duration(8.0) demoLabel2.fadeLength = 15.0 demoLabel2.leadingBuffer = 40.0 let attributedString2 = NSMutableAttributedString(string:"This is a long string, that's also an attributed string, which works just as well!") attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Helvetica-Bold", size: 18)!, range: NSMakeRange(0, 21)) attributedString2.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range: NSMakeRange(0, 14)) attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red: 0.234, green: 0.234, blue: 0.234, alpha: 1.0), range: NSMakeRange(0, attributedString2.length)) attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Light", size: 18)!, range: NSMakeRange(21, attributedString2.length - 21)) demoLabel2.attributedText = attributedString2 // Left/right example, with rate usage demoLabel3.tag = 301 demoLabel3.type = .leftRight demoLabel3.speed = .rate(60) demoLabel3.fadeLength = 10.0 demoLabel3.leadingBuffer = 30.0 demoLabel3.trailingBuffer = 20.0 demoLabel3.textAlignment = .center demoLabel3.text = "This is another long label that scrolls at a specific rate, rather than scrolling its length in a defined time window!" // Right/left example, with tap to scroll demoLabel4.tag = 401 demoLabel4.type = .rightLeft demoLabel4.textAlignment = .right demoLabel4.lineBreakMode = .byTruncatingHead demoLabel4.tapToScroll = true demoLabel4.trailingBuffer = 20.0 demoLabel4.text = "This label will not scroll until tapped, and then it performs its scroll cycle only once. Tap me!" // Continuous, with tap to pause demoLabel5.tag = 501 demoLabel5.type = .continuousReverse demoLabel5.speed = .duration(10) demoLabel5.fadeLength = 10.0 demoLabel5.leadingBuffer = 40.0 demoLabel5.trailingBuffer = 30.0 demoLabel5.text = "This text is long, and can be paused with a tap - handled via a UIGestureRecognizer!" demoLabel5.isUserInteractionEnabled = true // Don't forget this, otherwise the gesture recognizer will fail (UILabel has this as NO by default) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(pauseTap)) tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.numberOfTouchesRequired = 1 demoLabel5.addGestureRecognizer(tapRecognizer) // Continuous, with attributed text demoLabel6.tag = 601 demoLabel6.type = .continuous demoLabel6.speed = .duration(15.0) demoLabel6.fadeLength = 10.0 demoLabel6.trailingBuffer = 30.0 let attributedString6 = NSMutableAttributedString(string:"This is a long, attributed string, that's set up to loop in a continuous fashion!") attributedString6.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red: 0.123, green: 0.331, blue: 0.657, alpha: 1.000), range: NSMakeRange(0,34)) attributedString6.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red: 0.657, green: 0.096, blue: 0.088, alpha: 1.000), range: NSMakeRange(34, attributedString6.length - 34)) attributedString6.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Light", size:18.0)!, range: NSMakeRange(0, 16)) attributedString6.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Light", size:18.0)!, range: NSMakeRange(33, attributedString6.length - 33)) demoLabel6.attributedText = attributedString6; } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // If you have trouble with MarqueeLabel instances not automatically scrolling, implement the // viewWillAppear bulk method as seen below. This will attempt to restart scrolling on all // MarqueeLabels associated (in the view hierarchy) with the calling view controller // MarqueeLabel.controllerViewWillAppear(self) // Or.... (see below) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Or you could use viewDidAppear bulk method - try both to see which works best for you! // MarqueeLabel.controllerViewDidAppear(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeLabelTexts(_ sender: AnyObject) { // Use demoLabel1 tag to store "state" if (demoLabel1.tag == 101) { demoLabel1.text = "This label is not as long." demoLabel3.text = "This is a short, centered label." let attributedString2 = NSMutableAttributedString(string: "This is a different longer string, but still an attributed string, with new different attributes!") attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: NSMakeRange(0, attributedString2.length)) attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Helvetica-Bold", size:18.0)!, range:NSMakeRange(0, attributedString2.length)) attributedString2.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor(white:0.600, alpha:1.000), range:NSMakeRange(0,33)) attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Light", size:18.0)!, range:NSMakeRange(19, attributedString2.length - 19)) demoLabel2.attributedText = attributedString2; let attributedString6 = NSMutableAttributedString(string: "This is a different, longer, attributed string, that's set up to loop in a continuous fashion!") attributedString6.addAttribute(NSAttributedString.Key.foregroundColor, value:UIColor(red:0.657, green:0.078, blue:0.067, alpha:1.000), range:NSMakeRange(0,attributedString6.length)) attributedString6.addAttribute(NSAttributedString.Key.font, value:UIFont(name: "HelveticaNeue-Light", size:18.0)!, range:NSMakeRange(0, 16)) attributedString6.addAttribute(NSAttributedString.Key.font, value:UIFont(name: "HelveticaNeue-Light", size:18.0)!, range:NSMakeRange(33, attributedString6.length - 33)) attributedString6.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red:0.123, green:0.331, blue:0.657, alpha:1.000), range:NSMakeRange(33, attributedString6.length - 33)) demoLabel6.attributedText = attributedString6; demoLabel1.tag = 102; } else { demoLabel1.text = "This is a test of MarqueeLabel - the text is long enough that it needs to scroll to see the whole thing."; demoLabel3.text = "That also scrolls left, then right, rather than in a continuous loop!" let attributedString2 = NSMutableAttributedString(string: "This is a long string, that's also an attributed string, which works just as well!") attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "Helvetica-Bold", size:18.0)!, range:NSMakeRange(0, 21)) attributedString2.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.lightGray, range:NSMakeRange(10,11)) attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red:0.234, green:0.234, blue:0.234, alpha:1.000), range:NSMakeRange(0,attributedString2.length)) attributedString2.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Light", size:18.0)!, range: NSMakeRange(21, attributedString2.length - 21)) demoLabel2.attributedText = attributedString2 let attributedString6 = NSMutableAttributedString(string: "This is a long, attributed string, that's set up to loop in a continuous fashion!") attributedString6.addAttribute(NSAttributedString.Key.foregroundColor, value:UIColor(red:0.123, green:0.331, blue:0.657, alpha:1.000), range:NSMakeRange(0,attributedString6.length)) attributedString6.addAttribute(NSAttributedString.Key.font, value:UIFont(name: "HelveticaNeue-Light", size:18.0)!, range:NSMakeRange(0, 16)) attributedString6.addAttribute(NSAttributedString.Key.font, value:UIFont(name: "HelveticaNeue-Light", size:18.0)!, range:NSMakeRange(33, attributedString6.length - 33)) demoLabel6.attributedText = attributedString6 demoLabel1.tag = 101; } } @objc func pauseTap(_ recognizer: UIGestureRecognizer) { let continuousLabel2 = recognizer.view as! MarqueeLabel if recognizer.state == .ended { continuousLabel2.isPaused ? continuousLabel2.unpauseLabel() : continuousLabel2.pauseLabel() } } @IBAction func labelizeSwitched(_ sender: UISwitch) { if sender.isOn { MarqueeLabel.controllerLabelsLabelize(self) } else { MarqueeLabel.controllerLabelsAnimate(self) } } @IBAction func holdLabelsSwitched(_ sender: UISwitch) { for pv in view.subviews as [UIView] { if let v = pv as? MarqueeLabel { v.holdScrolling = sender.isOn } } } @IBAction func togglePause(_ sender: UISwitch) { for pv in view.subviews as [UIView] { if let v = pv as? MarqueeLabel { sender.isOn ? v.pauseLabel() : v.unpauseLabel() } } } @IBAction func unwindModalPopoverSegue(_ segue: UIStoryboardSegue) { // Empty by design } }
mit
34090c049504f172040bf85c477f71a5
53.403509
202
0.694453
4.623183
false
false
false
false
Mykhailo-Vorontsov-owo/OfflineCommute
OfflineCommute/Sources/UI/Scenes/StationsListViewController.swift
1
18929
// // ViewController.swift // OfflineCommute // // Created by Mykhailo Vorontsov on 27/02/2016. // Copyright © 2016 Mykhailo Vorontsov. All rights reserved. // import UIKit import CoreData //import MapKit import Mapbox import CoreLocation private struct Constants { static let CellReuseID = "Cell" static let pinViewReuseID = "Pin" static let animationDuration = 0.5 static let centerCoordinate = CLLocationCoordinate2DMake(51.5085300, -0.1257400) static let londondBounds = MGLCoordinateBoundsMake(CLLocationCoordinate2DMake(51.453749000320812, -0.29103857112860965), CLLocationCoordinate2DMake(51.561333843050079, 0.057506231562911125)) static let maxZoomLevel = 15 as Double static let minZoomLevel = 11 as Double } //extension MKAnnotation where Self:DockStation { //extension MGLAnnotation where Self:DockStation { extension DockStation: MGLAnnotation { var coordinate: CLLocationCoordinate2D { get { return CLLocationCoordinate2DMake(latitude.doubleValue, longitude.doubleValue) } } var subtitle: String? { get { let available = self.bikesAvailable?.integerValue ?? 0 let free = self.vacantPlaces?.integerValue ?? 0 return "bikes: \(available) / free: \(free)" } } } class StationsListViewController: LocalizableViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITabBarDelegate { lazy var progressView: UIProgressView! = { let progressView = UIProgressView(progressViewStyle: .Default) let container = self.curtainView let frame = container.bounds.size progressView.frame = CGRectMake(frame.width / 4, frame.height * 0.75, frame.width / 2, 10) progressView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] container.addSubview(progressView) return progressView }() lazy var curtainView: UIView! = { let container = self.mapViewContainer let curtainView = UIView(frame: container.bounds) curtainView.backgroundColor = UIColor.whiteColor() curtainView.alpha = 0.5 curtainView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] curtainView.hidden = true container.addSubview(curtainView) return curtainView }() @IBOutlet weak var mapViewContainer: UIView! @IBOutlet weak var tableView: UITableView! { didSet { tableView.tableFooterView = UIView() } } lazy var mapView:MGLMapView = { // let mapView = MGLMapView(frame: self.mapViewContainer.bounds) // let styleURL1 = NSBundle.mainBundle().URLForResource("LondonOSCBright", withExtension: "mbtiles") // let styleURL = NSBundle.mainBundle().URLForResource("LondonMapStyle", withExtension: "mbtiles") // let styleURL = NSURL(string:"https://www.mapbox.com/ios-sdk/files/mapbox-raster-v8.json"); let mapView = MGLMapView(frame: self.mapViewContainer.bounds, styleURL: MGLStyle.darkStyleURLWithVersion(9)) // let mapView = MGLMapView(frame: self.mapViewContainer.bounds, styleURL: mapURL) // mapView.setCenterCoordinate(Constants.centerCoordinate, zoomLevel:14, animated:true) mapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] mapView.delegate = self mapView.maximumZoomLevel = Constants.maxZoomLevel mapView.minimumZoomLevel = Constants.minZoomLevel mapView.setVisibleCoordinateBounds(Constants.londondBounds, animated:false) mapView.rotateEnabled = false // Setup offline pack notification handlers. NSNotificationCenter.defaultCenter().addObserver(self, selector: "offlinePackProgressDidChange:", name: MGLOfflinePackProgressChangedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "offlinePackDidReceiveError:", name: MGLOfflinePackErrorNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "offlinePackDidReceiveMaximumAllowedMapboxTiles:", name: MGLOfflinePackMaximumMapboxTilesReachedNotification, object: nil) return mapView }() deinit { // Remove offline pack observers. NSNotificationCenter.defaultCenter().removeObserver(self) } lazy var locationManager = { return CLLocationManager() }() lazy var dataManager:CoreDataManager = { return AppDelegate.sharedInstance.coreDataManager }() lazy var syncManager:DataRetrievalOperationManager = { return AppDelegate.sharedInstance.dataOperationManager }() lazy var dateFormatter:NSDateFormatter = { let formatter = NSDateFormatter() return formatter }() lazy var dateCalendar:NSCalendar = { return NSCalendar.currentCalendar() // let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! // return calendar }() var currentLocationAnnotation:MGLAnnotation? lazy var resultsController:NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "DockStation") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "distance", ascending: true), NSSortDescriptor(key: "sid", ascending: true)] // fetchRequest.predicate = NSPredicate(format: "distance < 1000", argumentArray: nil) let context:NSManagedObjectContext = self.dataManager.mainContext let controller:NSFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) controller.delegate = self do { try controller.performFetch() } catch { } return controller }() } // MARK: -Overrides extension StationsListViewController { override func viewDidLoad() { super.viewDidLoad() mapViewContainer.addSubview(mapView) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // mapView.showsUserLocation = true // mapView.setUserTrackingMode(.FollowWithHeading, animated: true) } override func viewDidAppear(animated: Bool) { // let manager = CLLocationManager() // manager.requestWhenInUseAuthorization() // locationManager = manager locationManager.requestWhenInUseAuthorization() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.refresh() } } } // MARK: -Actions extension StationsListViewController { @IBAction func refresh() { let netOperation = DockStationsSyncOperation() let fileOperation = DockStationFileOperation() let distanceOpeartion = UpdateDistanceSyncOperation(center: CLLocationCoordinate2DMake( 51.5085300, -0.1257400)) fileOperation.addDependency(netOperation) distanceOpeartion.addDependency(netOperation) distanceOpeartion.addDependency(fileOperation) syncManager.addOperations([netOperation, fileOperation, distanceOpeartion]) { (success, results, error) -> Void in print("Data fetching completed") } } @IBAction func switchToList() { tableView.hidden = false UIView.animateWithDuration(Constants.animationDuration, animations: { () -> Void in self.tableView.alpha = 0.7 }){ (completed) -> Void in // self.mapView.hidden = true } } @IBAction func switchToMap() { self.mapView.hidden = false UIView.animateWithDuration(Constants.animationDuration, animations: { () -> Void in self.tableView.alpha = 0.0 }) { (completed) -> Void in self.tableView.hidden = true } } @IBAction func showCurrentLocation(sender: AnyObject) { // self.mapView.setUserTrackingMode(.FollowWithHeading, animated: true) } } // MARK: -UITableViewDelegate extension StationsListViewController { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return resultsController.fetchedObjects?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CellReuseID, forIndexPath: indexPath) as? DockStationCell, let station = resultsController.objectAtIndexPath(indexPath) as? DockStation else { return UITableViewCell(style: .Default, reuseIdentifier: nil) } cell.nameLabel.text = station.title cell.vacantPlacesLabel.text = station.vacantPlaces?.stringValue ?? "-" cell.bikesAvalialbleLabel.text = station.bikesAvailable?.stringValue ?? "-" cell.distanceLabel.text = String((Int(station.distance ?? 0.0))) + "m" ?? "-" // NSDateComponents *components = [c components:NSHourCalendarUnit fromDate:d2 toDate:d1 options:0]; // NSInteger diff = components.minute; if (nil != station.updateDate) { cell.updateTimeLabel.text = stringForNowSinceDate(station.updateDate) } else { cell.updateTimeLabel.text = "" } return cell } func stringForNowSinceDate(date:NSDate) -> String{ // let dateComponents = dateCalendar.components([.Minute , .Hour, .Day], fromDate: date) let dateComponents = dateCalendar.components([.Minute , .Hour, .Day], fromDate: date, toDate: NSDate(), options: .MatchStrictly) var dateString = "Updated:" if dateComponents.day > 0 { dateString += "\(dateComponents.day)d " } if dateComponents.hour > 0 { dateString += "\(dateComponents.hour)h " } if dateComponents.minute > 0 { dateString += "\(dateComponents.minute)m " } dateString += "ago" return dateString } } //MARKL -NSFetchedResultsControllerDelegate extension StationsListViewController { func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { guard let anObject = anObject as? DockStation else { return } switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Left) // mapView.addAnnotation(anObject) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Left) // mapView.removeAnnotation(anObject) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Left) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Left) case .Update: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) mapView.removeAnnotation(anObject) // mapView.addAnnotation(anObject) } } } // MARK: - MKMapViewDelegate extension StationsListViewController { // func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { // guard let annotation = annotation as? DockStation else { // return nil // } // let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.pinViewReuseID) // // view.canShowCallout = true // // let bikesCount = annotation.bikesAvailable?.integerValue ?? 0 // let dockCount = annotation.vacantPlaces?.integerValue ?? 0 // // if bikesCount < 1 && dockCount < 1 { // view.pinTintColor = UIColor.lightGrayColor() // } else if bikesCount < 1 { // view.pinTintColor = UIColor.yellowColor() // } else if dockCount < 1 { // view.pinTintColor = UIColor.blueColor() // } else { // view.pinTintColor = UIColor.greenColor() // } // // return view // } // func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { // // } } // MARK: -UITabbarDelegate extension StationsListViewController { func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { switch item.tag { case 1: switchToMap() case 0: switchToList() default: break } } } //MARK: -UISearchBarDelegate extension StationsListViewController:UISearchBarDelegate { func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { guard let text = searchBar.text else { assert(true, "Text field text is nil!") return } let geoOperation = GeocodingSyncOperation(request: text) syncManager.addOperations([geoOperation]) { [weak self] (success, results, error) -> Void in guard let guardSelf = self else { return } guard success, let firstPlacemark = results.first as? CLPlacemark, let coordinate = firstPlacemark.location?.coordinate else { return } // guardSelf.mapView.setUserTrackingMode(.None, animated: false) let annotation = MGLPointAnnotation() annotation.coordinate = coordinate if nil != guardSelf.currentLocationAnnotation { guardSelf.mapView.removeAnnotation(guardSelf.currentLocationAnnotation!) } guardSelf.mapView.addAnnotation(annotation) guardSelf.currentLocationAnnotation = annotation guardSelf.mapView.showAnnotations([annotation], animated: true) let distanceOpeartion = UpdateDistanceSyncOperation(center: guardSelf.currentLocationAnnotation!.coordinate) guardSelf.syncManager.addOperations([distanceOpeartion], completionBLock: { (success, results, error) -> Void in }) } } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.showsCancelButton = false } } //MARK: -Notification progress observer extension StationsListViewController { func showAlert(message:String) { let alert = UIAlertController(title: "MapBox", message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: { (action) in alert.dismissViewControllerAnimated(true, completion: nil) })) print("Presenting message: \(message)") self.presentViewController(alert, animated: true, completion: nil) } // MARK: - MGLOfflinePack notification handlers func offlinePackProgressDidChange(notification: NSNotification) { // Get the offline pack this notification is regarding, // and the associated user info for the pack; in this case, `name = My Offline Pack` if let pack = notification.object as? MGLOfflinePack, userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(pack.context) as? [String: String] { curtainView.hidden = false let progress = pack.progress // or notification.userInfo![MGLOfflinePackProgressUserInfoKey]!.MGLOfflinePackProgressValue let completedResources = progress.countOfResourcesCompleted let expectedResources = progress.countOfResourcesExpected // Calculate current progress percentage. let progressPercentage = Float(completedResources) / Float(expectedResources) progressView.progress = progressPercentage // If this pack has finished, print its size and resource count. if completedResources == expectedResources { let byteCount = NSByteCountFormatter.stringFromByteCount(Int64(pack.progress.countOfBytesCompleted), countStyle: NSByteCountFormatterCountStyle.Memory) let message = "Offline pack “\(userInfo["name"])” completed: \(byteCount), \(completedResources) resources" print(message) showAlert(message) curtainView.hidden = true } else { // Otherwise, print download/verification progress. print("Offline pack “\(userInfo["name"])” has \(completedResources) of \(expectedResources) resources — \(progressPercentage * 100)%.") } } } func offlinePackDidReceiveError(notification: NSNotification) { var errorMessage = "" if let pack = notification.object as? MGLOfflinePack, userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(pack.context) as? [String: String], error = notification.userInfo?[MGLOfflinePackErrorUserInfoKey] as? NSError { errorMessage = "Offline pack “\(userInfo["name"])” received error: \(error.localizedFailureReason)" print(errorMessage) } showAlert(errorMessage) } func offlinePackDidReceiveMaximumAllowedMapboxTiles(notification: NSNotification) { if let pack = notification.object as? MGLOfflinePack, userInfo = NSKeyedUnarchiver.unarchiveObjectWithData(pack.context) as? [String: String], maximumCount = notification.userInfo?[MGLOfflinePackMaximumCountUserInfoKey]?.unsignedLongLongValue { let message = "Offline pack “\(userInfo["name"])” reached limit of \(maximumCount) tiles." print(message) showAlert(message) } } } extension StationsListViewController: MGLMapViewDelegate { func mapViewDidFinishLoadingMap(mapView: MGLMapView) { // Start downloading tiles and resources for z13-16. startOfflinePackDownload() } func mapView(mapView: MGLMapView, regionDidChangeAnimated animated: Bool) { let message = "New region:\(mapView.visibleCoordinateBounds)" print(message) // showAlert(message) } func startOfflinePackDownload() { // Create a region that includes the current viewport and any tiles needed to view it when zoomed further in. // Because tile count grows exponentially with the maximum zoom level, you should be conservative with your `toZoomLevel` setting. let region = MGLTilePyramidOfflineRegion( styleURL: mapView.styleURL, bounds: Constants.londondBounds, fromZoomLevel: Constants.minZoomLevel, toZoomLevel: Constants.maxZoomLevel ) let storage = MGLOfflineStorage.sharedOfflineStorage() guard storage.packs?.count < 1 else { return } // Store some data for identification purposes alongside the downloaded resources. let userInfo = ["name": "My Offline Pack"] let context = NSKeyedArchiver.archivedDataWithRootObject(userInfo) // Create and register an offline pack with the shared offline storage object. storage.addPackForRegion(region, withContext: context) { (pack, error) in guard error == nil else { // The pack couldn’t be created for some reason. print("Error: \(error?.localizedFailureReason)") return } // Start downloading. pack!.resume() } } }
mit
6fcb624878c1264251a19d229354261f
33.630037
209
0.709118
4.873196
false
false
false
false
abertelrud/swift-package-manager
Sources/LLBuildManifest/BuildManifest.swift
2
6367
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2021 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 Basics import struct TSCBasic.AbsolutePath public struct BuildManifest { public typealias TargetName = String public typealias CmdName = String /// The targets in the manifest. public private(set) var targets: [TargetName: Target] = [:] /// The commands in the manifest. public private(set) var commands: [CmdName: Command] = [:] /// The default target to build. public var defaultTarget: String = "" public init() { } public func getCmdToolMap<T: ToolProtocol>(kind: T.Type) -> [CmdName: T] { var result = [CmdName: T]() for (cmdName, cmd) in commands { if let tool = cmd.tool as? T { result[cmdName] = tool } } return result } public mutating func createTarget(_ name: TargetName) { guard !targets.keys.contains(name) else { return } targets[name] = Target(name: name, nodes: []) } public mutating func addNode(_ node: Node, toTarget target: TargetName) { targets[target, default: Target(name: target, nodes: [])].nodes.append(node) } public mutating func addPhonyCmd( name: String, inputs: [Node], outputs: [Node] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = PhonyTool(inputs: inputs, outputs: outputs) commands[name] = Command(name: name, tool: tool) } public mutating func addTestDiscoveryCmd( name: String, inputs: [Node], outputs: [Node] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = TestDiscoveryTool(inputs: inputs, outputs: outputs) commands[name] = Command(name: name, tool: tool) } public mutating func addTestEntryPointCmd( name: String, inputs: [Node], outputs: [Node] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = TestEntryPointTool(inputs: inputs, outputs: outputs) commands[name] = Command(name: name, tool: tool) } public mutating func addCopyCmd( name: String, inputs: [Node], outputs: [Node] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = CopyTool(inputs: inputs, outputs: outputs) commands[name] = Command(name: name, tool: tool) } public mutating func addPkgStructureCmd( name: String, inputs: [Node], outputs: [Node] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = PackageStructureTool(inputs: inputs, outputs: outputs) commands[name] = Command(name: name, tool: tool) } public mutating func addShellCmd( name: String, description: String, inputs: [Node], outputs: [Node], arguments: [String], environment: EnvironmentVariables = .empty(), workingDirectory: String? = nil, allowMissingInputs: Bool = false ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = ShellTool( description: description, inputs: inputs, outputs: outputs, arguments: arguments, environment: environment, workingDirectory: workingDirectory, allowMissingInputs: allowMissingInputs ) commands[name] = Command(name: name, tool: tool) } public mutating func addSwiftFrontendCmd( name: String, moduleName: String, description: String, inputs: [Node], outputs: [Node], arguments: [String] ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = SwiftFrontendTool( moduleName: moduleName, description: description, inputs: inputs, outputs: outputs, arguments: arguments ) commands[name] = Command(name: name, tool: tool) } public mutating func addClangCmd( name: String, description: String, inputs: [Node], outputs: [Node], arguments: [String], dependencies: String? = nil ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = ClangTool( description: description, inputs: inputs, outputs: outputs, arguments: arguments, dependencies: dependencies ) commands[name] = Command(name: name, tool: tool) } public mutating func addSwiftCmd( name: String, inputs: [Node], outputs: [Node], executable: AbsolutePath, moduleName: String, moduleAliases: [String: String]?, moduleOutputPath: AbsolutePath, importPath: AbsolutePath, tempsPath: AbsolutePath, objects: [AbsolutePath], otherArguments: [String], sources: [AbsolutePath], isLibrary: Bool, wholeModuleOptimization: Bool ) { assert(commands[name] == nil, "already had a command named '\(name)'") let tool = SwiftCompilerTool( inputs: inputs, outputs: outputs, executable: executable, moduleName: moduleName, moduleAliases: moduleAliases, moduleOutputPath: moduleOutputPath, importPath: importPath, tempsPath: tempsPath, objects: objects, otherArguments: otherArguments, sources: sources, isLibrary: isLibrary, wholeModuleOptimization: wholeModuleOptimization ) commands[name] = Command(name: name, tool: tool) } }
apache-2.0
64443e356f6cd7724a318e48b51a589c
31.484694
84
0.572954
4.647445
false
false
false
false
FlexMonkey/Filterpedia
Filterpedia/customFilters/LensFlare.swift
1
13924
// // LensFlare.swift // Filterpedia // // Created by Simon Gladman on 29/04/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // Thanks to: http://www.playchilla.com/how-to-check-if-a-point-is-inside-a-hexagon // // 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 CoreImage class LensFlare: CIFilter { var inputOrigin = CIVector(x: 150, y: 150) var inputSize = CIVector(x: 640, y: 640) var inputColor = CIVector(x: 0.5, y: 0.2, z: 0.3) var inputReflectionBrightness: CGFloat = 0.25 var inputPositionOne: CGFloat = 0.15 var inputPositionTwo: CGFloat = 0.3 var inputPositionThree: CGFloat = 0.4 var inputPositionFour: CGFloat = 0.45 var inputPositionFive: CGFloat = 0.6 var inputPositionSix: CGFloat = 0.75 var inputPositionSeven: CGFloat = 0.8 var inputReflectionSizeZero: CGFloat = 20 var inputReflectionSizeOne: CGFloat = 25 var inputReflectionSizeTwo: CGFloat = 12.5 var inputReflectionSizeThree: CGFloat = 5 var inputReflectionSizeFour: CGFloat = 20 var inputReflectionSizeFive: CGFloat = 35 var inputReflectionSizeSix: CGFloat = 40 var inputReflectionSizeSeven: CGFloat = 20 override var attributes: [String : AnyObject] { let positions: [String : AnyObject] = [ "inputPositionOne": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.15, kCIAttributeDisplayName: "Position One", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionTwo": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.3, kCIAttributeDisplayName: "Position Two", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionThree": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.4, kCIAttributeDisplayName: "Position Three", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionFour": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.45, kCIAttributeDisplayName: "Position Four", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionFive": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.6, kCIAttributeDisplayName: "Position Five", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionSix": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.75, kCIAttributeDisplayName: "Position Six", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputPositionSeven": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.8, kCIAttributeDisplayName: "Position Seven", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], ] let sizes: [String : AnyObject] = [ "inputReflectionSizeZero": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Size Zero", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeOne": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 25, kCIAttributeDisplayName: "Size One", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeTwo": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 12.5, kCIAttributeDisplayName: "Size Two", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeThree": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 5, kCIAttributeDisplayName: "Size Three", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeFour": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Size Four", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeFive": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 35, kCIAttributeDisplayName: "Size Five", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeSix": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 40, kCIAttributeDisplayName: "Size Six", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputReflectionSizeSeven": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Size Seven", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputSize": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Image Size", kCIAttributeDefault: CIVector(x: 640, y: 640), kCIAttributeType: kCIAttributeTypeOffset] ] let attributes: [String : AnyObject] = [ kCIAttributeFilterDisplayName: "Lens Flare", "inputOrigin": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Light Origin", kCIAttributeDefault: CIVector(x: 150, y: 150), kCIAttributeType: kCIAttributeTypePosition], "inputColor": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Color", kCIAttributeDefault: CIVector(x: 0.5, y: 0.2, z: 0.3), kCIAttributeType: kCIAttributeTypeColor], "inputReflectionBrightness": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.25, kCIAttributeDisplayName: "Reflection Brightness", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar] ] return attributes + positions + sizes } let sunbeamsFilter = CIFilter(name: "CISunbeamsGenerator", withInputParameters: ["inputStriationStrength": 0]) var colorKernel = CIColorKernel(string: "float brightnessWithinHexagon(vec2 coord, vec2 center, float v)" + "{" + " float h = v * sqrt(3.0);" + " float x = abs(coord.x - center.x); " + " float y = abs(coord.y - center.y); " + " float brightness = (x > h || y > v * 2.0) ? 0.0 : smoothstep(0.5, 1.0, (distance(destCoord(), center) / (v * 2.0))); " + " return ((2.0 * v * h - v * x - h * y) >= 0.0) ? brightness : 0.0;" + "}" + "kernel vec4 lensFlare(vec2 center0, vec2 center1, vec2 center2, vec2 center3, vec2 center4, vec2 center5, vec2 center6, vec2 center7," + " float size0, float size1, float size2, float size3, float size4, float size5, float size6, float size7, " + " vec3 color, float reflectionBrightness) " + "{" + " float reflectionO = brightnessWithinHexagon(destCoord(), center0, size0); " + " float reflection1 = reflectionO + brightnessWithinHexagon(destCoord(), center1, size1); " + " float reflection2 = reflection1 + brightnessWithinHexagon(destCoord(), center2, size2); " + " float reflection3 = reflection2 + brightnessWithinHexagon(destCoord(), center3, size3); " + " float reflection4 = reflection3 + brightnessWithinHexagon(destCoord(), center4, size4); " + " float reflection5 = reflection4 + brightnessWithinHexagon(destCoord(), center5, size5); " + " float reflection6 = reflection5 + brightnessWithinHexagon(destCoord(), center6, size6); " + " float reflection7 = reflection6 + brightnessWithinHexagon(destCoord(), center7, size7); " + " return vec4(color * reflection7 * reflectionBrightness, reflection7); " + "}" ) override var outputImage: CIImage! { guard let colorKernel = colorKernel else { return nil } let extent = CGRect(x: 0, y: 0, width: inputSize.X, height: inputSize.Y) let center = CIVector(x: inputSize.X / 2, y: inputSize.Y / 2) let localOrigin = CIVector(x: center.X - inputOrigin.X, y: center.Y - inputOrigin.Y) let reflectionZero = CIVector(x: center.X + localOrigin.X, y: center.Y + localOrigin.Y) let reflectionOne = inputOrigin.interpolateTo(reflectionZero, value: inputPositionOne) let reflectionTwo = inputOrigin.interpolateTo(reflectionZero, value: inputPositionTwo) let reflectionThree = inputOrigin.interpolateTo(reflectionZero, value: inputPositionThree) let reflectionFour = inputOrigin.interpolateTo(reflectionZero, value: inputPositionFour) let reflectionFive = inputOrigin.interpolateTo(reflectionZero, value: inputPositionFive) let reflectionSix = inputOrigin.interpolateTo(reflectionZero, value: inputPositionSix) let reflectionSeven = inputOrigin.interpolateTo(reflectionZero, value: inputPositionSeven) sunbeamsFilter?.setValue(inputOrigin, forKeyPath: kCIInputCenterKey) sunbeamsFilter?.setValue(inputColor, forKey: kCIInputColorKey) let sunbeamsImage = sunbeamsFilter!.outputImage! let arguments = [ reflectionZero, reflectionOne, reflectionTwo, reflectionThree, reflectionFour, reflectionFive, reflectionSix, reflectionSeven, inputReflectionSizeZero, inputReflectionSizeOne, inputReflectionSizeTwo, inputReflectionSizeThree, inputReflectionSizeFour, inputReflectionSizeFive, inputReflectionSizeSix, inputReflectionSizeSeven, inputColor, inputReflectionBrightness] let lensFlareImage = colorKernel.applyWithExtent( extent, arguments: arguments)?.imageByApplyingFilter("CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: 2]) return lensFlareImage?.imageByApplyingFilter( "CIAdditionCompositing", withInputParameters: [kCIInputBackgroundImageKey: sunbeamsImage]).imageByCroppingToRect(extent) } } func + <T, U>(left: Dictionary<T, U>, right: Dictionary<T, U>) -> Dictionary<T, U> { var target = Dictionary<T, U>() for (key, value) in left { target[key] = value } for (key, value) in right { target[key] = value } return target }
gpl-3.0
d241511a9cb4bc180694e722e75272dd
43.340764
145
0.602815
5.419619
false
false
false
false
moonknightskye/Luna
Luna/WKWebView+extension.swift
1
7588
// // WKWebView+extension.swift // Luna // // Created by Mart Civil on 2017/02/21. // Copyright © 2017年 salesforce.com. All rights reserved. // //【swift3】WKWebViewでUIGestureRecognizerを使う //https://qiita.com/KOH_TA/items/769fda8b9c7d19e991e0 import Foundation import WebKit extension WKWebView { convenience init( webview_id:Int ) { let contentController = WKUserContentController() contentController.add( Shared.shared.ViewController, name: "webcommand" ) var jsScript = "" do { var jsFile = try File(fileId: File.generateID(), bundle: "apollo11.js", path: "") jsScript.append(try jsFile.getStringContent() ?? "") jsFile = try File(fileId: File.generateID(), bundle: "Sputnik1.js", path: "") jsScript.append(try jsFile.getStringContent() ?? "") jsScript.append("(function(){ window.sputnik1 = new window.Sputnik1(); })();") } catch let error as NSError { print( error.localizedDescription ) } let params:NSMutableDictionary = NSMutableDictionary() params.setValue( webview_id, forKey: "webview_id" ); params.setValue( "all", forKey: "source_global_id" ); params.setValue( APP_VERSION, forKey: "app_version" ); jsScript.append( WKWebView.generateJavaScript(commandName: "init", params: params) ) WKWebView.appendJavascript( script: jsScript, contentController: contentController ) let config = WKWebViewConfiguration() config.userContentController = contentController self.init( frame:UIScreen.main.bounds, configuration: config ) self.navigationDelegate = Shared.shared.ViewController self.uiDelegate = Shared.shared.ViewController self.addObserver(self, forKeyPath: #keyPath(WKWebView.loading), options: .new, context: nil) self.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil) self.isOpaque = false self.scrollView.contentInsetAdjustmentBehavior = .never; self.scrollView.bounces = false } func load( bundlefilePath:URL, onSuccess:(()->())?=nil, onFail:((String)->())?=nil ){ self.load( NSURLRequest(url: bundlefilePath) as URLRequest ) if onSuccess != nil { onSuccess!() } } func load( docfilePath:URL, onSuccess:(()->())?=nil, onFail:((String)->())?=nil ){ self.loadFileURL( docfilePath, allowingReadAccessTo: FileManager.getDocumentsDirectoryPath()! ) if onSuccess != nil { onSuccess!() } } func load( url:URL, onSuccess:(()->())?=nil, onFail:((String)->())?=nil ){ self.load( URLRequest( url: url ) ) if onSuccess != nil { onSuccess!() } } private class func appendJavascript( script:String, contentController:WKUserContentController ) { contentController.addUserScript( WKUserScript( source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: false ) ) } private class func generateJavaScript( commandName:String, params: Any?=nil ) -> String { let command:NSMutableDictionary = NSMutableDictionary() command.setValue( commandName, forKey: "command" ); if( params != nil ) { command.setValue(params, forKey: "params") } return "(function(){ sputnik1.beamMessage(JSON.parse('\(Utility.shared.dictionaryToJSON(dictonary: command))')); })();" } func runJSCommand( commandName:String, params: NSDictionary, onComplete:((Any?, Error?)->Void)?=nil ) { DispatchQueue.main.async { let script = WKWebView.generateJavaScript( commandName: commandName, params: params ) self.evaluateJavaScript( script, completionHandler: onComplete ) } } func getManager() -> WebViewManager? { return WebViewManager.getManager( webview: self ) } open func removeFromSuperview( onSuccess:(()->())?=nil ) { if self.observationInfo != nil { self.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress)) self.removeObserver(self, forKeyPath: #keyPath(WKWebView.loading)) } //self.load(url: URL(string:"about:blank")!) super.removeFromSuperview() if onSuccess != nil { onSuccess!() } } func setProperty( property: NSDictionary, animation: NSDictionary?=nil, onSuccess:((Bool)->())?=nil ) { if animation != nil { var duration = 0.0 if let duration_val = animation!.value(forKey: "duration") as? Double { duration = duration_val } var delay = 0.0 if let delay_val = animation!.value(forKey: "delay") as? Double { delay = delay_val } UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseInOut, animations: { self.setProperty(property: property) }, completion: { finished in if onSuccess != nil { onSuccess!( finished ) } }) } else { self.setProperty(property: property) if onSuccess != nil { onSuccess!( true ) } } } private func setProperty( property: NSDictionary ) { if let frame = property.value(forKeyPath: "frame") as? NSDictionary { if let width = frame.value(forKeyPath: "width") as? CGFloat { self.frame.size.width = width } if let height = frame.value(forKeyPath: "height") as? CGFloat { self.frame.size.height = height } if let x = frame.value(forKeyPath: "x") as? CGFloat { self.frame.origin.x = x } if let y = frame.value(forKeyPath: "y") as? CGFloat { self.frame.origin.y = y } } if let alpha = property.value(forKeyPath: "opacity") as? CGFloat { self.alpha = alpha } if let isOpaque = property.value(forKeyPath: "isOpaque") as? Bool { self.isOpaque = isOpaque; } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } guard let change = change else { return } if let wkmanager = self.getManager() { switch keyPath { case "loading": // new:1 or 0 if let val = change[.newKey] as? Bool { if val { wkmanager.onLoad() } else { if self.estimatedProgress == 1 { //self.removeObserver(self, forKeyPath: #keyPath(WKWebView.loading)) wkmanager.onLoaded(isSuccess: true) } } } case "estimatedProgress": //DispatchQueue.main.async { wkmanager.onLoading(progress: self.estimatedProgress * 100) if self.estimatedProgress == 1 { //self.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress)) } //} default: break } } } }
gpl-3.0
184e2048dbdc16380f9e1363ffbe8675
36.676617
156
0.57573
4.808254
false
false
false
false
codestergit/swift
test/sil-func-extractor/basic.swift
3
4172
// Passing demangled name // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.foo" | %FileCheck %s -check-prefix=EXTRACT-FOO // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.X.test" | %FileCheck %s -check-prefix=EXTRACT-TEST // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.Vehicle.init" | %FileCheck %s -check-prefix=EXTRACT-INIT // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.Vehicle.now" | %FileCheck %s -check-prefix=EXTRACT-NOW // Passing mangled name // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic3fooSiyF" | %FileCheck %s -check-prefix=EXTRACT-FOO // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic1XV4testyyF" | %FileCheck %s -check-prefix=EXTRACT-TEST // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleCACSi1n_tcfc" | %FileCheck %s -check-prefix=EXTRACT-INIT // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleC3nowSiyF" | %FileCheck %s -check-prefix=EXTRACT-NOW // EXTRACT-FOO-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-FOO-LABEL: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-FOO: bb0: // EXTRACT-FOO-NEXT: %0 = integer_literal // EXTRACT-FOO-NEXT: %1 = struct $Int // EXTRACT-FOO-NEXT: return %1 : $Int // EXTRACT-TEST-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-TEST-LABEL: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-TEST: bb0(%0 : $X): // EXTRACT-TEST-NEXT: function_ref // EXTRACT-TEST-NEXT: function_ref @_T05basic3fooSiyF : $@convention(thin) () -> Int // EXTRACT-TEST-NEXT: apply // EXTRACT-TEST-NEXT: tuple // EXTRACT-TEST-NEXT: return // EXTRACT-INIT-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-INIT-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-INIT-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@owned Vehicle) -> Int { // EXTRACT-INIT-LABEL: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @owned Vehicle) -> @owned Vehicle { // EXTRACT-INIT: bb0 // EXTRACT-INIT-NEXT: ref_element_addr // EXTRACT-INIT-NEXT: store // EXTRACT-INIT-NEXT: return // EXTRACT-NOW-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-NOW-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-NOW-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-NOW-LABEL: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-NOW: bb0 // EXTRACT-NOW: ref_element_addr // EXTRACT-NOW-NEXT: load // EXTRACT-NOW-NEXT: return struct X { func test() { foo() } } class Vehicle { var numOfWheels: Int init(n: Int) { numOfWheels = n } func now() -> Int { return numOfWheels } } func foo() -> Int { return 7 }
apache-2.0
e1d9316c71bcb58331ee3fba5ccc16a9
50.506173
199
0.678332
3.034182
false
true
false
false
zsmzhu/MinCarouseView
MinCarouseViewDemo/SimpleDemo/SimpleDemo/ViewController.swift
1
1536
// // ViewController.swift // SimpleDemo // // Created by songmin.zhu on 16/4/6. // Copyright © 2016年 zhusongmin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var carouse1: MinCarouseView! override func viewDidLoad() { super.viewDidLoad() let imageArray = [ UIImage(named: "bamboo")!, UIImage(named: "plum blossom")!, UIImage(named: "lotus")! ] //storyboard创建 carouse1.imageArray = imageArray let urlArray = [ "http://d.lanrentuku.com/down/png/1307/jiqiren-wall-e/jiqiren-wall-e-04.png", "http://d.lanrentuku.com/down/png/1307/jiqiren-wall-e/jiqiren-wall-e-05.png", "http://d.lanrentuku.com/down/png/1307/jiqiren-wall-e/jiqiren-wall-e-03.png" ] // 代码创建 let carouse2Frame = CGRect( x: carouse1.frame.origin.x, y: carouse1.frame.height + 20.0, width: UIScreen.mainScreen().bounds.width - 40.0, height: 200.0) let carouse2 = MinCarouseView(frame: carouse2Frame, imageArray: urlArray, placeholder: UIImage(named: "placeholder")!) self.view.addSubview(carouse2) carouse2.scrollInterVal = 2.0 carouse2.tapClosure = { index in print(index) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
280210070b0d353bcf94cf2bb1502362
30.040816
126
0.599606
3.65625
false
false
false
false
BenziAhamed/Tracery
Playgrounds/Face Generator.playground/Contents.swift
1
6053
//: # Pixel Face Generator //: Powered by [Tracery](https://github.com/BenziAhamed/Tracery) import UIKit import SpriteKit import PlaygroundSupport import Tracery let view = SKView.init(frame: .init(x: 0, y: 0, width: 400, height: 400)) PlaygroundPage.current.liveView = view var colors:[String: UIColor] = [ "blk" : .black, "w": .white, "bg": UIColor(red:0.152, green:0.698, blue:0.962, alpha:1), "cheekcol": UIColor(hex: "f28fb2").withAlphaComponent(0.32), "skin-1": UIColor(hex: "ffcc80"), "skin-2": UIColor(hex: "ffb74d"), "skin-3": UIColor(hex: "ffa726"), "skin-4": UIColor(hex: "ff9800"), "skin-5": UIColor(hex: "fb8c00"), "skin-6": UIColor(hex: "f57c00"), "skin-8": UIColor(hex: "a1887f"), "skin-9": UIColor(hex: "8d6e63"), "skin-10": UIColor(hex: "795548"), "skin-11": UIColor(hex: "6d4c41"), "skin-12": UIColor(hex: "5d4037"), ] /*: Our face is generated in a 8x8 block. We will exclusively use methods as the main mechanism to render the face. For example, the `.block` method is used to render a solid colored rectangle at the coordinates specified. */ var tracery = Tracery {[ "face": "#.block(1,1,7,7,#skin#)#", "eyes": "#.set(2,4,w)# #.set(5,4,w)#", "neck": "#.xf(2,0,4,#skin-dark#)#", "mouth": "#.block(3,2,5,3,#lips#)#", "freckles": ["", "", "", "#.set(1,2,#skin-dark#)# #.set(6,3,#skin-dark#)#", "#.set(4,5,#skin-dark#)#", "#.xf(5,6,2,blk)#"], "cheeks": ["", "", "", "#.set(1,3,cheekcol)# #.set(6,3,cheekcol)#"], // various hairstyles "hair-neil": "#.block(1,7,7,8,blk)##.block(1,6,4,7,blk)#", "hair-latino" : "#.block(1,6,7,8,blk)##.set(4,6,blk)#", "hair-army2" : "#.block(1,7,7,8,blk)##.set(1,6,blk)##.set(3,6,blk)##.set(5,6,blk)#", "hair-army1" : "#.block(1,7,7,8,blk)#", "hair-chinese" : "#.block(0,3,1,8,blk)##.block(7,3,8,8,blk)##hair-army1##.set(3,6,blk)##.set(4,6,blk)#", "hair-fran": "#.yf(0,4,3,blk)##.xf(1,7,6,blk)##.xf(3,6,5,blk)##.xf(5,5,3,blk)##.set(6,4,blk)#", "hair-messi": "#.xf(1,7,6,blk)##.xf(0,6,4,blk)##.xf(5,6,2,blk)##.xf(4,5,2,blk)##.set(1,5,blk)#", "hair-alena": "#hair-army1# #.yf(0,3,4,blk)# #.yf(7,3,4,blk)# #.xf(0,6,4,blk)#", "hair-alice": "#hair-army1# #.yf(0,3,4,blk)# #.yf(7,3,4,blk)# #.yf(6,3,2,blk)# #.xf(2,5,2,blk)# #.set(4,6,blk)#", "hair-opts" : "neil latino army1 army2 fran messi alena alice".components(separatedBy: " "), // select a hair-style "initHair": "[hair:\\#hair-#hair-opts#\\#]", // select and set skin tone colors "initSkin": [ "[skin:skin-1][skin-dark:skin-2][lips:skin-3]", "[skin:skin-2][skin-dark:skin-3][lips:skin-4]", "[skin:skin-3][skin-dark:skin-4][lips:skin-5]", "[skin:skin-4][skin-dark:skin-5][lips:skin-6]", "[skin:skin-8][skin-dark:skin-9][lips:skin-10]", "[skin:skin-9][skin-dark:skin-10][lips:skin-11]", "[skin:skin-10][skin-dark:skin-11][lips:skin-12]", ], // init "init": "#initHair# #initSkin#", // render a random face "gen" : "#init# #face# #eyes# #neck# #mouth# #freckles# #cheeks# #hair.eval#", ]} class Scene : SKScene { var prevUpdateTime: TimeInterval? = nil var elapsed: CGFloat = 0 let grid = SKNode() var zpos: CGFloat = 0 override func didMove(to view: SKView) { size = view.frame.size backgroundColor = colors["bg"]! grid.position = CGPoint(x: 80, y: 80) addChild(grid) setupTracery() generateFace() } //: We create and attach the necessary methods to Tracery func setupTracery() { // fills a rectangular area // with a solid color func fillBlock(_ args: [String]) -> String { let sx = CGFloat(Double(args[0]) ?? 0) let sy = CGFloat(Double(args[1]) ?? 0) let ex = CGFloat(Double(args[2]) ?? 1) let ey = CGFloat(Double(args[3]) ?? 1) let color = colors[args[4]]! let size = CGSize(width: (ex - sx) * 30, height: (ey - sy) * 30) let block = SKSpriteNode(color: color, size: size) block.anchorPoint = .zero block.position = CGPoint.init(x: 30 * sx, y: 30 * sy) block.zPosition = zpos grid.addChild(block) return "" } tracery.add(method: "block") { _, args in return fillBlock(args) } // set an individial pixel tracery.add(method: "set") { _, args in let sx = Int(args[0]) ?? 0 let sy = Int(args[1]) ?? 0 let color = args[2] return fillBlock(["\(sx)","\(sy)","\(sx+1)","\(sy+1)",color]) } // line across x axis tracery.add(method: "xf") { _, args in let sx = Int(args[0]) ?? 0 let sy = Int(args[1]) ?? 0 let count = Int(args[2]) ?? 0 let color = args[3] return fillBlock(["\(sx)","\(sy)","\(sx+count)","\(sy+1)",color]) } // line across y axis tracery.add(method: "yf") { _, args in let sx = Int(args[0]) ?? 0 let sy = Int(args[1]) ?? 0 let count = Int(args[2]) ?? 0 let color = args[3] return fillBlock(["\(sx)","\(sy)","\(sx+1)","\(sy+count)",color]) } tracery.add(modifier: "eval") { input in return tracery.expand(input, maintainContext: false) } } func generateFace() { zpos = 0 grid.removeAllChildren() _ = tracery.expand("#gen#") } //: Generate a new face every second override func update(_ currentTime: TimeInterval) { elapsed += CGFloat(currentTime - (prevUpdateTime ?? currentTime)) prevUpdateTime = currentTime guard elapsed >= 1 else { return } elapsed = 0 generateFace() } } view.presentScene(Scene())
mit
22c568be91e5afaa7b975a1699b39d56
33.392045
219
0.52222
2.929816
false
false
false
false
abertelrud/swift-package-manager
Sources/Workspace/CheckoutState.swift
2
1292
//===----------------------------------------------------------------------===// // // This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import struct TSCUtility.Version import struct SourceControl.Revision /// A checkout state represents the current state of a repository. /// /// A state will always has a revision. It can also have a branch or a version but not both. public enum CheckoutState: Equatable, Hashable { case revision(_ revision: Revision) case version(_ version: Version, revision: Revision) case branch(name: String, revision: Revision) } extension CheckoutState: CustomStringConvertible { public var description: String { switch self { case .revision(let revision): return revision.identifier case .version(let version, _): return version.description case .branch(let branch, _): return branch } } }
apache-2.0
2f1e28986486cb107f6c9fbb47d28bf3
34.888889
92
0.613003
5.168
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Settings/Auxiliary/LanguageFeature.swift
1
2071
// // LanguageFeature.swift // // // Created by Vladislav Fitc on 21/04/2020. // import Foundation public enum LanguageFeature { /// Enables language feature functionality. /// The languages supported here are either every language (this is the default, see list of Language), /// or those set by queryLanguages. See queryLanguages example below. case `true` /// Disables language feature functionality. case `false` /// A list of Language for which language feature should be enabled. /// This list of queryLanguages will override any values that you may have set in Settings. case queryLanguages([Language]) } extension LanguageFeature: ExpressibleByBooleanLiteral { public init(booleanLiteral value: Bool) { self = value ? .true : .false } } extension LanguageFeature: ExpressibleByArrayLiteral { public init(arrayLiteral elements: Language...) { self = .queryLanguages(elements) } } extension LanguageFeature: Encodable { public func encode(to encoder: Encoder) throws { var singleValueContainer = encoder.singleValueContainer() switch self { case .true: try singleValueContainer.encode(true) case .false: try singleValueContainer.encode(false) case .queryLanguages(let languages): try singleValueContainer.encode(languages) } } } extension LanguageFeature: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let boolContainer = try? container.decode(BoolContainer.self) { self = boolContainer.rawValue ? .true : .false } else { let languages = try container.decode([Language].self) self = .queryLanguages(languages) } } } extension LanguageFeature: Equatable {} extension LanguageFeature: URLEncodable { public var urlEncodedString: String { switch self { case .false: return String(false) case .true: return String(true) case .queryLanguages(let languages): return languages.map(\.rawValue).joined(separator: ",") } } }
mit
dc7744636af19146b8635616d8ad705c
22.804598
105
0.707388
4.482684
false
false
false
false
webventil/OpenSport
OpenSport/OpenSport/HealthManager.swift
1
4106
// // HealthManager.swift // OpenSport // // Created by Johannes on 05.03.15. // Copyright (c) 2015 Arne Tempelhof. All rights reserved. // import Foundation import HealthKit public class HealthManager { let healthKitStore:HKHealthStore = HKHealthStore() public class func shared() -> HealthManager { struct Static { static let s_manager = HealthManager() } return Static.s_manager } func authorizeHealthKit(completion: ((success: Bool, error: NSError!) -> Void)!) { let healthKitTypesToRead = NSSet(array: [ HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth), HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex), HKObjectType.workoutType() ]) let healthKitTypesToWrite = NSSet(array:[ HKQuantityType.workoutType() ]) if !HKHealthStore.isHealthDataAvailable() { let error = NSError(domain: NSBundle.mainBundle().bundleIdentifier!, code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this device"]) if completion != nil { completion(success:false, error:error) } return; } healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in if completion != nil { completion(success:success,error:error) } } } func getAgeAndSex() -> (age:Int?, biologicalsex:HKBiologicalSexObject?) { var error:NSError? var age:Int? if let birthDay = healthKitStore.dateOfBirthWithError(&error) { let today = NSDate() let calendar = NSCalendar.currentCalendar() let differenceComponents = NSCalendar.currentCalendar().components(.YearCalendarUnit, fromDate: birthDay, toDate: today, options: NSCalendarOptions(0) ) age = differenceComponents.year } if error != nil { println("Error reading Birthday: \(error)") } var biologicalSex:HKBiologicalSexObject? = healthKitStore.biologicalSexWithError(&error); if error != nil { println("Error reading Biological Sex: \(error)") } return (age, biologicalSex) } func saveWorkoutToHealthKit(distance: Double, startTime: NSDate, endTime: NSDate, duration: NSNumber, type: NSString, kiloCalories: Double) { var activityType: HKWorkoutActivityType let caloriesQuantity = HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: kiloCalories) let distanceQuantity = HKQuantity(unit: HKUnit.meterUnit(), doubleValue: distance) switch type { case "NORDICWALKING", "WALKING": activityType = HKWorkoutActivityType.Walking case "RUNNING": activityType = HKWorkoutActivityType.Running default: activityType = HKWorkoutActivityType.Cycling } let workout = HKWorkout(activityType: activityType, startDate: startTime, endDate: endTime, duration: NSTimeInterval(duration), totalEnergyBurned: caloriesQuantity, totalDistance: distanceQuantity, metadata: nil) healthKitStore.saveObject(workout, withCompletion: { (success, error) -> Void in if error != nil { println("Error saving distance sample: \(error.localizedDescription)") } else { println("Distance sample saved successfully!") } }) } func saveActivityToHealthKit(activity: SportActivity) { saveWorkoutToHealthKit(Double(activity.distance), startTime: activity.startTime, endTime: activity.endTime, duration: activity.duration.integerValue, type: activity.activityType, kiloCalories: 0.0) } }
mit
a06cf9ba0bda3c5afb8b70d5cab41dc0
35.660714
164
0.625426
5.204056
false
false
false
false
K-cat/CatProgressButton
CatProgressButtonExample/CatProgressButtonExample/ViewController.swift
1
2962
// // ViewController.swift // CatProgressButtonExample // // Created by K-cat on 16/7/9. // Copyright © 2016年 K-cat. All rights reserved. // import UIKit import CatProgressButton let blueColor = UIColor(red: 0.0000000000, green: 0.4568864703, blue: 0.7001402974, alpha: 1.0000000000) let greenColor = UIColor(red: 0.1503065315, green: 0.7194610834, blue: 0.1177300118, alpha: 1.0000000000) class ViewController: UIViewController { var progressButton: MyProgressButton! override func viewDidLoad() { super.viewDidLoad() progressButton = MyProgressButton(frame: CGRectMake(0, 0, 150, 40)) progressButton.center = self.view.center progressButton.title = "Download" progressButton.layer.cornerRadius = 20 progressButton.progressColor = blueColor progressButton.titleColor = blueColor progressButton.layer.borderColor = blueColor.CGColor progressButton.layer.borderWidth = 1 progressButton.layer.masksToBounds = true progressButton.progressAnimationDuration = 0.5 self.view.addSubview(progressButton) progressButton.buttonOnClickHandler = {(button) in switch self.progressButton.buttonState { case .Download: self.halfProgress() case .Use: self.progressButton.buttonState = .Inuse default: break } } progressButton.progressValueChangeHandler = {(progressValue) in } // Do any additional setup after loading the view, typically from a nib. } func maxProgress() { progressButton.buttonState = .Use progressButton.progressValue = 1 } func halfProgress() { progressButton.buttonState = .Downloading progressButton.progressValue = 0.5 self.performSelector(#selector(maxProgress), withObject: nil, afterDelay: 0.5) } func clearProgress() { progressButton.progressValue = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } enum ProgressButtonState { case Download case Downloading case Use case Inuse } class MyProgressButton: CatProgressButton { var buttonState: ProgressButtonState = .Download { didSet { switch buttonState { case .Download: self.title = "Download" case .Downloading: self.title = "Downloading" case .Use: self.title = "Use" self.progressColor = blueColor self.layer.borderColor = blueColor.CGColor case .Inuse: self.title = "Inuse" self.progressColor = greenColor self.layer.borderColor = greenColor.CGColor } } } }
mit
f12f34c025fe68b5ac277dfc5dd9e5fd
28.59
105
0.61879
4.834967
false
false
false
false
wuzhenli/MyDailyTestDemo
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/error-handle.xcplaygroundpage/Contents.swift
2
1670
import Foundation let d = NSData() do { try d.write(toFile: "Hello", options: []) } catch let error as NSError { print ("Error: \(error.domain)") } enum LoginError: Error { case UserNotFound, UserPasswordNotMatch } func login(user: String, password: String) throws { let users = [String: String]() if !users.keys.contains(user) { throw LoginError.UserNotFound } if users[user] != password { throw LoginError.UserPasswordNotMatch } print("Login successfully.") } do { try login(user: "onevcat", password: "123") } catch LoginError.UserNotFound { print("UserNotFound") } catch LoginError.UserPasswordNotMatch { print("UserPasswordNotMatch") } // Do something with login user enum E: Error { case Negative } func methodThrowsWhenPassingNegative(number: Int) throws -> Int { if number < 0 { throw E.Negative } return number } if let num = try? methodThrowsWhenPassingNegative(number: 100) { print(type(of: num)) } else { print("failed") } // Never do this! func methodThrowsWhenPassingNegative1(number: Int) throws -> Int? { if number < 0 { throw E.Negative } if number == 0 { return nil } return number } if let num = try? methodThrowsWhenPassingNegative1(number: 0) { print(type(of: num)) } else { print("failed") } func methodThrows(num: Int) throws { if num < 0 { print("Throwing!") throw E.Negative } print("Executed!") } func methodRethrows(num: Int, f: (Int) throws -> ()) rethrows { try f(num) } do { try methodRethrows(num: 1, f: methodThrows) } catch _ { }
apache-2.0
2ccb08f9fe21d15f5d723b228e91e3de
17.555556
67
0.628144
3.614719
false
false
false
false
freshOS/Komponents
KomponentsExample/AppDelegate.swift
1
900
// // AppDelegate.swift // React // // Created by Sacha Durand Saint Omer on 29/03/2017. // Copyright © 2017 Freshos. All rights reserved. // import UIKit import Komponents @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/iOSInjection10.bundle")?.load() window = UIWindow(frame: UIScreen.main.bounds) let navVC = UINavigationController(rootViewController: NavigationVC()) navVC.navigationBar.isTranslucent = false window?.rootViewController = navVC window?.makeKeyAndVisible() Komponents.logsEnabled = true return true } }
mit
e2c6e323bb09de184456be1198fb0740
30
115
0.690768
5.166667
false
false
false
false
RiBj1993/CodeRoute
Pods/TinyConstraints/TinyConstraints/Classes/Abstraction.swift
2
1846
// // MIT License // // Copyright (c) 2017 Robert-Hein Hooijmans <[email protected]> // // 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 #if os(OSX) import AppKit public typealias View = NSView public typealias LayoutGuide = NSLayoutGuide public typealias ConstraintAxis = NSLayoutConstraintOrientation public typealias LayoutPriority = NSLayoutPriority extension EdgeInsets { static var zero = NSEdgeInsetsZero } #else import UIKit public typealias View = UIView public typealias LayoutGuide = UILayoutGuide public typealias ConstraintAxis = UILayoutConstraintAxis public typealias LayoutPriority = UILayoutPriority public typealias EdgeInsets = UIEdgeInsets #endif
apache-2.0
7113b31a91078bd70c47137ed2ff5f6c
39.130435
83
0.73402
4.883598
false
false
false
false
anas10/Monumap
Monumap/Network/ParsingUtils.swift
1
1274
// // ParsingUtils.swift // Monumap // // Created by Anas Ait Ali on 19/03/2017. // Copyright © 2017 Anas Ait Ali. All rights reserved. // import Foundation import SwiftyJSON extension JSON { func parseString(_ key: String) throws -> String { guard self[key].exists() else { throw JSONSerializationError.missing(key) } guard let ret = self[key].string else { throw JSONSerializationError.invalid(key, self[key]) } return ret } func parseLatitude(_ key: String) throws -> Double { guard self[key].exists() else { throw JSONSerializationError.missing(key) } guard let ret = self[key].double else { throw JSONSerializationError.invalid(key, self[key]) } guard case (-90...90) = ret else { throw JSONSerializationError.invalid("latitude value", self[key]) } return ret } func parseLongitude(_ key: String) throws -> Double { guard self[key].exists() else { throw JSONSerializationError.missing(key) } guard let ret = self[key].double else { throw JSONSerializationError.invalid(key, self[key]) } guard case (-180...180) = ret else { throw JSONSerializationError.invalid("longitude value", self[key]) } return ret } }
apache-2.0
4981a95d733838c3fbb3405996d1d175
34.361111
102
0.645719
4.34471
false
false
false
false
fireunit/login
Pods/Material/Sources/iOS/NavigationItem.swift
2
4167
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 HOLDER 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 UIKit /// A memory reference to the NavigationItem instance. private var MaterialAssociatedObjectNavigationItemKey: UInt8 = 0 public class MaterialAssociatedObjectNavigationItem { /// Back Button. public var backButton: IconButton? /// Content View. public var contentView: UIView? /// Title label. public private(set) var titleLabel: UILabel! /// Detail text. public var detail: String? /// Detail label. public private(set) var detailLabel: UILabel! /// Left controls. public var leftControls: Array<UIControl>? /// Right controls. public var rightControls: Array<UIControl>? /// Initializer. public init() { prepareTitleLabel() prepareDetailLabel() } /// Prepares the titleLabel. private func prepareTitleLabel() { titleLabel = UILabel() titleLabel.font = RobotoFont.mediumWithSize(17) titleLabel.textAlignment = .Left } /// Prepares the detailLabel. private func prepareDetailLabel() { detailLabel = UILabel() detailLabel.font = RobotoFont.regularWithSize(12) detailLabel.textAlignment = .Left } } public extension UINavigationItem { /// NavigationItem reference. public internal(set) var item: MaterialAssociatedObjectNavigationItem { get { return MaterialAssociatedObject(self, key: &MaterialAssociatedObjectNavigationItemKey) { return MaterialAssociatedObjectNavigationItem() } } set(value) { MaterialAssociateObject(self, key: &MaterialAssociatedObjectNavigationItemKey, value: value) } } /// Back Button. public internal(set) var backButton: IconButton? { get { return item.backButton } set(value) { item.backButton = value } } /// Content View. public internal(set) var contentView: UIView? { get { return item.contentView } set(value) { item.contentView = value } } /// Title Label. public internal(set) var titleLabel: UILabel { get { return item.titleLabel } set(value) { item.titleLabel = value } } /// Detail text. public var detail: String? { get { return item.detail } set(value) { item.detail = value } } /// Detail Label. public internal(set) var detailLabel: UILabel { get { return item.detailLabel } set(value) { item.detailLabel = value } } /// Left side UIControls. public var leftControls: Array<UIControl>? { get { return item.leftControls } set(value) { item.leftControls = value } } /// Right side UIControls. public var rightControls: Array<UIControl>? { get { return item.rightControls } set(value) { item.rightControls = value } } }
mit
bbc3b91205c41e2c11916ec684a5748a
24.888199
95
0.729302
3.883504
false
false
false
false
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/Samples/MenuManager.swift
1
5784
// // MenuManager.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import Foundation import Result import ReactiveSwift import FontAwesome /// ViewModel for `MenuTabBarController`. final class MenuManager { let tabViewControllersProperty = MutableProperty<[UIViewController]>([]) let menusProperty: Property<(main: [MenuType], sub: [MenuType])> private let _menusProperty = MutableProperty<(main: [MenuType], sub: [MenuType])>(main: [], sub: []) /// Dummy Menu API Action. let menuAction = Action<TimeInterval, MenuBadgeDummyAPI.MenuResponse, NoError> { input in return MenuBadgeDummyAPI._menusProducer(delay: input) } /// Dummy Badge API Action. let badgeAction = Action<TimeInterval, MenuBadgeDummyAPI.BadgeResponse, NoError> { input in return MenuBadgeDummyAPI._badgesProducer(delay: input) } init() { self.menusProperty = Property(self._menusProperty) // Update `_menusProperty` via Menu API. self._menusProperty <~ menuAction.values .map { menuIdsTuple in let main = menuIdsTuple.main.map(_createMenu) let sub = menuIdsTuple.sub.map(_createMenu) return (main, sub) } // Proxy for `tabC.viewControllers <~ _menusProperty`. self.tabViewControllersProperty <~ self._menusProperty.producer .map { $0.main.map { $0.viewController } } // Update on-memory badges via Badge API. for menuId in MenuId.allMenuIds { BadgeManager.badges[menuId] <~ self.badgeAction.values .map { badgeTuples -> Badge? in return (badgeTuples.first { $0.menuId == menuId }?.badgeString) .flatMap(Badge.init) } .skipNil() } // Bind to `menu.badge` everytime `_menusProperty` is updated. self._menusProperty.signal .map { $0 + $1 } // main + sub .observeValues { menus in for menu in menus { menu.badge <~ BadgeManager.badges[menu.menuId] } } /// Send subMenus to `SettingsMenu` everytime `_menusProperty` is updated. self._menusProperty.signal .flatMap(.merge) { main, sub -> SignalProducer<([MenuType], SettingsMenu), NoError> in if let x = (main + sub).find(SettingsMenu.self).map({ (sub, $0) }) { return SignalProducer<([MenuType], SettingsMenu), NoError>(value: x).concat(.never) } else { return .never } } .observeValues { subMenus, settingsMenu in settingsMenu.menusProperty.value = subMenus } } } // MARK: Dummy API struct MenuBadgeDummyAPI { typealias MenuResponse = (main: [MenuId], sub: [MenuId]) typealias BadgeResponse = [(menuId: MenuId, badgeString: String)] /// Dummy response for layouting tabBar (main) and `Settings`'s tableView (sub). /// - Note: Main array has maximum of 5 elements, including `.Settings` at last. private static func _responseMenuIds() -> (main: [MenuId], sub: [MenuId]) { var menuIds = MenuId.allMenuIds menuIds.remove(at: menuIds.index(of: .settings)!) menuIds.shuffle() let slices = splitAt(random(5))(menuIds) return (main: Array(slices.0 + [.settings]), sub: Array(slices.1)) } /// Common SignalProducer for simulating dummy network calls with dummy network `delay`, /// which has response type `(main: [MenuId], sub: [MenuId])`. private static func _dummyResponseMenuIdsProducer(_ logContext: String, delay: TimeInterval) -> SignalProducer<MenuBadgeDummyAPI.MenuResponse, NoError> { return SignalProducer(value: MenuBadgeDummyAPI._responseMenuIds()) // .on(started: logSink("dummy \(logContext) request")) .delay(delay, on: QueueScheduler.main) // .on(next: logSink("dummy \(logContext) response")) } /// SignalProducer for simulating `MenuList API` with dummy network `delay` /// which layouts mainMenus (tab) & subMenus (tableView). fileprivate static func _menusProducer(delay: TimeInterval) -> SignalProducer<MenuBadgeDummyAPI.MenuResponse, NoError> { return self._dummyResponseMenuIdsProducer("Menu API", delay: delay) } /// SignalProducer for simulating `Badge API` with dummy network `delay` /// which has response type `[(menuId: MenuId, badge: String)]` (menus are flattened). fileprivate static func _badgesProducer(delay: TimeInterval) -> SignalProducer<MenuBadgeDummyAPI.BadgeResponse, NoError> { return self._dummyResponseMenuIdsProducer("Badge API", delay: delay) .map { $0 + $1 } // flatten `main` & `sub` .map { menuIds in menuIds.map { ($0, Badge.randomBadgeString()) } } } } // MARK: Helpers private func _createMenu(menuId: MenuId) -> MenuType { switch menuId { case .settings: return SettingsMenu() default: return CustomMenu(menuId: menuId) } } /// For dummy Badge API. extension Badge { static func randomBadgeString() -> Swift.String { let rand = random(3000) let badgeString: Swift.String switch rand { case 0..<1500: badgeString = "\(rand)" case 1500..<2000: badgeString = "N" case 2000..<2500: badgeString = "ヽ(ツ)ノ" default: badgeString = "" } return badgeString } }
mit
f9ba8dee9ad37ce0a207b3f0b7b83b35
34.881988
155
0.603774
4.340346
false
false
false
false
kamoljan/algolia-swift-demo
Source/MoviesTableViewController.swift
1
6266
// // Copyright (c) 2015 Algolia // http://www.algolia.com/ // // 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 import AlgoliaSearch import AFNetworking import SwiftyJSON class MoviesTableViewController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating { var searchController: UISearchController! var movieIndex: Index! let query = Query() var movies = [Ad]() var searchId = 0 var displayedSearchId = -1 var loadedPage: UInt = 0 var nbPages: UInt = 0 let placeholder = UIImage(named: "white") override func viewDidLoad() { super.viewDidLoad() // Search controller searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.delegate = self // Add the search bar tableView.tableHeaderView = self.searchController!.searchBar definesPresentationContext = true searchController!.searchBar.sizeToFit() // Algolia Search // let apiClient = Client(appID: "latency", apiKey: "dce4286c2833e8cf4b7b1f2d3fa1dbcb") // movieIndex = apiClient.getIndex("movies") let apiClient = Client(appID: "HU2A6UF5VX", apiKey: "7bbbc005e3744372ad302dffbcef544c") movieIndex = apiClient.getIndex("ads") query.hitsPerPage = 15 query.attributesToRetrieve = ["title", "description", "medium_list", "price", "loveCount"] query.attributesToHighlight = ["title", "description"] // First load updateSearchResultsForSearchController(searchController) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("movieCell", forIndexPath: indexPath) as! UITableViewCell // Load more? if (indexPath.row + 5) >= (movies.count - 1) { loadMore() } // Configure the cell... let movie = movies[indexPath.row] cell.textLabel?.highlightedTextColor = UIColor(red:1, green:1, blue:0.898, alpha:1) cell.textLabel?.highlightedText = movie.title cell.detailTextLabel?.text = "\(movie.description)" cell.imageView?.cancelImageRequestOperation() cell.imageView?.setImageWithURL(NSURL(string: "http://sushi.shopafter.com/fid/" + movie.medium_list), placeholderImage: placeholder) return cell } // MARK: - Search bar func updateSearchResultsForSearchController(searchController: UISearchController) { query.query = searchController.searchBar.text let curSearchId = searchId movieIndex.search(query, block: { (data, error) -> Void in if (curSearchId <= self.displayedSearchId) || (error != nil) { return } self.displayedSearchId = curSearchId self.loadedPage = 0 // reset loaded page let json = JSON(data!) let hits: [JSON] = json["hits"].arrayValue self.nbPages = UInt(json["nbPages"].intValue) var tmp = [Ad]() for record in hits { tmp.append(Ad(json: record)) } self.movies = tmp self.tableView.reloadData() }) ++self.searchId } // MARK: - Load more func loadMore() { if loadedPage + 1 >= nbPages { return } let nextQuery = Query(copy: query) nextQuery.page = loadedPage + 1 movieIndex.search(nextQuery, block: { (data , error) -> Void in // Reject if query has changed if (nextQuery.query != self.query.query) || (error != nil) { return } self.loadedPage = nextQuery.page let json = JSON(data!) let hits: [JSON] = json["hits"].arrayValue var tmp = [Ad]() for record in hits { tmp.append(Ad(json: record)) } self.movies.extend(tmp) self.tableView.reloadData() }) } /* // 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. } */ }
mit
2ed5fce256764f5ee4b371726281f34b
34.005587
140
0.628631
4.929976
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/DashboardV2/Views/ActivityTimeView.swift
1
3346
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 UIKit protocol ActivityTimeViewDelegate: AnyObject { func activityTimeViewTapped(time: ActivityTime) } class ActivityTimeView: View { private let dayButton = Button(style: .plain) private let weekButton = Button(style: .plain) private let underlineView = View() weak var delegate: ActivityTimeViewDelegate? override func commonInit() { super.commonInit() dayButton.title = "Day" weekButton.title = "Week" dayButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside) weekButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside) underlineView.backgroundColor = Style.Colors.FoundationGreen addSubview(dayButton) { $0.top.bottom.leading.equalToSuperview() $0.width.equalToSuperview().dividedBy(2) } addSubview(weekButton) { $0.top.bottom.trailing.equalToSuperview() $0.width.equalToSuperview().dividedBy(2) $0.leading.equalTo(dayButton.snp.trailing) } addSubview(underlineView) { $0.height.equalTo(1) $0.bottom.equalToSuperview() $0.leading.trailing.equalTo(dayButton) } } func configure(state: ActivityState) { underlineView.snp.remakeConstraints { $0.height.equalTo(1) $0.bottom.equalToSuperview() switch state.time { case .day: $0.leading.trailing.equalTo(dayButton) case .week: $0.leading.trailing.equalTo(weekButton) } } setNeedsLayout() UIView.animate(withDuration: 0.3, delay: 0.0, options: [.beginFromCurrentState], animations: { self.layoutIfNeeded() }, completion: nil) } @objc func buttonTapped(_ sender: Button) { switch sender { case dayButton: delegate?.activityTimeViewTapped(time: .day) case weekButton: delegate?.activityTimeViewTapped(time: .week) default: break } } }
bsd-3-clause
02d1cc86e09636abf12ff4048b3f56af
33.84375
98
0.720478
4.349805
false
false
false
false
MukeshKumarS/Swift
test/SILOptimizer/return.swift
1
3353
// RUN: %target-swift-frontend %s -emit-sil -verify func singleBlock() -> Int { _ = 0 } // expected-error {{missing return in a function expected to return 'Int'}} func singleBlock2() -> Int { var y = 0 y += 1 } // expected-error {{missing return in a function expected to return 'Int'}} class MyClassWithClosure { var f : (s: String) -> String = { (s: String) -> String in } // expected-error {{missing return in a closure expected to return 'String'}} } func multipleBlocksSingleMissing(b: Bool) -> (String, Int) { var y = 0 if b { return ("a", 1) } else if (y == 0) { y += 1 } } // expected-error {{missing return in a function expected to return '(String, Int)'}} func multipleBlocksAllMissing(x: Int) -> Int { var y : Int = x + 1 while (y > 0 ) { --y; break; } var x = 0 x += 1 } // expected-error {{missing return in a function expected to return 'Int'}} @noreturn func MYsubscriptNonASCII(idx: Int) -> UnicodeScalar { } // no-warning @noreturn @_silgen_name("exit") func exit ()->() @noreturn func tryingToReturn (x: Bool) -> () { if x { return // expected-error {{return from a 'noreturn' function}} } exit() } @noreturn func implicitReturnWithinNoreturn() { _ = 0 }// expected-error {{return from a 'noreturn' function}} func diagnose_missing_return_in_the_else_branch(i: Bool) -> Int { if (i) { exit() } } // expected-error {{missing return in a function expected to return 'Int'}} func diagnose_missing_return_no_error_after_noreturn(i: Bool) -> Int { if (i) { exit() } else { exit() } } // no error class TuringMachine { @noreturn func halt() { repeat { } while true } @noreturn func eatTape() { return // expected-error {{return from a 'noreturn' function}} } } func diagnose_missing_return_no_error_after_noreturn_method() -> Int { TuringMachine().halt() } // no error func whileLoop(flag: Bool) -> Int { var b = 1; while (flag) { if b == 3 { return 3 } b++ } } //expected-error {{missing return in a function expected to return 'Int'}} func whileTrueLoop() -> Int { var b = 1; while (true) { if b == 3 { return 3 } b++ } // no-error } func testUnreachableAfterNoReturn(x: Int) -> Int { exit(); // expected-note{{a call to a noreturn function}} return x; // expected-warning {{will never be executed}} } func testUnreachableAfterNoReturnInADifferentBlock() -> Int { let x:Int = 5; if true { // expected-note {{condition always evaluates to true}} exit(); } return x; // expected-warning {{will never be executed}} } func testReachableAfterNoReturnInADifferentBlock(x: Int) -> Int { if x == 5 { exit(); } return x; // no warning } func testUnreachableAfterNoReturnFollowedByACall() -> Int { let x:Int = 5; exit(); // expected-note{{a call to a noreturn function}} exit(); // expected-warning {{will never be executed}} return x; } func testUnreachableAfterNoReturnMethod() -> Int { TuringMachine().halt(); // expected-note{{a call to a noreturn function}} return 0; // expected-warning {{will never be executed}} } func testCleanupCodeEmptyTuple(@autoclosure fn: () -> Bool = false, message: String = "", file: String = __FILE__, line: Int = __LINE__) { if true { exit() } } // no warning
apache-2.0
6760efeecd09b24038a48be46a035c1a
23.474453
140
0.622428
3.514675
false
false
false
false
tinrobots/CoreDataPlus
Tests/Resources/SampleModel2/SampleModel2+V3.swift
1
32762
// CoreDataPlus // // You can use collection operators in CoreData and during migration: // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html // i.e. FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:" , "MY_ENTITY_MAPPING_NAME", [email protected]) // @distinctUnionOfSets expects an NSSet containing NSSet objects, and returns an NSSet. Because sets can’t contain duplicate values anyway, there is only the distinct operator.) import CoreData @testable import CoreDataPlus extension V3 { enum Configurations { static let one = "SampleConfigurationV3" // all the entities } @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) static func makeManagedObjectModel() -> NSManagedObjectModel { if let model = SampleModel2.modelCache["V3"] { return model } let managedObjectModel = NSManagedObjectModel() let writer = makeWriterEntity() let author = makeAuthorEntity() let book = makeBookEntity() let cover = makeCoverEntity() let graphicNovel = makeGraphicNovelEntity() let page = makePageEntity() let feedback = makeFeedbackEntity() // Definition using the CoreDataPlus convenience init let feedbackList = NSFetchedPropertyDescription(name: AuthorV3.FetchedProperty.feedbacks, destinationEntity: feedback) { $0.predicate = NSPredicate(format: "%K == $FETCH_SOURCE.%K", #keyPath(FeedbackV3.authorAlias), #keyPath(AuthorV3.alias)) $0.sortDescriptors = [NSSortDescriptor(key: #keyPath(FeedbackV3.rating), ascending: true)] } author.add(feedbackList) // Definition without the CoreDataPlus convenience init let request2 = NSFetchRequest<NSFetchRequestResult>(entity: feedback) request2.resultType = .managedObjectResultType request2.predicate = NSPredicate(format: "authorAlias == $FETCH_SOURCE.alias AND (comment CONTAINS [c] $FETCHED_PROPERTY.userInfo.search)") let favFeedbackList = NSFetchedPropertyDescription() favFeedbackList.name = AuthorV3.FetchedProperty.favFeedbacks favFeedbackList.fetchRequest = request2 favFeedbackList.userInfo?["search"] = "great" author.add(favFeedbackList) let authorToBooks = NSRelationshipDescription() authorToBooks.name = #keyPath(AuthorV3.books) authorToBooks.destinationEntity = book authorToBooks.isOptional = true authorToBooks.isOrdered = false authorToBooks.minCount = 0 authorToBooks.maxCount = .max authorToBooks.deleteRule = .cascadeDeleteRule let bookToAuthor = NSRelationshipDescription() bookToAuthor.name = #keyPath(BookV3.author) bookToAuthor.destinationEntity = author // 🚩 Set to optional just because if the model is build using the Xcode UI we have this error otherwise: // Misconfigured Entity: Entity Author cannot have uniqueness constraints and to-one mandatory inverse relationship Book.author bookToAuthor.isOptional = true bookToAuthor.isOrdered = false bookToAuthor.minCount = 0 bookToAuthor.maxCount = 1 bookToAuthor.deleteRule = .nullifyDeleteRule authorToBooks.inverseRelationship = bookToAuthor bookToAuthor.inverseRelationship = authorToBooks let coverToBook = NSRelationshipDescription() coverToBook.name = #keyPath(CoverV3.book) coverToBook.destinationEntity = book coverToBook.isOptional = false coverToBook.isOrdered = false coverToBook.minCount = 1 coverToBook.maxCount = 1 coverToBook.deleteRule = .cascadeDeleteRule let bookToCover = NSRelationshipDescription() bookToCover.name = #keyPath(Book.cover) bookToCover.destinationEntity = cover bookToCover.isOptional = false bookToCover.isOrdered = false bookToCover.minCount = 1 bookToCover.maxCount = 1 // there was a warning during migration tests about not having this set as cascade bookToCover.deleteRule = .cascadeDeleteRule coverToBook.inverseRelationship = bookToCover bookToCover.inverseRelationship = coverToBook let bookToPages = NSRelationshipDescription() bookToPages.name = #keyPath(BookV3.pages) bookToPages.destinationEntity = page bookToPages.isOptional = false bookToPages.isOrdered = false bookToPages.minCount = 1 bookToPages.maxCount = 10_000 bookToPages.deleteRule = .cascadeDeleteRule let pageToBook = NSRelationshipDescription() pageToBook.name = #keyPath(PageV3.book) pageToBook.destinationEntity = book // 🚩 Set to optional just because if the model is build using the Xcode UI we have this error otherwise: // Misconfigured Entity: Entity Book cannot have uniqueness constraints and to-one mandatory inverse relationship Page.book pageToBook.isOptional = true pageToBook.isOrdered = false pageToBook.minCount = 0 pageToBook.maxCount = 1 pageToBook.deleteRule = .nullifyDeleteRule bookToPages.inverseRelationship = pageToBook pageToBook.inverseRelationship = bookToPages author.add(authorToBooks) // author.properties += [authorToBooks] book.properties += [bookToAuthor, bookToPages, bookToCover] cover.properties += [coverToBook] page.properties += [pageToBook] writer.subentities = [author] book.subentities = [graphicNovel] let entities = [writer, author, book, graphicNovel, page, feedback, cover] managedObjectModel.entities = entities managedObjectModel.setEntities(entities, forConfigurationName: Configurations.one) SampleModel2.modelCache["V3"] = managedObjectModel return managedObjectModel } static func makeWriterEntity() -> NSEntityDescription { let entity = NSEntityDescription(for: WriterV3.self, withName: String(describing: Writer.self)) entity.isAbstract = true let age = NSAttributeDescription.int16(name: #keyPath(WriterV3.age)) age.isOptional = false entity.add(age) return entity } static func makeAuthorEntity() -> NSEntityDescription { var entity = NSEntityDescription() entity = NSEntityDescription() entity.name = String(describing: Author.self) // 🚩 the entity name should stay the same entity.managedObjectClassName = String(describing: AuthorV3.self) // ✅ added in V3 let socialURL = NSAttributeDescription.uri(name: #keyPath(AuthorV3.socialURL)) socialURL.isOptional = true socialURL.renamingIdentifier = #keyPath(AuthorV3.socialURL) let alias = NSAttributeDescription.string(name: #keyPath(AuthorV3.alias)) alias.isOptional = false entity.properties = [alias, socialURL] entity.uniquenessConstraints = [[#keyPath(AuthorV3.alias)]] let index = NSFetchIndexDescription(name: "authorIndex", elements: [NSFetchIndexElementDescription(property: alias, collationType: .binary)]) entity.indexes.append(index) return entity } @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) static func makeCoverEntity() -> NSEntityDescription { var entity = NSEntityDescription() entity = NSEntityDescription() entity.name = String(describing: "Cover") entity.managedObjectClassName = String(describing: CoverV3.self) let data = NSAttributeDescription.binaryData(name: #keyPath(CoverV3.data)) data.isOptional = false entity.properties = [data] return entity } @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) static func makeBookEntity() -> NSEntityDescription { var entity = NSEntityDescription() entity = NSEntityDescription() entity.name = String(describing: Book.self) entity.managedObjectClassName = String(describing: BookV3.self) let uniqueID = NSAttributeDescription.uuid(name: #keyPath(BookV3.uniqueID)) uniqueID.isOptional = false let title = NSAttributeDescription.string(name: #keyPath(BookV3.title)) title.isOptional = false let rule1 = (NSPredicate(format: "length >= 3 AND length <= 50"),"Title must have a length between 3 and 50 chars.") let rule2 = (NSPredicate(format: "SELF CONTAINS %@", "title"), "Title must contain 'title'.") title.setValidationPredicates([rule1.0, rule2.0], withValidationWarnings: [rule1.1, rule2.1]) let price = NSAttributeDescription.decimal(name: #keyPath(BookV3.price)) price.isOptional = false // ✅ Renamed cover as frontCover let defaultCover = Cover(text: "default cover") let cover = NSAttributeDescription.transformable(for: Cover.self, name: #keyPath(BookV3.frontCover), defaultValue: defaultCover) cover.isOptional = false let publishedAt = NSAttributeDescription.date(name: #keyPath(BookV3.publishedAt)) publishedAt.isOptional = false let pagesCount = NSDerivedAttributeDescription(name: #keyPath(BookV3.pagesCount), type: .integer64AttributeType, derivationExpression: NSExpression(format: "pages.@count")) pagesCount.isOptional = true entity.properties = [uniqueID, title, price, cover, publishedAt, pagesCount] entity.uniquenessConstraints = [[#keyPath(BookV3.uniqueID)]] return entity } static func makePageEntity() -> NSEntityDescription { var entity = NSEntityDescription() entity = NSEntityDescription() entity.name = String(describing: Page.self) entity.managedObjectClassName = String(describing: PageV3.self) let number = NSAttributeDescription.int32(name: #keyPath(PageV3.number)) number.isOptional = false let isBookmarked = NSAttributeDescription.bool(name: #keyPath(PageV3.isBookmarked)) isBookmarked.isOptional = false isBookmarked.defaultValue = false let content = NSAttributeDescription.customTransformable(for: Content.self, name: #keyPath(PageV3.content)) { //(content: Content?) -> Data? in guard let content = $0 else { return nil } return try? NSKeyedArchiver.archivedData(withRootObject: content, requiringSecureCoding: true) } reverse: { //data -> Content? in guard let data = $0 else { return nil } return try? NSKeyedUnarchiver.unarchivedObject(ofClass: Content.self, from: data) } content.isOptional = false entity.properties = [isBookmarked, number, content] return entity } static func makeGraphicNovelEntity() -> NSEntityDescription { var entity = NSEntityDescription() entity = NSEntityDescription() entity.name = String(describing: GraphicNovel.self) entity.managedObjectClassName = String(describing: GraphicNovelV3.self) let isBlackAndWhite = NSAttributeDescription.bool(name: #keyPath(GraphicNovel.isBlackAndWhite)) isBlackAndWhite.isOptional = false isBlackAndWhite.defaultValue = false entity.properties = [isBlackAndWhite] return entity } static func makeFeedbackEntity() -> NSEntityDescription { let entity = NSEntityDescription(for: FeedbackV3.self, withName: String(describing: Feedback.self)) let bookID = NSAttributeDescription.uuid(name: #keyPath(FeedbackV3.bookID)) bookID.isOptional = false let authorAlias = NSAttributeDescription.string(name: #keyPath(FeedbackV3.authorAlias)) authorAlias.isOptional = false let comment = NSAttributeDescription.string(name: #keyPath(FeedbackV3.comment)) comment.isOptional = true let rating = NSAttributeDescription.double(name: #keyPath(FeedbackV3.rating)) rating.isOptional = false entity.add(authorAlias) entity.add(bookID) entity.add(comment) entity.add(rating) return entity } } // MARK: - Mapping // Abstract class (Writer) don't need a NSEntityMapping // Subclasses (Author, GraphicNovel) need to define all the property mappings (for super properties too) // // BUG: // It seems that entity version hashes change if the entity has a derived attribute (it happens too if the model is created using the // Xcode UI - http://openradar.appspot.com/FB9044112) // Since an entity version hash depends on its property hashes, all the entity in relation with that entity have this bug. // // In the sample, "Book" has a derived attribute (pagesCount), all the related entities suffer from this bug: // 1. Cover (has a book relationship) // 2. Authour (has a books relationship) // 3. Book and GraphicNovel // 4. Page (has a book relationship) // // Fix: since the models are cached (and hence the entities descriptions with their version hasesh too), we use NSManagedObjectModel entityVersionHashesByName; // if the model isn't recreated on demand, the entities version hashes will stay the same. // If we use Xcode UI, we need to do some manual cleaning: https://github.com/diogot/CoreDataModelMigrationBug @available(iOS 13.0, iOSApplicationExtension 13.0, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) extension V3 { static func makeCoverMapping() -> NSEntityMapping { let destinationEntityVersionHash = V3.makeManagedObjectModel().entityVersionHashesByName["Cover"] let mapping = NSEntityMapping() mapping.name = "Cover" mapping.mappingType = .addEntityMappingType mapping.sourceEntityName = nil mapping.destinationEntityName = "Cover" mapping.destinationEntityVersionHash = destinationEntityVersionHash let data = NSPropertyMapping() data.name = #keyPath(CoverV3.data) data.valueExpression = nil let book = NSPropertyMapping() book.name = #keyPath(CoverV3.book) book.valueExpression = nil mapping.attributeMappings = [data] mapping.relationshipMappings = [book] return mapping } static func makeBookMapping() -> NSEntityMapping { let sourceEntityVersionHash = V2.makeManagedObjectModel().entityVersionHashesByName["Book"] let destinationEntityVersionHash = V3.makeManagedObjectModel().entityVersionHashesByName["Book"] let mapping = NSEntityMapping() mapping.name = "BookToBook" mapping.mappingType = .customEntityMappingType mapping.sourceEntityName = "Book" mapping.destinationEntityName = "Book" mapping.entityMigrationPolicyClassName = String(describing: BookCoverToCoverMigrationPolicy.self) mapping.sourceEntityVersionHash = sourceEntityVersionHash mapping.destinationEntityVersionHash = destinationEntityVersionHash // you can use the userInfo property to pass additional data to the migration policy var userInfo = [AnyHashable: Any]() userInfo["modelVersion"] = "V3" mapping.userInfo = userInfo let uniqueID = NSPropertyMapping() uniqueID.name = #keyPath(BookV3.uniqueID) uniqueID.valueExpression = NSExpression(format: "$source.\(#keyPath(BookV2.uniqueID))") let title = NSPropertyMapping() title.name = #keyPath(BookV3.title) // 🚩 Investigating how to implement and call custom methods in the policy //title.valueExpression = NSExpression(format: "$source.\(#keyPath(BookV2.title))") title.valueExpression = NSExpression(format: #"FUNCTION($entityPolicy, "destinationTitleForSourceBookTitle:manager:", $source.\#(#keyPath(BookV2.title)),$manager)"#) let price = NSPropertyMapping() price.name = #keyPath(BookV3.price) price.valueExpression = NSExpression(format: "$source.\(#keyPath(BookV2.price))") let publishedAt = NSPropertyMapping() publishedAt.name = #keyPath(BookV3.publishedAt) publishedAt.valueExpression = NSExpression(format: "$source.\(#keyPath(BookV2.publishedAt))") let pagesCount = NSPropertyMapping() pagesCount.name = #keyPath(BookV3.pagesCount) pagesCount.valueExpression = NSExpression(format: "$source.\(#keyPath(BookV2.pagesCount))") let pages = NSPropertyMapping() pages.name = #keyPath(BookV3.pages) pages.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:", "PageToPage", $source.\#(#keyPath(BookV2.pages)))"#) let author = NSPropertyMapping() author.name = #keyPath(BookV3.author) author.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:", "AuthorToAuthor", $source.\#(#keyPath(BookV2.author)))"#) let frontCover = NSPropertyMapping() frontCover.name = #keyPath(BookV3.frontCover) mapping.attributeMappings = [pagesCount, price, publishedAt, title, uniqueID ] mapping.relationshipMappings = [author, frontCover, pages] mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Book", "TRUEPREDICATE"), $manager.sourceContext, NO)"#) return mapping } static func makeGraphicNovelMapping() -> NSEntityMapping { let sourceEntityVersionHash = V2.makeManagedObjectModel().entityVersionHashesByName["GraphicNovel"] let destinationEntityVersionHash = V3.makeManagedObjectModel().entityVersionHashesByName["GraphicNovel"] let mapping = NSEntityMapping() mapping.name = "GraphicNovelToGraphicNovel" mapping.mappingType = .customEntityMappingType mapping.sourceEntityName = "GraphicNovel" mapping.destinationEntityName = "GraphicNovel" mapping.entityMigrationPolicyClassName = String(describing: BookCoverToCoverMigrationPolicy.self) mapping.sourceEntityVersionHash = sourceEntityVersionHash mapping.destinationEntityVersionHash = destinationEntityVersionHash // you can use the userInfo property to pass additional data to the migration policy var userInfo = [AnyHashable: Any]() userInfo["modelVersion"] = "V3" mapping.userInfo = userInfo let uniqueID = NSPropertyMapping() uniqueID.name = #keyPath(BookV3.uniqueID) uniqueID.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.uniqueID))") let title = NSPropertyMapping() title.name = #keyPath(BookV3.title) // 🚩 Investigating how to implement and call custom methods in the policy //title.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.title))") title.valueExpression = NSExpression(format: #"FUNCTION($entityPolicy, "destinationTitleForSourceBookTitle:manager:", $source.\#(#keyPath(BookV2.title)),$manager)"#) let price = NSPropertyMapping() price.name = #keyPath(BookV3.price) price.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.price))") let publishedAt = NSPropertyMapping() publishedAt.name = #keyPath(BookV3.publishedAt) publishedAt.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.publishedAt))") let pageCount = NSPropertyMapping() pageCount.name = #keyPath(BookV3.pagesCount) pageCount.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.pagesCount))") let pages = NSPropertyMapping() pages.name = #keyPath(BookV3.pages) pages.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:", "PageToPage", $source.\#(#keyPath(BookV2.pages)))"#) let author = NSPropertyMapping() author.name = #keyPath(BookV3.author) author.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:", "AuthorToAuthor", $source.\#(#keyPath(GraphicNovelV2.author)))"#) let frontCover = NSPropertyMapping() frontCover.name = #keyPath(BookV3.frontCover) let isBlackAndWhite = NSPropertyMapping() isBlackAndWhite.name = #keyPath(GraphicNovelV3.isBlackAndWhite) isBlackAndWhite.valueExpression = NSExpression(format: "$source.\(#keyPath(GraphicNovelV2.isBlackAndWhite))") mapping.attributeMappings = [isBlackAndWhite, pageCount, price, publishedAt, title, uniqueID, ] mapping.relationshipMappings = [author, frontCover, pages] mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "GraphicNovel", "TRUEPREDICATE"), $manager.sourceContext, NO)"#) return mapping } // This mapping takes all the feedbacks whose comment property contains the word "great" a increse their rating by 10 static func makeFeedbackMappingPartOne() -> NSEntityMapping { let mapping = NSEntityMapping() mapping.name = "FeedbackToFeedbackPartOne" mapping.mappingType = .copyEntityMappingType mapping.sourceEntityName = "Feedback" mapping.destinationEntityName = "Feedback" mapping.sourceEntityVersionHash = V2.makeFeedbackEntity().versionHash mapping.destinationEntityVersionHash = V3.makeFeedbackEntity().versionHash let bookID = NSPropertyMapping() bookID.name = #keyPath(FeedbackV3.bookID) bookID.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.bookID))") let authorAlias = NSPropertyMapping() authorAlias.name = #keyPath(FeedbackV3.authorAlias) authorAlias.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.authorAlias))") let comment = NSPropertyMapping() comment.name = #keyPath(FeedbackV3.comment) comment.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.comment))") let rating = NSPropertyMapping() rating.name = #keyPath(FeedbackV3.rating) rating.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.rating)) + 10") mapping.attributeMappings = [authorAlias, bookID, comment, rating] let predicate = NSPredicate(format: "%K CONTAINS [c] %@", "comment", "great") // 🚩 Investigating how to implement and call custom methods in the manager // the FETCH uses customfetchRequestForSourceEntityNamed:predicateString: defined in FeedbackMigrationManager instead of: // mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Feedback", %@), $manager.sourceContext, NO)"#, argumentArray: [predicate.description]) mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "customfetchRequestForSourceEntityNamed:predicateString:" , "Feedback", %@), $manager.sourceContext, NO)"#, argumentArray: [predicate.description]) return mapping } // This mapping takes all the other feedbacks without any custom changes static func makeFeedbackMappingPartTwo() -> NSEntityMapping { let mapping = NSEntityMapping() mapping.name = "FeedbackToFeedbackPartTwo" mapping.mappingType = .copyEntityMappingType mapping.sourceEntityName = "Feedback" mapping.destinationEntityName = "Feedback" mapping.sourceEntityVersionHash = V2.makeFeedbackEntity().versionHash mapping.destinationEntityVersionHash = V3.makeFeedbackEntity().versionHash let bookID = NSPropertyMapping() bookID.name = #keyPath(FeedbackV3.bookID) bookID.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.bookID))") let authorAlias = NSPropertyMapping() authorAlias.name = #keyPath(FeedbackV3.authorAlias) authorAlias.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.authorAlias))") let comment = NSPropertyMapping() comment.name = #keyPath(FeedbackV3.comment) comment.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.comment))") let rating = NSPropertyMapping() rating.name = #keyPath(FeedbackV3.rating) rating.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.rating))") mapping.attributeMappings = [authorAlias, bookID, comment, rating] let predicate = NSPredicate(format: "NOT (%K CONTAINS [c] %@)", "comment", "great") mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Feedback", %@), $manager.sourceContext, NO)"#, argumentArray: [predicate.description]) return mapping } // Not used (see FeedbackToFeedbackPartOne and FeedbackToFeedbackPartTwo) static func makeFeedbackMapping() -> NSEntityMapping { let mapping = NSEntityMapping() mapping.name = "FeedbackToFeedback" mapping.mappingType = .copyEntityMappingType mapping.sourceEntityName = "Feedback" mapping.destinationEntityName = "Feedback" mapping.sourceEntityVersionHash = V2.makeFeedbackEntity().versionHash mapping.destinationEntityVersionHash = V3.makeFeedbackEntity().versionHash let bookID = NSPropertyMapping() bookID.name = #keyPath(FeedbackV3.bookID) bookID.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.bookID))") let authorAlias = NSPropertyMapping() authorAlias.name = #keyPath(FeedbackV3.authorAlias) authorAlias.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.authorAlias))") let comment = NSPropertyMapping() comment.name = #keyPath(FeedbackV3.comment) comment.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.comment))") let rating = NSPropertyMapping() rating.name = #keyPath(FeedbackV3.rating) rating.valueExpression = NSExpression(format: "$source.\(#keyPath(FeedbackV2.rating))") mapping.attributeMappings = [authorAlias, bookID, comment, rating] mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Feedback", "TRUEPREDICATE"), $manager.sourceContext, NO)"#) return mapping } static func makePageMapping() -> NSEntityMapping { let sourceEntityVersionHash = V2.makeManagedObjectModel().entityVersionHashesByName["Page"] let destinationEntityVersionHash = V3.makeManagedObjectModel().entityVersionHashesByName["Page"] let mapping = NSEntityMapping() mapping.name = "PageToPage" mapping.mappingType = .copyEntityMappingType mapping.sourceEntityName = "Page" mapping.destinationEntityName = "Page" mapping.sourceEntityVersionHash = sourceEntityVersionHash mapping.destinationEntityVersionHash = destinationEntityVersionHash let number = NSPropertyMapping() number.name = #keyPath(PageV3.number) number.valueExpression = NSExpression(format: "$source.\(#keyPath(PageV2.number))") let book = NSPropertyMapping() book.name = #keyPath(PageV3.book) book.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForSourceRelationshipNamed:sourceInstances:", "book", $source.\#(#keyPath(PageV2.book)))"#) let isBookmarked = NSPropertyMapping() isBookmarked.name = #keyPath(PageV3.isBookmarked) isBookmarked.valueExpression = NSExpression(format: "$source.\(#keyPath(PageV2.isBookmarked))") let content = NSPropertyMapping() content.name = #keyPath(PageV3.content) content.valueExpression = NSExpression(format: "$source.\(#keyPath(PageV2.content))") mapping.attributeMappings = [content, isBookmarked, number] mapping.relationshipMappings = [book] mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Page", "TRUEPREDICATE"), $manager.sourceContext, NO)"#) return mapping } static func makeAuthorMapping() -> NSEntityMapping { let sourceEntityVersionHash = V2.makeManagedObjectModel().entityVersionHashesByName["Author"] let destinationEntityVersionHash = V3.makeManagedObjectModel().entityVersionHashesByName["Author"] // Author let mapping = NSEntityMapping() mapping.name = "AuthorToAuthor" mapping.sourceEntityName = "Author" mapping.destinationEntityName = "Author" mapping.mappingType = .copyEntityMappingType mapping.sourceEntityVersionHash = sourceEntityVersionHash mapping.destinationEntityVersionHash = destinationEntityVersionHash let alias = NSPropertyMapping() alias.name = #keyPath(AuthorV3.alias) alias.valueExpression = NSExpression(format: "$source.\(#keyPath(AuthorV2.alias))") let socialURL = NSPropertyMapping() socialURL.name = #keyPath(AuthorV3.socialURL) let age = NSPropertyMapping() age.name = #keyPath(WriterV3.age) age.valueExpression = NSExpression(format: "$source.\(#keyPath(AuthorV2.age))") let books = NSPropertyMapping() books.name = #keyPath(AuthorV3.books) books.valueExpression = NSExpression(format: #"FUNCTION($manager, "destinationInstancesForSourceRelationshipNamed:sourceInstances:", "books", $source.\#(#keyPath(AuthorV2.books)))"#) mapping.attributeMappings = [age, alias, socialURL] mapping.relationshipMappings = [books] mapping.sourceExpression = NSExpression(format: #"FETCH(FUNCTION($manager, "fetchRequestForSourceEntityNamed:predicateString:" , "Author", "TRUEPREDICATE"), $manager.sourceContext, NO)"#) return mapping } static func makeMappingModelV2toV3() -> [NSMappingModel] { // Multiple Passes—Dealing With Large Datasets // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmCustomizing.html#//apple_ref/doc/uid/TP40004399-CH8-SW9 // https://www.objc.io/issues/4-core-data/core-data-migration/ // https://stackoverflow.com/questions/4875553/memory-issues-migrating-large-coredata-datastores-on-iphone // Model for a single mapping model without 2 separate Feedback entity mappings // let mappingModel = NSMappingModel() // mappingModel.entityMappings.append(makeGraphicNovelMapping()) // mappingModel.entityMappings.append(makeFeedbackMapping()) // mappingModel.entityMappings.append(makePageMapping()) // mappingModel.entityMappings.append(makeAuthorMapping()) // mappingModel.entityMappings.append(makeCoverMapping()) // mappingModel.entityMappings.append(makeBookMapping()) // return [mappingModel] let mappingModel1 = NSMappingModel() mappingModel1.entityMappings.append(makeFeedbackMappingPartOne()) mappingModel1.entityMappings.append(makeFeedbackMappingPartTwo()) //mappingModel1.entityMappings.append(makeFeedbackMapping()) let mappingModel2 = NSMappingModel() mappingModel2.entityMappings.append(makePageMapping()) mappingModel2.entityMappings.append(makeCoverMapping()) mappingModel2.entityMappings.append(makeAuthorMapping()) mappingModel2.entityMappings.append(makeBookMapping()) mappingModel2.entityMappings.append(makeGraphicNovelMapping()) // ⚠️ if we use the same NSMigrationManager to to migrate these mapping models, // the order count: [1,2] will fail while [2,1] will succeed. // // In the failing case ([1,2]) it seems that when books are saved a validation error is thrown about // not having enough pages. // This could be solved in 2 ways: // 1. // // bookToPages.isOptional = false // bookToPages.isOrdered = false // bookToPages.minCount = 1 // bookToPages.maxCount = 10_000 // // should be set as: // // bookToPages.isOptional = false // bookToPages.isOrdered = false // bookToPages.minCount = 0 🚩 // bookToPages.maxCount = 10_000 // // 2. // // Recreate the relationship between Book and Page in the BookCoverToCoverMigrationPolicy // in the createDestinationInstances(forSource:in:manager:); we can't do it in createRelationships(forDestination:in:manager:) // because the migration will fail before calling that method. // // Sample error: // "Error Domain=NSCocoaErrorDomain Code=1580 \"Troppi pochi elementi in %{PROPERTY}@.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x7b14000349e0> (entity: Book; id: 0x7b08000ca1a0 <x-coredata:///Book/t64D6FDB7-03DB-4244-90D3-EE867E8019C316396>; data: <fault>), NSLocalizedDescription=Troppi pochi elementi in %{PROPERTY}@., NSValidationErrorKey=pages, NSValidationErrorValue=Relationship 'pages' on managed object (0x7b14000349e0) <NSManagedObject: 0x7b14000349e0> (entity: Book; id: 0x7b08000ca1a0 <x-coredata:///Book/t64D6FDB7-03DB-4244-90D3-EE867E8019C316396>; data: <fault>) with objects {(\n)}}" // Since the error is about having not enough elements, I think that setting minCount to 1 triggers a pre-save validation on the first migration pass (before relationships are set again in the second migration pass). // // I haven't figured it out why inverting the order to [2,1] doesn't cause any errors (the the entities in the mapping models aren't releated). // Maybe these validations aren't triggered in [2,1] because the Book table is created and then populated right away. return [mappingModel1, mappingModel2] } }
mit
5decef56f8679571c8dbc7d352d4d056
46.849415
615
0.739711
4.308715
false
false
false
false
OctMon/OMExtension
OMExtension/OMExtension/Source/Foundation/OMInt.swift
1
2606
// // OMInt.swift // OMExtension // // The MIT License (MIT) // // Copyright (c) 2016 OctMon // // 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 #if !os(macOS) import UIKit #endif public extension Int { struct OM { public static func random(_ range: Range<Int>) -> Int { return random(range.lowerBound, range.upperBound - 1) } public static func random(_ range: ClosedRange<Int>) -> Int { return random(range.lowerBound, range.upperBound) } public static func random(_ lower: Int = 0, _ upper: Int = 9) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - lower + 1))) } } } public extension Int { var omToString: String { return String(self) } var omToDouble: Double { return Double(self) } var omToFloat: Float { return Float(self) } var omToCGFloat: CGFloat { return CGFloat(self) } var omIsEven: Bool { return (self % 2 == 0) } var omIsOdd: Bool { return !omIsEven } var omAbs: Int { return abs(self) } var omLocaleCurrency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self as NSNumber)! } }
mit
4d4ec38b1886ea75372bae804040f745
25.323232
82
0.610898
4.493103
false
false
false
false
Ascoware/get-iplayer-automator
BBCDownload.swift
1
17107
// Converted to Swift 5.7 by Swiftify v5.7.28606 - https://swiftify.com/ // // BBCDownload.swift // Get iPlayer Automator // // Created by Scott Kovatch on 11/9/22. // import Foundation import CocoaLumberjackSwift @objc class BBCDownload: Download { var reasonForFailure: String? // MARK: Overridden Methods required init(programme p: Programme, tvFormats tvFormatList: [TVFormat], radioFormats radioFormatList: [RadioFormat], proxy aProxy: HTTPProxy?) { super.init() reasonForFailure = nil proxy = aProxy show = p defaultsPrefix = "BBC_" downloadPath = UserDefaults.standard.string(forKey: "DownloadPath") ?? "" DDLogInfo("Downloading \(show.showName)") //Initialize Formats var formatArg = "--quality=" var formatStrings: [String] = [] if show.radio { for format in radioFormatList { if let mappedFormat = radioFormats[format.format] as? String { formatStrings.append(mappedFormat) } } } else { for format in tvFormatList { if let mappedFormat = tvFormats[format.format] as? String { formatStrings.append(mappedFormat) } } } let commaSeparatedFormats = formatStrings.joined(separator: ",") formatArg += commaSeparatedFormats //Set Proxy Arguments var proxyArg: String? = nil var partialProxyArg: String? = nil if let aProxy { proxyArg = "-p\(aProxy.url)" if UserDefaults.standard.bool(forKey: "AlwaysUseProxy") { partialProxyArg = "--partial-proxy" } } //Initialize the rest of the arguments let noWarningArg = GetiPlayerArguments.sharedController().noWarningArg let noPurgeArg = "--nopurge" let atomicParsleyPath = URL(fileURLWithPath: AppController.shared().extraBinariesPath).appendingPathComponent("AtomicParsley").path let atomicParsleyArg = "--atomicparsley=\(atomicParsleyPath)" let ffmpegArg = "--ffmpeg=\(URL(fileURLWithPath: AppController.shared().extraBinariesPath).appendingPathComponent("ffmpeg").path)" let downloadPathArg = "--output=\(downloadPath)" let subDirArg = "--subdir" let progressArg = "--logprogress" let getArg = "--pid" let searchArg = show.pid let whitespaceArg = "--whitespace" //AudioDescribed & Signed var needVersions = false var nonDefaultVersions: [String] = [] if UserDefaults.standard.bool(forKey: "AudioDescribedNew") { nonDefaultVersions.append("audiodescribed") needVersions = true } if UserDefaults.standard.bool(forKey: "SignedNew") { nonDefaultVersions.append("signed") needVersions = true } //We don't want this to refresh now! let cacheExpiryArg = GetiPlayerArguments.sharedController().cacheExpiryArg let profileDirArg = GetiPlayerArguments.sharedController().profileDirArg //Add Arguments that can't be NULL var args = [AppController.shared().getiPlayerPath, profileDirArg, noWarningArg, noPurgeArg, atomicParsleyArg, cacheExpiryArg, downloadPathArg, subDirArg, progressArg, formatArg, getArg, searchArg, whitespaceArg, "--attempts=5", "--thumbsize=640", ffmpegArg, "--log-progress"] if let proxyArg { args.append(proxyArg) } if let partialProxyArg { args.append(partialProxyArg) } // Only add a --versions parameter for audio described or signed. Otherwise, let get_iplayer figure it out. if needVersions { nonDefaultVersions.append("default") var versionArg = "--versions=" versionArg += nonDefaultVersions.joined(separator: ",") args.append(versionArg) } //Verbose? if UserDefaults.standard.bool(forKey: "Verbose") { args.append("--verbose") } if UserDefaults.standard.bool(forKey: "DownloadSubtitles") { args.append("--subtitles") if UserDefaults.standard.bool(forKey: "EmbedSubtitles") { args.append("--subs-embed") } } //Naming Convention if !UserDefaults.standard.bool(forKey: "XBMC_naming") { args.append("--file-prefix=<name> - <episode> ((<modeshort>))") } else { args.append("--file-prefix=<nameshort><.senum><.episodeshort>") args.append("--subdir-format=<nameshort>") } // 50 FPS frames? if UserDefaults.standard.bool(forKey: "Use25FPSStreams") { args.append("--tv-lower-bitrate") } //Tagging if !UserDefaults.standard.bool(forKey: "TagShows") { args.append("--no-tag") } for arg in args { DDLogVerbose("\(arg)") } if UserDefaults.standard.bool(forKey: "TagRadioAsPodcast") { args.append("--tag-podcast-radio") show.podcast = true } task = Process() pipe = Pipe() errorPipe = Pipe() task?.arguments = args task?.launchPath = AppController.shared().perlBinaryPath task?.standardOutput = pipe task?.standardError = errorPipe var envVariableDictionary = [String: String]() envVariableDictionary["HOME"] = (("~") as NSString).expandingTildeInPath envVariableDictionary["PERL_UNICODE"] = "AS" envVariableDictionary["PATH"] = AppController.shared().perlEnvironmentPath task?.environment = envVariableDictionary let fh = pipe?.fileHandleForReading let errorFh = errorPipe?.fileHandleForReading NotificationCenter.default.addObserver( self, selector: #selector(downloadDataNotification(_:)), name: FileHandle.readCompletionNotification, object: fh) fh?.readInBackgroundAndNotify() NotificationCenter.default.addObserver( self, selector: #selector(downloadDataNotification(_:)), name: FileHandle.readCompletionNotification, object: errorFh) errorFh?.readInBackgroundAndNotify() NotificationCenter.default.addObserver( self, selector: #selector(downloadFinished(_:)), name: Process.didTerminateNotification, object: task) task?.launch() //Prepare UI setCurrentProgress("Starting download...") show.status = "Starting.." } override var description: String { return "BBC Download (ID=\(show.pid))" } // MARK: Task Control @objc func downloadDataNotification(_ n: Notification?) { if let data = n?.userInfo?[NSFileHandleNotificationDataItem] as? Data, let s = String(data: data, encoding: .utf8) { processGetiPlayerOutput(s) } let fh = n?.object as? FileHandle fh?.readInBackgroundAndNotify() } @objc func downloadFinished(_ notification: Notification?) { if runDownloads.boolValue { complete() } NotificationCenter.default.removeObserver(self) NotificationCenter.default.post(name: NSNotification.Name("DownloadFinished"), object: show) task = nil pipe = nil errorPipe = nil } func complete() { // If we have a path it was successful. Note that and return. if !show.path.isEmpty { show.complete = true show.successful = true show.status = "Download Complete" return } // Handle all other error cases. show.complete = true show.successful = false if let reasonForFailure { show.reasonForFailure = reasonForFailure } if reasonForFailure == "FileExists" { show.status = "Failed: File already exists" DDLogError("\(show.showName) failed, already exists") } else if reasonForFailure == "ShowNotFound" { show.status = "Failed: PID not found" } else if reasonForFailure == "proxy" { let proxyOption = UserDefaults.standard.string(forKey: "Proxy") if proxyOption == "None" { show.status = "Failed: See Log" DDLogError("REASON FOR FAILURE: VPN or System Proxy failed. If you are using a VPN or a proxy configured in System Preferences, contact the VPN or proxy provider for assistance.") show.reasonForFailure = "ShowNotFound" } else if proxyOption == "Provided" { show.status = "Failed: Bad Proxy" DDLogError("REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences.") show.reasonForFailure = "Provided_Proxy" } else if proxyOption == "Custom" { show.status = "Failed: Bad Proxy" DDLogError("REASON FOR FAILURE: Proxy failed. If in the UK, please disable the proxy in the preferences.") DDLogError("If outside the UK, please use a different proxy.") show.reasonForFailure = "Custom_Proxy" } DDLogError("\(show.showName) failed") } else if reasonForFailure == "Specified_Modes" { show.status = "Failed: No Specified Modes" DDLogError("REASON FOR FAILURE: None of the modes in your download format list are available for this show.") DDLogError("Try adding more modes.") DDLogError("\(show.showName) failed") } else if reasonForFailure == "InHistory" { show.status = "Failed: In download history" DDLogError("InHistory") } else if reasonForFailure == "AudioDescribedOnly" { show.reasonForFailure = "AudioDescribedOnly" } else if reasonForFailure == "External_Disconnected" { show.status = "Failed: HDD not Accessible" DDLogError("REASON FOR FAILURE: The specified download directory could not be written to.") DDLogError("Most likely this is because your external hard drive is disconnected but it could also be a permission issue") DDLogError("\(show.showName) failed") } else if reasonForFailure == "Download_Directory_Permissions" { show.status = "Failed: Download Directory Unwriteable" DDLogError("REASON FOR FAILURE: The specified download directory could not be written to.") DDLogError("Please check the permissions on your download directory.") DDLogError("\(show.showName) failed") } else { // Failed for an unknown reason. show.status = "Download Failed" DDLogError("\(show.showName) failed") } } func processGetiPlayerOutput(_ outp: String?) { let array = outp?.components(separatedBy: .newlines) //Parse each line individually. for output in array ?? [] { if output.count == 0 { continue } if output.hasPrefix("DEBUG:") { DDLogDebug("\(output)") } else if output.hasPrefix("WARNING:") { DDLogWarn("\(output)") } else { DDLogInfo("\(output)") } if output.hasPrefix("INFO: Downloading subtitles") { let scanner = Scanner(string: output) var srtPath: String? scanner.scanString("INFO: Downloading Subtitles to \'", into: nil) srtPath = scanner.scanUpToString(".srt\'") srtPath = URL(fileURLWithPath: srtPath ?? "").appendingPathExtension("srt").path show.subtitlePath = srtPath ?? "" } else if output.hasPrefix("INFO: Wrote file ") { let scanner = Scanner(string: output) scanner.scanString("INFO: Wrote file ", into: nil) let path = scanner.scanUpToCharactersFromSet(set: .newlines) show.path = path ?? "" } else if output.hasPrefix("INFO: No specified modes") && output.hasSuffix("--quality=)") { reasonForFailure = "Specified_Modes" let modeScanner = Scanner(string: output) modeScanner.scanUpTo("--quality=", into: nil) modeScanner.scanString("--quality=", into: nil) let availableModes = modeScanner.scanUpToString(")") show.availableModes = availableModes ?? "" } else if output.hasSuffix("use --force to override") { reasonForFailure = "InHistory" } else if output.contains("Permission denied") { if output.contains("/Volumes") { //Most likely disconnected external HDD { reasonForFailure = "External_Disconnected" } else { reasonForFailure = "Download_Directory_Permissions" } } else if output.hasPrefix("WARNING: Use --overwrite") { reasonForFailure = "FileExists" } else if output.hasPrefix("ERROR: Failed to get version pid") { reasonForFailure = "ShowNotFound" } else if output.hasPrefix("WARNING: If you use a VPN") || output.hasSuffix("blocked by the BBC") { reasonForFailure = "proxy" } else if output.hasPrefix("WARNING: No programmes are available for this pid with version(s):") || output.hasPrefix("INFO: No versions of this programme were selected") { let versionScanner = Scanner(string: output) versionScanner.scanUpTo("available versions:", into: nil) versionScanner.scanString("available versions:", into: nil) versionScanner.scanCharacters(from: .whitespaces, into: nil) let availableVersions = versionScanner.scanUpToString(")") if (availableVersions as NSString?)?.range(of: "audiodescribed").location != NSNotFound || (availableVersions as NSString?)?.range(of: "signed").location != NSNotFound { reasonForFailure = "AudioDescribedOnly" } } else if output.hasPrefix("INFO: Downloading thumbnail") { show.status = "Downloading Artwork.." setPercentage(102) setCurrentProgress("Downloading Artwork.. -- \(show.showName)") } else if output.hasPrefix("INFO:") || output.hasPrefix("WARNING:") || output.hasPrefix("ERROR:") || output.hasSuffix("default") || output.hasPrefix(show.pid) { // Do nothing! This ensures we don't process any other info messages } else if output.hasSuffix("[audio+video]") || output.hasSuffix("[audio]") || output.hasSuffix("[video]") { //Process iPhone/Radio Downloads Status Message let scanner = Scanner(string: output) var percentage: Decimal? var h: Decimal? var m: Decimal? var s: Decimal? scanner.scanUpToCharacters( from: .decimalDigits, into: nil) percentage = scanner.scanDecimal() setPercentage(NSDecimalNumber(decimal: percentage ?? .zero).doubleValue) // Jump ahead to the ETA field. scanner.scanUpTo("ETA: ", into: nil) scanner.scanString("ETA: ", into: nil) scanner.scanUpToCharacters( from: .decimalDigits, into: nil) h = scanner.scanDecimal() scanner.scanUpToCharacters( from: .decimalDigits, into: nil) m = scanner.scanDecimal() scanner.scanUpToCharacters( from: .decimalDigits, into: nil) s = scanner.scanDecimal() scanner.scanUpToCharacters( from: .decimalDigits, into: nil) let eta = String(format: "%.2ld:%.2ld:%.2ld remaining", NSDecimalNumber(decimal: h ?? .zero).intValue, NSDecimalNumber(decimal: m ?? .zero).intValue, NSDecimalNumber(decimal: s ?? .zero).intValue) setCurrentProgress(eta) var format = "Video downloaded: %ld%%" if output.hasSuffix("[audio+video]") { format = "Downloaded %ld%%" } else if output.hasSuffix("[audio]") { format = "Audio download: %ld%%" } else if output.hasSuffix("[video]") { format = "Video download: %ld%%" } if let percentage { show.status = String(format: format, NSDecimalNumber(decimal: percentage).intValue) } } } } }
gpl-3.0
d24beedc9254bab0234de732dadce373
41.031941
283
0.58099
4.968632
false
false
false
false
exponent/exponent
ios/vendored/sdk42/stripe-react-native/ios/PaymentMethodFactory.swift
2
12708
import Foundation import Stripe class PaymentMethodFactory { var billingDetailsParams: STPPaymentMethodBillingDetails? = nil var params: NSDictionary? = nil var cardFieldView: CardFieldView? = nil init(params: NSDictionary, cardFieldView: CardFieldView?) { self.billingDetailsParams = Mappers.mapToBillingDetails(billingDetails: params["billingDetails"] as? NSDictionary) self.params = params self.cardFieldView = cardFieldView } func createParams(paymentMethodType: STPPaymentMethodType) throws -> STPPaymentMethodParams? { do { switch paymentMethodType { case STPPaymentMethodType.iDEAL: return try createIDEALPaymentMethodParams() case STPPaymentMethodType.OXXO: return try createOXXOPaymentMethodParams() case STPPaymentMethodType.card: return try createCardPaymentMethodParams() case STPPaymentMethodType.FPX: return try createFPXPaymentMethodParams() case STPPaymentMethodType.alipay: return try createAlipayPaymentMethodParams() case STPPaymentMethodType.sofort: return try createSofortPaymentMethodParams() case STPPaymentMethodType.bancontact: return try createBancontactPaymentMethodParams() case STPPaymentMethodType.SEPADebit: return try createSepaPaymentMethodParams() case STPPaymentMethodType.giropay: return try createGiropayPaymentMethodParams() case STPPaymentMethodType.EPS: return try createEPSPaymentMethodParams() case STPPaymentMethodType.grabPay: return createGrabpayPaymentMethodParams() case STPPaymentMethodType.przelewy24: return try createP24PaymentMethodParams() case STPPaymentMethodType.AUBECSDebit: return try createBECSDebitPaymentMethodParams() case STPPaymentMethodType.afterpayClearpay: return try createAfterpayClearpayPaymentMethodParams() default: throw PaymentMethodError.paymentNotSupported } } catch { throw error } } func createOptions(paymentMethodType: STPPaymentMethodType) throws -> STPConfirmPaymentMethodOptions? { do { switch paymentMethodType { case STPPaymentMethodType.iDEAL: return nil case STPPaymentMethodType.EPS: return nil case STPPaymentMethodType.card: return createCardPaymentMethodOptions() case STPPaymentMethodType.FPX: return nil case STPPaymentMethodType.sofort: return nil case STPPaymentMethodType.alipay: return try createAlipayPaymentMethodOptions() case STPPaymentMethodType.bancontact: return nil case STPPaymentMethodType.SEPADebit: return nil case STPPaymentMethodType.OXXO: return nil case STPPaymentMethodType.giropay: return nil case STPPaymentMethodType.grabPay: return nil case STPPaymentMethodType.przelewy24: return nil case STPPaymentMethodType.AUBECSDebit: return nil case STPPaymentMethodType.afterpayClearpay: return nil default: throw PaymentMethodError.paymentNotSupported } } catch { throw error } } private func createIDEALPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodiDEALParams() if let bankName = self.params?["bankName"] as? String { params.bankName = bankName } return STPPaymentMethodParams(iDEAL: params, billingDetails: billingDetailsParams, metadata: nil) } private func createGrabpayPaymentMethodParams() -> STPPaymentMethodParams { let params = STPPaymentMethodGrabPayParams() return STPPaymentMethodParams(grabPay: params, billingDetails: billingDetailsParams, metadata: nil) } private func createCardPaymentMethodParams() throws -> STPPaymentMethodParams { if let token = params?["token"] as? String { let methodParams = STPPaymentMethodCardParams() methodParams.token = ABI42_0_0RCTConvert.nsString(token) return STPPaymentMethodParams(card: methodParams, billingDetails: billingDetailsParams, metadata: nil) } guard let cardParams = cardFieldView?.cardParams else { throw PaymentMethodError.cardPaymentMissingParams } return STPPaymentMethodParams(card: cardParams, billingDetails: billingDetailsParams, metadata: nil) } private func createCardPaymentMethodOptions() -> STPConfirmPaymentMethodOptions? { let cvc = params?["cvc"] as? String guard cvc != nil else { return nil } let cardOptions = STPConfirmCardOptions() cardOptions.cvc = cvc; let paymentMethodOptions = STPConfirmPaymentMethodOptions() paymentMethodOptions.cardOptions = cardOptions return paymentMethodOptions } private func createFPXPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodFPXParams() if self.params?["testOfflineBank"] as? Bool == true { params.rawBankString = "test_offline_bank" } return STPPaymentMethodParams(fpx: params, billingDetails: billingDetailsParams, metadata: nil) } private func createAlipayPaymentMethodParams() throws -> STPPaymentMethodParams { return STPPaymentMethodParams(alipay: STPPaymentMethodAlipayParams(), billingDetails: billingDetailsParams, metadata: nil) } private func createP24PaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodPrzelewy24Params() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.p24PaymentMissingParams } return STPPaymentMethodParams(przelewy24: params, billingDetails: billingDetails, metadata: nil) } private func createAlipayPaymentMethodOptions() throws -> STPConfirmPaymentMethodOptions { let options = STPConfirmPaymentMethodOptions() options.alipayOptions = STPConfirmAlipayOptions() return options } private func createSofortPaymentMethodParams() throws -> STPPaymentMethodParams { guard let country = self.params?["country"] as? String else { throw PaymentMethodError.sofortPaymentMissingParams } let params = STPPaymentMethodSofortParams() params.country = country return STPPaymentMethodParams(sofort: params, billingDetails: billingDetailsParams, metadata: nil) } private func createBancontactPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodBancontactParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.bancontactPaymentMissingParams } return STPPaymentMethodParams(bancontact: params, billingDetails: billingDetails, metadata: nil) } private func createSepaPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodSEPADebitParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.sepaPaymentMissingParams } guard let iban = self.params?["iban"] as? String else { throw PaymentMethodError.sepaPaymentMissingParams } params.iban = iban return STPPaymentMethodParams(sepaDebit: params, billingDetails: billingDetails, metadata: nil) } private func createOXXOPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodOXXOParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.bancontactPaymentMissingParams } return STPPaymentMethodParams(oxxo: params, billingDetails: billingDetails, metadata: nil) } private func createGiropayPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodGiropayParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.giropayPaymentMissingParams } return STPPaymentMethodParams(giropay: params, billingDetails: billingDetails, metadata: nil) } private func createEPSPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodEPSParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.epsPaymentMissingParams } return STPPaymentMethodParams(eps: params, billingDetails: billingDetails, metadata: nil) } private func createBECSDebitPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodAUBECSDebitParams() let billingDetails = STPPaymentMethodBillingDetails() let formDetails = self.params?["formDetails"] as? NSDictionary billingDetails.name = formDetails?["name"] as? String billingDetails.email = formDetails?["email"] as? String params.accountNumber = formDetails?["accountNumber"] as? String params.bsbNumber = formDetails?["bsbNumber"] as? String return STPPaymentMethodParams(aubecsDebit: params, billingDetails: billingDetails, metadata: nil) } private func createAfterpayClearpayPaymentMethodParams() throws -> STPPaymentMethodParams { let params = STPPaymentMethodAfterpayClearpayParams() guard let billingDetails = billingDetailsParams else { throw PaymentMethodError.afterpayClearpayPaymentMissingParams } return STPPaymentMethodParams(afterpayClearpay: params, billingDetails: billingDetails, metadata: nil) } } enum PaymentMethodError: Error { case cardPaymentMissingParams case epsPaymentMissingParams case idealPaymentMissingParams case paymentNotSupported case sofortPaymentMissingParams case cardPaymentOptionsMissingParams case bancontactPaymentMissingParams case sepaPaymentMissingParams case giropayPaymentMissingParams case p24PaymentMissingParams case afterpayClearpayPaymentMissingParams } extension PaymentMethodError: LocalizedError { public var errorDescription: String? { switch self { case .cardPaymentMissingParams: return NSLocalizedString("Card details not complete", comment: "Create payment error") case .giropayPaymentMissingParams: return NSLocalizedString("You must provide billing details", comment: "Create payment error") case .idealPaymentMissingParams: return NSLocalizedString("You must provide bank name", comment: "Create payment error") case .sofortPaymentMissingParams: return NSLocalizedString("You must provide bank account country", comment: "Create payment error") case .p24PaymentMissingParams: return NSLocalizedString("You must provide billing details", comment: "Create payment error") case .bancontactPaymentMissingParams: return NSLocalizedString("You must provide billing details", comment: "Create payment error") case .sepaPaymentMissingParams: return NSLocalizedString("You must provide billing details and IBAN", comment: "Create payment error") case .epsPaymentMissingParams: return NSLocalizedString("You must provide billing details", comment: "Create payment error") case .afterpayClearpayPaymentMissingParams: return NSLocalizedString("You must provide billing details", comment: "Create payment error") case .paymentNotSupported: return NSLocalizedString("This payment type is not supported yet", comment: "Create payment error") case .cardPaymentOptionsMissingParams: return NSLocalizedString("You must provide CVC number", comment: "Create payment error") } } }
bsd-3-clause
28689fa42f5fa29ff9d0d93d168699c5
41.501672
130
0.677919
5.918957
false
false
false
false
einsteinx2/iSub
Frameworks/EX2Kit/NetworkIndicator.swift
1
1122
// // NetworkIndicator.swift // iSub // // Created by Benjamin Baron on 1/26/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class NetworkIndicator { fileprivate static let lock = SpinLock() fileprivate static var counter = 0 static func usingNetwork() { lock.synchronized { counter += 1 async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } } } static func doneUsingNetwork() { lock.synchronized { if counter > 0 { counter -= 1 if counter == 0 { async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } } } } static func goingOffline() { lock.synchronized { if counter > 0 { counter = 0 async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } } } }
gpl-3.0
50a4bd8bfeaa5c81b449c29ce180e0a6
22.851064
86
0.491525
5.690355
false
false
false
false
ahmedabadie/ABNScheduler-travis
ABNSDemo/SecondViewController.swift
1
3103
// // SecondViewController.swift // ABNSDemo // // Created by Ahmed Abdul Badie on 3/15/16. // Copyright © 2016 Ahmed Abdul Badie. All rights reserved. // import UIKit class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var scheduled: [ABNotification]? var queued: [ABNotification]? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. scheduled = ABNScheduler.scheduledNotifications() queued = ABNScheduler.notificationsQueue() } override func viewWillAppear(_ animated: Bool) { self.tabBarController!.navigationItem.rightBarButtonItem?.isEnabled = false self.tabBarController!.navigationItem.leftBarButtonItem?.isEnabled = false scheduled = ABNScheduler.scheduledNotifications() queued = ABNScheduler.notificationsQueue() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Table View func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "notificationCell") if indexPath.section == 0 { let alertBody = scheduled?[indexPath.row].alertBody let repeatInterval = (scheduled?[indexPath.row].repeatInterval.rawValue) cell.textLabel!.text = "\(alertBody!) -- Repeats: \(repeatInterval!)" if let date = scheduled?[indexPath.row].fireDate { cell.detailTextLabel!.text = String(describing: date) } } else { let alertBody = queued?[indexPath.row].alertBody let repeatInterval = (queued?[indexPath.row].repeatInterval.rawValue) cell.textLabel!.text = "\(alertBody!) -- Repeats: \(repeatInterval!)" if let date = queued?[indexPath.row].fireDate { cell.detailTextLabel!.text = "Fire date: " + String(describing: date) } } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return ABNScheduler.scheduledCount() case 1: return ABNScheduler.queuedCount() default: return 0 } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 54 } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Scheduled: \(String(ABNScheduler.scheduledCount()))" case 1: return "Queued: \(String(ABNScheduler.queuedCount()))" default: return nil } } }
mit
72cb7304a353edb7d5050848477ff232
35.069767
109
0.643778
5.385417
false
false
false
false
SirWellington/sir-wellington-mall
SirWellingtonMall/SirWellingtonMall/ProductListViewController.swift
1
4339
// // InventoryViewController.swift // SirWellingtonMall // // Created by Juan Wellington Moreno on 5/14/16. // Copyright © 2016 Sir Wellington. All rights reserved. // import AromaSwiftClient import Foundation import UIKit class ProductListViewController : UICollectionViewController { private var products: [Product] = Products.BASIC_INVENTORY var onProductSelected: ((Product) -> Void)? = nil private var emptyCell: UICollectionViewCell { return UICollectionViewCell() } override func viewDidLoad() { super.viewDidLoad() } } //MARK: Segues & Unwinds extension ProductListViewController { override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } private func unwind() { self.performSegueWithIdentifier("unwind", sender: self) } @IBAction func unwindFromAddProduct(segue: UIStoryboardSegue) { let source = segue.sourceViewController if let lastStep = source as? AddProduct3ViewController, product = lastStep.product { self.onProductAdded(product) } } } //MARK: Product List Modifications extension ProductListViewController { private func onProductAdded(newProduct: Product) { self.products.append(newProduct) self.collectionView?.reloadData() AromaClient.sendMediumPriorityMessage(withTitle: "Product Added", withBody: "\(newProduct)") } } //MARK: Collection View Data Source Methods extension ProductListViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let row = indexPath.row guard row >= 0 && row < products.count else { AromaClient.beginWithTitle("Bad Logic") .withPriority(.MEDIUM) .addBody("InventoryViewController").addLine() .addBody("Unexpected Row#: \(row)") .send() return emptyCell } let product = products[row] guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProductCell", forIndexPath: indexPath) as? ProductCell else { AromaClient.beginWithTitle("Collection View Error") .addBody("Failed to deque InventoryCell. Returning Empty cell.") .withPriority(.MEDIUM) .send() return emptyCell } populateCell(cell, withProduct: product, atIndexPath: indexPath) return cell } private func populateCell(cell: ProductCell, withProduct product: Product, atIndexPath path: NSIndexPath) { cell.productName.text = product.name cell.productImage.image = product.getImage() } } //MARK: Collection View Delegate Methods extension ProductListViewController : UICollectionViewDelegateFlowLayout { override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row guard row >= 0 && row < products.count else { AromaClient.sendHighPriorityMessage(withTitle: "Bad Logic", withBody: "Unexpected Row #\(row)") return } let product = self.products[row] onProductSelected?(product) self.unwind() } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width = self.view.frame.width * 0.45 let height = width return CGSize(width: width, height: height) } } class ProductCell: UICollectionViewCell { @IBOutlet private weak var productImage: UIImageView! @IBOutlet private weak var productName: UILabel! }
mit
96d9f1f8dfa1370097c285c9bc1a0cb5
27.175325
169
0.641079
5.590206
false
false
false
false
dourgulf/SwiftByProject
functional-thinking/functional-thinking/PerfectNumber.swift
1
1565
// // PerfectNumber.swift // functional-thinking // // Created by jinchu darwin on 16/2/23. // Copyright © 2016年 FullStackOrient. All rights reserved. // import Foundation public enum ClassifierType { case Perfect case Abundant(Int) case Deficient(Int) } func memoize<T:Hashable, U>(fn : T -> U) -> T -> U { var cache = [T:U]() return { (val : T) -> U in if cache.indexForKey(val) == nil { cache[val] = fn(val) } return cache[val]! } } var factorsOf: (Int) -> [Int] = memoize { number in print("1 calculating") return Range(1...number).filter { potential in return number % potential == 0 } } public func factorsOf(number: Int) -> [Int] { print("2 calculating") return Range(1...number).filter { potential in return number % potential == 0 } } public func aliquotSum(number: Int) -> Int{ return factorsOf(number).reduce(0, combine: +) - number } public func isPerfect(number: Int) -> Bool { return aliquotSum(number) == number } public func isAbundant(number: Int) -> Bool { return aliquotSum(number) > number } public func isDeficient(number: Int) -> Bool { return aliquotSum(number) < number } public func classify(number: Int) -> ClassifierType { let sum = aliquotSum(number) if sum == number { return .Perfect } else if sum > number { return .Abundant(sum) } else { return .Deficient(sum) } } func carryfun(a: Int)(_ b: Int)(_ c: Int) ->Int { return a+b+c; }
gpl-3.0
29ebd163c5ea371877dfe512ca0e77c7
20.108108
59
0.600512
3.344754
false
false
false
false
Guicai-Li/iOS_Tutorial
Flo/Flo/PushButtonView.swift
1
1919
// // PushButtonView.swift // Flo // // Created by 力贵才 on 15/12/2. // Copyright © 2015年 Guicai.Li. All rights reserved. // import UIKit @IBDesignable class PushButtonView: UIButton { @IBInspectable var fillColor: UIColor = UIColor.greenColor() @IBInspectable var isAddButton: Bool = true override func drawRect(rect: CGRect) { var path = UIBezierPath(ovalInRect: rect) fillColor.setFill() path.fill() //set up the width and height variables //for the horizontal stroke let plusHeight: CGFloat = 3.0 let plusWidth: CGFloat = min(bounds.width, bounds.height) * 0.6 //create the path var plusPath = UIBezierPath() //set the path's line width to the height of the stroke plusPath.lineWidth = plusHeight //move the initial point of the path //to the start of the horizontal stroke plusPath.moveToPoint(CGPoint( x:bounds.width/2 - plusWidth/2 + 0.5, y:bounds.height/2 + 0.5)) //add a point to the path at the end of the stroke plusPath.addLineToPoint(CGPoint( x:bounds.width/2 + plusWidth/2 + 0.5, y:bounds.height/2 + 0.5)) //Vertical Line if isAddButton { //move to the start of the vertical stroke plusPath.moveToPoint(CGPoint( x:bounds.width/2 + 0.5, y:bounds.height/2 - plusWidth/2 + 0.5)) //add the end point to the vertical stroke plusPath.addLineToPoint(CGPoint( x:bounds.width/2 + 0.5, y:bounds.height/2 + plusWidth/2 + 0.5)) } //set the stroke color UIColor.whiteColor().setStroke() //draw the stroke plusPath.stroke() } }
apache-2.0
34de2658b46e9231998649f6f6a766dd
27.939394
71
0.55445
4.370709
false
false
false
false
KordianKL/SongGenius
Song Genius/API/API.swift
1
2515
// // API.swift // Song Genius // // Created by Kordian Ledzion on 15.06.2017. // Copyright © 2017 KordianLedzion. All rights reserved. // import Foundation import Alamofire enum Endpoint { case getSongs(forTerm: String) var url: String { switch self { case .getSongs(let forTerm): return forTerm.replacingOccurrences(of: " ", with: "+") } } //We'll be covering only one HTTP method but WHO KNOWS?! growth potential for the win var method: Alamofire.HTTPMethod { switch self { case .getSongs: return .get } } } final class API { // country = pl because we're in Poland and we want Polish market // limit = 50 seems reasonable // media = music we obviously want music only (not musicVideos, software etc) // entity = song we want songs returned (not albums, artist only etc) // term = ?? user's input here (with & removed and spaces changed to "&" static func request(_ endpoint: Endpoint, completion: @escaping ((Result<Any, DataSourceError>) -> Void)) -> DataRequest { let url = URL(string: "https://itunes.apple.com/search?country=pl&limit=50&entity=song&media=music&term=\(endpoint.url)")! switch endpoint { case .getSongs: let request = Alamofire.request(url, method: endpoint.method) request.responseJSON { response in switch response.result { case .success(let value): completion(Result.success(value)) case .failure(let error): completion(Result.failure(DataSourceError.connectivityProblem(description: error.localizedDescription))) } } return request } } } //Maybe RxSwift will be fixed one day 😅 //extension API: ReactiveCompatible {} // //extension Reactive where Base: API { // func request(_ endpoint: Endpoint) -> Observable<[Song]> { // return Observable.create { observer in // let request = API.request( endpoint, completion: { success, songs in // if(success) { // observer.onNext(songs!) // } else { // observer.onNext([Song]()) // } // }) // return Disposables.create { // request.cancel() // } // }.observeOn(MainScheduler.instance) // } //}
mit
f6c231125bc0c61e9d94f22b8c21b0dc
30
130
0.564715
4.467972
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Director/ApplicationDirectorTestBuilder.swift
1
13584
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import UIKit.UIViewController class StubCollectThemAllModuleProviding: CollectThemAllModuleProviding { let stubInterface = FakeViewController() func makeCollectThemAllModule() -> UIViewController { return stubInterface } } class StubMapsModuleProviding: MapsModuleProviding { let stubInterface = FakeViewController() private(set) var delegate: MapsModuleDelegate? func makeMapsModule(_ delegate: MapsModuleDelegate) -> UIViewController { self.delegate = delegate return stubInterface } } extension StubMapsModuleProviding { func simulateDidSelectMap(_ map: MapIdentifier) { delegate?.mapsModuleDidSelectMap(identifier: map) } } class StubMapDetailModuleProviding: MapDetailModuleProviding { let stubInterface = UIViewController() private(set) var capturedModel: MapIdentifier? private(set) var delegate: MapDetailModuleDelegate? func makeMapDetailModule(for map: MapIdentifier, delegate: MapDetailModuleDelegate) -> UIViewController { capturedModel = map self.delegate = delegate return stubInterface } } extension StubMapDetailModuleProviding { func simulateDidSelectDealer(_ dealer: DealerIdentifier) { delegate?.mapDetailModuleDidSelectDealer(dealer) } } class StubAnnouncementsModuleProviding: AnnouncementsModuleProviding { let stubInterface = UIViewController() private(set) var delegate: AnnouncementsModuleDelegate? func makeAnnouncementsModule(_ delegate: AnnouncementsModuleDelegate) -> UIViewController { self.delegate = delegate return stubInterface } } extension StubAnnouncementsModuleProviding { func simulateDidSelectAnnouncement(_ announcement: AnnouncementIdentifier) { delegate?.announcementsModuleDidSelectAnnouncement(announcement) } } class StubKnowledgeGroupEntriesModuleProviding: KnowledgeGroupEntriesModuleProviding { let stubInterface = UIViewController() private(set) var delegate: KnowledgeGroupEntriesModuleDelegate? private(set) var capturedModel: KnowledgeGroupIdentifier? func makeKnowledgeGroupEntriesModule(_ groupIdentifier: KnowledgeGroupIdentifier, delegate: KnowledgeGroupEntriesModuleDelegate) -> UIViewController { capturedModel = groupIdentifier self.delegate = delegate return stubInterface } } extension StubKnowledgeGroupEntriesModuleProviding { func simulateKnowledgeEntrySelected(_ entry: KnowledgeEntryIdentifier) { delegate?.knowledgeGroupEntriesModuleDidSelectKnowledgeEntry(identifier: entry) } } class StubEventFeedbackModuleProviding: EventFeedbackModuleProviding { let stubInterface = UIViewController() private(set) var eventToLeaveFeedbackFor: EventIdentifier? private var delegate: EventFeedbackModuleDelegate? func makeEventFeedbackModule(for event: EventIdentifier, delegate: EventFeedbackModuleDelegate) -> UIViewController { eventToLeaveFeedbackFor = event self.delegate = delegate return stubInterface } func simulateDismissFeedback() { delegate?.eventFeedbackCancelled() } } class StubAdditionalServicesModuleProviding: AdditionalServicesModuleProviding { let stubInterface = UIViewController() func makeAdditionalServicesModule() -> UIViewController { return stubInterface } } class ApplicationDirectorTestBuilder { struct Context { var director: ApplicationDirector var moduleOrderingPolicy: ModuleOrderingPolicy var rootModule: StubRootModuleFactory var tutorialModule: StubTutorialModuleFactory var preloadModule: StubPreloadModuleFactory var tabModule: StubTabModuleFactory var newsModule: StubNewsModuleFactory var scheduleModule: StubScheduleModuleFactory var dealersModule: StubDealersModuleFactory var dealerDetailModule: StubDealerDetailModuleProviding var collectThemAllModule: StubCollectThemAllModuleProviding var messages: StubMessagesModuleFactory var loginModule: StubLoginModuleFactory var windowWireframe: CapturingWindowWireframe var messageDetailModule: StubMessageDetailModuleProviding var knowledgeListModule: StubKnowledgeGroupsListModuleProviding var knowledgeGroupEntriesModule: StubKnowledgeGroupEntriesModuleProviding var knowledgeDetailModule: StubKnowledgeDetailModuleProviding var mapsModule: StubMapsModuleProviding var mapDetailModule: StubMapDetailModuleProviding var announcementsModule: StubAnnouncementsModuleProviding var announcementDetailModule: StubAnnouncementDetailModuleFactory var eventDetailModule: StubEventDetailModuleFactory var eventFeedbackModule: StubEventFeedbackModuleProviding var additionalServicesModule: StubAdditionalServicesModuleProviding var linkRouter: StubContentLinksService var webModuleProviding: StubWebMobuleProviding var urlOpener: CapturingURLOpener } private var moduleOrderingPolicy: ModuleOrderingPolicy private let rootModule: StubRootModuleFactory private let tutorialModule: StubTutorialModuleFactory private let preloadModule: StubPreloadModuleFactory private let tabModule: StubTabModuleFactory private let newsModule: StubNewsModuleFactory private let scheduleModule: StubScheduleModuleFactory private let dealersModule: StubDealersModuleFactory private let dealerDetailModule: StubDealerDetailModuleProviding private let collectThemAllModule: StubCollectThemAllModuleProviding private let messagesModule: StubMessagesModuleFactory private let loginModule: StubLoginModuleFactory private let windowWireframe: CapturingWindowWireframe private let messageDetailModule: StubMessageDetailModuleProviding private let knowledgeListModule: StubKnowledgeGroupsListModuleProviding private let knowledgeGroupEntriesModule: StubKnowledgeGroupEntriesModuleProviding private let knowledgeDetailModule: StubKnowledgeDetailModuleProviding private let mapsModule: StubMapsModuleProviding private let mapDetailModule: StubMapDetailModuleProviding private let announcementsModule: StubAnnouncementsModuleProviding private let announcementDetailModule: StubAnnouncementDetailModuleFactory private let eventDetailModule: StubEventDetailModuleFactory private let eventFeedbackModule: StubEventFeedbackModuleProviding private let additionalServicesModule: StubAdditionalServicesModuleProviding private let linkRouter: StubContentLinksService private let webModuleProviding: StubWebMobuleProviding private let urlOpener: CapturingURLOpener private struct DoNotChangeOrderPolicy: ModuleOrderingPolicy { func order(modules: [UIViewController]) -> [UIViewController] { return modules } func saveOrder(_ modules: [UIViewController]) { } } init() { moduleOrderingPolicy = DoNotChangeOrderPolicy() rootModule = StubRootModuleFactory() tutorialModule = StubTutorialModuleFactory() preloadModule = StubPreloadModuleFactory() windowWireframe = CapturingWindowWireframe() tabModule = StubTabModuleFactory() newsModule = StubNewsModuleFactory() scheduleModule = StubScheduleModuleFactory() dealersModule = StubDealersModuleFactory() dealerDetailModule = StubDealerDetailModuleProviding() collectThemAllModule = StubCollectThemAllModuleProviding() messagesModule = StubMessagesModuleFactory() loginModule = StubLoginModuleFactory() messageDetailModule = StubMessageDetailModuleProviding() knowledgeListModule = StubKnowledgeGroupsListModuleProviding() knowledgeGroupEntriesModule = StubKnowledgeGroupEntriesModuleProviding() knowledgeDetailModule = StubKnowledgeDetailModuleProviding() mapsModule = StubMapsModuleProviding() mapDetailModule = StubMapDetailModuleProviding() announcementsModule = StubAnnouncementsModuleProviding() announcementDetailModule = StubAnnouncementDetailModuleFactory() eventDetailModule = StubEventDetailModuleFactory() eventFeedbackModule = StubEventFeedbackModuleProviding() additionalServicesModule = StubAdditionalServicesModuleProviding() linkRouter = StubContentLinksService() webModuleProviding = StubWebMobuleProviding() urlOpener = CapturingURLOpener() } @discardableResult func with(_ orderingPolicy: ModuleOrderingPolicy) -> ApplicationDirectorTestBuilder { self.moduleOrderingPolicy = orderingPolicy return self } func build() -> Context { let director = makeDirectorBuilder().build() return Context(director: director, moduleOrderingPolicy: moduleOrderingPolicy, rootModule: rootModule, tutorialModule: tutorialModule, preloadModule: preloadModule, tabModule: tabModule, newsModule: newsModule, scheduleModule: scheduleModule, dealersModule: dealersModule, dealerDetailModule: dealerDetailModule, collectThemAllModule: collectThemAllModule, messages: messagesModule, loginModule: loginModule, windowWireframe: windowWireframe, messageDetailModule: messageDetailModule, knowledgeListModule: knowledgeListModule, knowledgeGroupEntriesModule: knowledgeGroupEntriesModule, knowledgeDetailModule: knowledgeDetailModule, mapsModule: mapsModule, mapDetailModule: mapDetailModule, announcementsModule: announcementsModule, announcementDetailModule: announcementDetailModule, eventDetailModule: eventDetailModule, eventFeedbackModule: eventFeedbackModule, additionalServicesModule: additionalServicesModule, linkRouter: linkRouter, webModuleProviding: webModuleProviding, urlOpener: urlOpener) } private func makeDirectorBuilder() -> DirectorBuilder { let moduleRepository = FakeModuleRepository(webModuleProviding: webModuleProviding, rootModuleProviding: rootModule, tutorialModuleProviding: tutorialModule, preloadModuleProviding: preloadModule, newsModuleProviding: newsModule, scheduleModuleProviding: scheduleModule, dealersModuleProviding: dealersModule, dealerDetailModuleProviding: dealerDetailModule, collectThemAllModuleProviding: collectThemAllModule, messagesModuleProviding: messagesModule, loginModuleProviding: loginModule, messageDetailModuleProviding: messageDetailModule, knowledgeListModuleProviding: knowledgeListModule, knowledgeGroupEntriesModule: knowledgeGroupEntriesModule, knowledgeDetailModuleProviding: knowledgeDetailModule, mapsModuleProviding: mapsModule, mapDetailModuleProviding: mapDetailModule, announcementsModuleFactory: announcementsModule, announcementDetailModuleProviding: announcementDetailModule, eventDetailModuleProviding: eventDetailModule, eventFeedbackModuleProviding: eventFeedbackModule, additionalServicesModule: additionalServicesModule) let builder = DirectorBuilder(moduleRepository: moduleRepository, linkLookupService: linkRouter) builder.withAnimations(false) builder.with(moduleOrderingPolicy) builder.with(windowWireframe) builder.with(StubNavigationControllerFactory()) builder.with(tabModule) builder.with(urlOpener) return builder } } extension ApplicationDirectorTestBuilder.Context { func navigateToTabController() { rootModule.simulateStoreShouldBeRefreshed() preloadModule.simulatePreloadFinished() } func navigationController(for viewController: UIViewController) -> CapturingNavigationController? { return tabModule.navigationController(for: viewController) } }
mit
d5606d2ecd56fcd9602a2bb9878892a0
42.678457
154
0.690518
6.758209
false
false
false
false
EZ-NET/ESCSVParser
ESCSVParserTests/ESCSVParserTests.swift
1
2190
// // ESCSVParserTests.swift // ESCSVParserTests // // Created by Tomohiro Kumagai on H27/07/15. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import XCTest @testable import ESCSVParser class ESCSVParserTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseFile1() { do { let path = NSBundle(forClass: self.dynamicType).pathForResource("Sample1", ofType: "csv")! let csv = try CSV<Sample1Row>(path: path) XCTAssertEqual(csv.count, 5) let row1 = csv[1] let row2 = csv[2] let row3 = csv[3] let row4 = csv[4] let row5 = csv[5] print("Row 1 : \(row1)") XCTAssertEqual(row1.country, "日本国") XCTAssertEqual(row1.capital, "東京") XCTAssertEqual(row1.population, 127767944) XCTAssertNil(row1.favolite) print("Row 2 : \(row2)") XCTAssertEqual(row2.country, "アメリカ合衆国") XCTAssertEqual(row2.capital, "ワシントン") XCTAssertEqual(row2.population, 300007997) XCTAssertEqual(row2.favolite, true) print("Row 3 : \(row3)") XCTAssertEqual(row3.country, "日本国") XCTAssertEqual(row3.capital, "東京") XCTAssertEqual(row3.population, 127767944) XCTAssertNil(row3.favolite) print("Row 4 : \(row4)") XCTAssertEqual(row4.country, "日本国") XCTAssertEqual(row4.capital, "東京") XCTAssertEqual(row4.population, 127767944) XCTAssertEqual(row4.favolite, false) print("Row 5 : \(row5)") XCTAssertEqual(row5.country, "日本国") XCTAssertEqual(row5.capital, "東\"京") XCTAssertEqual(row5.population, 127767944) XCTAssertNil(row5.favolite) } catch CSVParserError.ParseError(let message) { XCTFail(message) } catch CSVParserError.ConvertError(let message) { XCTFail(message) } catch { XCTFail(String(reflecting: error)) } } }
mit
45da40e66d5a0e140860457b9f130c4e
23.356322
111
0.662105
3.270062
false
true
false
false
rectinajh/leetCode_Swift
NumberOfArithmeticSlices/NumberOfArithmeticSlices/ViewController.swift
1
923
// // ViewController.swift // NumberOfArithmeticSlices // // Created by hua on 16/10/9. // Copyright © 2016年 212. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var input :[Int] = [1,2,3,4] var test = Solution.numberOfArithmeticSlices(input) let case0 :[Int] = [1,2,3,4] let case1 = [2, 4, 6, 7, 8] let case2 = [2, 7, 11, 15] let case3 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] var test0 = Solution.numberOfArithmeticSlices(case0) var test1 = Solution.numberOfArithmeticSlices(case1) var test2 = Solution.numberOfArithmeticSlices(case2) var test3 = Solution.numberOfArithmeticSlices(case3) print(test0) print(test1) print(test2) print(test3) } }
mit
fc9e6f287377ea8129b4459af559c76f
22.589744
60
0.570652
3.622047
false
true
false
false
kimberlyz/Hint-Hint
Pods/CVCalendar/CVCalendar/CVCalendarMenuView.swift
5
4391
// // CVCalendarMenuView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public typealias WeekdaySymbolType = CVWeekdaySymbolType public final class CVCalendarMenuView: UIView { public var symbols = [String]() public var symbolViews: [UILabel]? public var firstWeekday: Weekday? = .Sunday public var dayOfWeekTextColor: UIColor? = .darkGrayColor() public var dayOfWeekTextUppercase: Bool? = true public var dayOfWeekFont: UIFont? = UIFont(name: "Avenir", size: 10) public var weekdaySymbolType: WeekdaySymbolType? = .Short @IBOutlet public weak var menuViewDelegate: AnyObject? { set { if let delegate = newValue as? MenuViewDelegate { self.delegate = delegate } } get { return delegate as? AnyObject } } public var delegate: MenuViewDelegate? { didSet { setupAppearance() setupWeekdaySymbols() createDaySymbols() } } public init() { super.init(frame: CGRectZero) } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func setupAppearance() { if let delegate = delegate { firstWeekday~>delegate.firstWeekday?() dayOfWeekTextColor~>delegate.dayOfWeekTextColor?() dayOfWeekTextUppercase~>delegate.dayOfWeekTextUppercase?() dayOfWeekFont~>delegate.dayOfWeekFont?() weekdaySymbolType~>delegate.weekdaySymbolType?() } } public func setupWeekdaySymbols() { let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate()) calendar.firstWeekday = firstWeekday!.rawValue symbols = calendar.weekdaySymbols } public func createDaySymbols() { // Change symbols with their places if needed. let dateFormatter = NSDateFormatter() var weekdays: NSArray switch weekdaySymbolType! { case .Normal: weekdays = dateFormatter.weekdaySymbols as NSArray case .Short: weekdays = dateFormatter.shortWeekdaySymbols as NSArray case .VeryShort: weekdays = dateFormatter.veryShortWeekdaySymbols as NSArray } let firstWeekdayIndex = firstWeekday!.rawValue - 1 if (firstWeekdayIndex > 0) { let copy = weekdays weekdays = (weekdays.subarrayWithRange(NSMakeRange(firstWeekdayIndex, 7 - firstWeekdayIndex))) weekdays = weekdays.arrayByAddingObjectsFromArray(copy.subarrayWithRange(NSMakeRange(0, firstWeekdayIndex))) } self.symbols = weekdays as! [String] // Add symbols. self.symbolViews = [UILabel]() let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 let y: CGFloat = 0 for i in 0..<7 { x = CGFloat(i) * width + space let symbol = UILabel(frame: CGRectMake(x, y, width, height)) symbol.textAlignment = .Center symbol.text = self.symbols[i] if (dayOfWeekTextUppercase!) { symbol.text = (self.symbols[i]).uppercaseString } symbol.font = dayOfWeekFont symbol.textColor = dayOfWeekTextColor self.symbolViews?.append(symbol) self.addSubview(symbol) } } public func commitMenuViewUpdate() { if let delegate = delegate { let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 let y: CGFloat = 0 for i in 0..<self.symbolViews!.count { x = CGFloat(i) * width + space let frame = CGRectMake(x, y, width, height) let symbol = self.symbolViews![i] symbol.frame = frame } } } }
bsd-3-clause
01dc7fdef817c74f1c9059da54c60d6b
29.922535
120
0.585744
5.088065
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift
62
5348
// // Driver+Subscription.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif private let driverErrorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" + "This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n" // This would ideally be Driver, but unfortunately Driver can't be extended in Swift 3.0 extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { /** Creates new subscription and sends elements to observer. This method can be only called from `MainThread`. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return self.asSharedSequence().asObservable().subscribe(observer) } /** Creates new subscription and sends elements to observer. This method can be only called from `MainThread`. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func drive<O: ObserverType>(_ observer: O) -> Disposable where O.E == E? { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return self.asSharedSequence().asObservable().map { $0 as E? }.subscribe(observer) } /** Creates new subscription and sends elements to variable. This method can be only called from `MainThread`. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the variable. */ public func drive(_ variable: Variable<E>) -> Disposable { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return drive(onNext: { e in variable.value = e }) } /** Creates new subscription and sends elements to variable. This method can be only called from `MainThread`. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the variable. */ public func drive(_ variable: Variable<E?>) -> Disposable { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return drive(onNext: { e in variable.value = e }) } /** Subscribes to observable sequence using custom binder function. This method can be only called from `MainThread`. - parameter with: Function used to bind elements from `self`. - returns: Object representing subscription. */ public func drive<R>(_ transformation: (Observable<E>) -> R) -> R { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return transformation(self.asObservable()) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return with(self)(curriedArgument) } This method can be only called from `MainThread`. - parameter with: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ public func drive<R1, R2>(_ with: (Observable<E>) -> (R1) -> R2, curriedArgument: R1) -> R2 { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return with(self.asObservable())(curriedArgument) } /** Subscribes an element handler, a completion handler and disposed handler to an observable sequence. This method can be only called from `MainThread`. Error callback is not exposed because `Driver` can't error out. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. gracefully completed, errored, or if the generation is canceled by disposing subscription) - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ public func drive(onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { MainScheduler.ensureExecutingOnScheduler(errorMessage: driverErrorMessage) return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) } }
mit
4c6f864a6e8c15d6139c3aaa8642feb0
42.120968
134
0.708996
5.102099
false
false
false
false
RoverPlatform/rover-ios-beta
Sources/UI/LoadingViewController.swift
2
2947
// // LoadingViewController.swift // Rover // // Created by Sean Rucker on 2019-05-11. // Copyright © 2019 Rover Labs Inc. All rights reserved. // import UIKit /// The default view controller displayed by the `RoverViewController` while it is fetching an experience from the /// server. /// /// The `LoadingViewController` displays an activity inidicator in the center of the screen. After three seconds it /// also displays a cancel button. When the cancel button is tapped it dismisses the view controller. open class LoadingViewController: UIViewController { /// The activity indicator displayed in the center of the screen. #if swift(>=4.2) public var activityIndicator = UIActivityIndicatorView(style: .whiteLarge) #else public var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) #endif /// The cancel button displayed below the activity indicator after 3 seconds. public var cancelButton = UIButton(type: .custom) override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white activityIndicator.color = .gray activityIndicator.translatesAutoresizingMaskIntoConstraints = false view.addSubview(activityIndicator) cancelButton.setTitle(NSLocalizedString("Cancel", comment: "Rover Cancel"), for: .normal) cancelButton.setTitleColor(.darkText, for: .normal) cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside) cancelButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(cancelButton) if #available(iOS 11.0, *) { let layoutGuide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ activityIndicator.centerXAnchor.constraint(equalTo: layoutGuide.centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: layoutGuide.centerYAnchor) ]) } else { NSLayoutConstraint.activate([ activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } NSLayoutConstraint.activate([ cancelButton.centerXAnchor.constraint(equalTo: activityIndicator.centerXAnchor), cancelButton.topAnchor.constraint(equalTo: activityIndicator.bottomAnchor, constant: 8) ]) activityIndicator.startAnimating() // The cancel button starts off hidden and is displayed after 3 seconds cancelButton.isHidden = true Timer.scheduledTimer(withTimeInterval: TimeInterval(3), repeats: false) { [weak self] _ in self?.cancelButton.isHidden = false } } @objc private func cancel() { dismiss(animated: true, completion: nil) } }
mit
a61b687f39cf8e7c7f12ee5831a17d29
39.356164
115
0.681602
5.676301
false
false
false
false
strivingboy/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/View/CCArticleTableView/CCArticleTableViewCell.swift
1
4437
// // CCArticleTableViewCell.swift // CocoaChinaPlus // // Created by user on 15/10/28. // Copyright © 2015年 zixun. All rights reserved. // import Foundation import Neon class CCArticleTableViewCell: CCPTableViewCell { var urlString:String! //标志cell是否有图片 var hasImage:Bool = false private var picView:UIImageView! private var picMaskView:UIView! private var titleLabel:UILabel! private var postDateLabel:UILabel! private var watchLabel:UILabel! private var bottomLine:UIImageView! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.picView = UIImageView() self.picView.layer.cornerRadius = 4 self.picView.clipsToBounds = true self.containerView.addSubview(picView) self.picMaskView = UIView() self.picMaskView.hidden = true self.picMaskView.backgroundColor = UIColor.appGrayColor().colorWithAlphaComponent(0.6) self.containerView.addSubview(self.picMaskView) self.titleLabel = UILabel() self.titleLabel.font = UIFont.systemFontOfSize(14) self.titleLabel.textColor = UIColor.whiteColor() self.titleLabel.textAlignment = NSTextAlignment.Left self.titleLabel.numberOfLines = 2 self.titleLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail self.containerView.addSubview(titleLabel) self.postDateLabel = UILabel() self.postDateLabel.font = UIFont.systemFontOfSize(10) self.postDateLabel.textColor = UIColor.grayColor() self.postDateLabel.textAlignment = NSTextAlignment.Left self.containerView.addSubview(postDateLabel) self.watchLabel = UILabel() self.watchLabel.font = UIFont.systemFontOfSize(10) self.watchLabel.textColor = UIColor.grayColor() self.containerView.addSubview(watchLabel) } override func layoutSubviews() { super.layoutSubviews() if self.hasImage { //有图片的布局 self.picView.hidden = false self.picView.anchorAndFillEdge(Edge.Left, xPad: 4, yPad: 4, otherSizeTupling: 1.5) self.picMaskView.frame = self.picView.frame self.titleLabel.alignAndFillWidth(align: .ToTheRightMatchingTop, relativeTo: self.picView, padding: 4, height: AutoHeight) self.postDateLabel.anchorInCornerWithAutoSize(Corner.BottomLeft, xPad: self.picView.xMax, yPad: 2) self.watchLabel.anchorInCornerWithAutoSize(Corner.BottomRight, xPad: 4, yPad: 2) }else { let xPad : CGFloat = 10.0 let yPad : CGFloat = 4.0 self.picView.hidden = true self.titleLabel.anchorAndFillEdge(Edge.Top, xPad: xPad, yPad: yPad, otherSize: AutoHeight) self.postDateLabel.anchorInCornerWithAutoSize(Corner.BottomLeft, xPad: xPad, yPad: yPad) self.watchLabel.anchorInCornerWithAutoSize(Corner.BottomRight, xPad: xPad, yPad: yPad) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configure(model:CCArticleModel) { self.configure(model, forceHighlight: false) } func configure(model:CCArticleModel, forceHighlight:Bool) { urlString = model.linkURL if model.imageURL != nil { self.hasImage = true picView.sd_setImageWithURL(NSURL(string:model.imageURL!)!) }else { self.hasImage = false } titleLabel.text = model.title postDateLabel.text = model.postTime watchLabel.text = model.viewed if forceHighlight { self.highlightCell(true) }else { if CCArticleService.isArticleExsitById(model.identity) { self.highlightCell(false) }else { self.highlightCell(true) } } } func highlightCell(highlight:Bool) { if highlight { self.titleLabel.textColor = UIColor.whiteColor() self.picMaskView.hidden = true }else { self.titleLabel.textColor = UIColor.appGrayColor() self.picMaskView.hidden = false } } }
mit
21eaa1f46a1da5f17d66acdd368f0384
32.656489
134
0.632486
4.833333
false
false
false
false
2794129697/-----mx
CoolXuePlayer/PageViewController.swift
1
4762
// // PageViewController.swift // CoolXuePlayer // // Created by lion-mac on 15/5/29. // Copyright (c) 2015年 lion-mac. All rights reserved. // import UIKit class PageViewController: UIViewController,UIScrollViewDelegate { var pageImages: [UIImage] = [] var pageViews: [UIImageView?] = [] @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! func loadPage(page: Int) { if page < 0 || page >= pageImages.count { // 如果超出了页面显示的范围,什么也不需要做 return } // 1 if let pageView = pageViews[page] { // 页面已经加载,不需要额外操作 } else { // 2 var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 // 3 // let newPageView = UIImageView(image: pageImages[page]) // newPageView.contentMode = .ScaleAspectFit // newPageView.frame = frame let newPageView = UIImageView() newPageView.sd_setImageWithURL(NSURL(string: "http://media.icoolxue.com/M87ExoMcDKdQ3K9DxVYLJo.jpg")) newPageView.contentMode = .ScaleAspectFit newPageView.frame = frame scrollView.addSubview(newPageView) // 4 pageViews[page] = newPageView } } func purgePage(page: Int) { if page < 0 || page >= pageImages.count { // 如果超出要显示的范围,什么也不做 return } // 从scrollView中移除页面并重置pageViews容器数组响应页面 if let pageView = pageViews[page] { pageView.removeFromSuperview() pageViews[page] = nil } } func scrollViewDidScroll(scrollView: UIScrollView) { // Load the pages that are now on screen loadVisiblePages() } override func viewDidLoad() { super.viewDidLoad() // 1 pageImages.append(UIImage(named: "defaut_logo_zongyi.png")!) pageImages.append(UIImage(named: "default_hoder114x152.jpg")!) pageImages.append(UIImage(named: "defaut_logo_zongyi.png")!) pageImages.append(UIImage(named: "default_hoder_170x100.jpg")!) pageImages.append(UIImage(named: "default_hoder_295x165.jpg")!) // pageImages = [ // UIImage(named: "photo1.png"), // UIImage(named: "photo2.png"), // UIImage(named: "photo3.png"), // UIImage(named: "photo4.png"), // UIImage(named: "photo5.png") // ] let pageCount = pageImages.count // 2 pageControl.currentPage = 0 pageControl.numberOfPages = pageCount // 3 for _ in 0..<pageCount { pageViews.append(nil) } // 4 let pagesScrollViewSize = scrollView.frame.size scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count), height: pagesScrollViewSize.height) // 5 loadVisiblePages() // Do any additional setup after loading the view. } func loadVisiblePages() { // 首先确定当前可见的页面 let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // 更新pageControl pageControl.currentPage = page // 计算那些页面需要加载 let firstPage = page - 1 let lastPage = page + 1 // 清理firstPage之前的所有页面 for var index = 0; index < firstPage; ++index { purgePage(index) } // 加载范围内(firstPage到lastPage之间)的所有页面 for index in firstPage...lastPage { loadPage(index) } // 清理lastPage之后的所有页面 for var index = lastPage+1; index < pageImages.count; ++index { purgePage(index) } } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
lgpl-3.0
b7638f4d4395bc93c97c9efd866e7434
29.917808
113
0.569561
4.587398
false
false
false
false
mlilback/rc2SwiftClient
ClientCore/PreferenceKeys.swift
1
2267
// // PreferenceKeys.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Rc2Common import Foundation import SwiftyUserDefaults import Networking extension ServerHost: DefaultsSerializable {} public extension DefaultsKeys { static let currentCloudHost = DefaultsKey<ServerHost?>("currentCloudHost") static let maxCommandHistory = DefaultsKey<Int>("MaxCommandHistorySize", defaultValue: 10) //import static let lastImportDirectory = DefaultsKey<Data?>("rc2.LastImportDirectory") static let replaceFiles = DefaultsKey<Bool>("rc2.ImportReplacesExistingFiles", defaultValue: false) static let autosaveEnabled = DefaultsKey<Bool>("AutoSaveEnabled", defaultValue: false) static let wordWrapEnabled = DefaultsKey<Bool>("WordWrapEnabled", defaultValue: false) static let openGeneratedFiles = DefaultsKey<Bool>("OpenGeneratedFiles", defaultValue: false) static let lastExportDirectory = DefaultsKey<Data?>("rc2.LastExportDirectory") static let helpTopicSearchSummaries = DefaultsKey<Bool>("rc2.helpSidebar.searchSummaries", defaultValue: false) static let editorFont = DefaultsKey<FontDescriptor?>("rc2.editor.font") static let defaultFontSize = DefaultsKey<Double>("rc2.defaultFontSize", defaultValue: 14.0) static let consoleOutputFont = DefaultsKey<FontDescriptor?>("rc2.console.font") static let clearImagesWithConsole = DefaultsKey<Bool>("clearImagesWithConsole", defaultValue: false) static let previewUpdateDelay = DefaultsKey<Double>("PreviewUpdateDelay", defaultValue: 0.5) static let suppressDeleteTemplate = DefaultsKey<Bool>("suppressDeleteTemplate", defaultValue: false) static let suppressDeleteFileWarnings = DefaultsKey<Bool>("SuppressDeleteFileWarning", defaultValue: false) static let suppressClearWorkspace = DefaultsKey<Bool>("SuppressClearWorkspaceWarning", defaultValue: false) static let suppressClearImagesWithConsole = DefaultsKey<Bool>("SuppressClearImagesWithConsole", defaultValue: false) static let suppressDeleteChunkWarnings = DefaultsKey<Bool>("SuppressDeleteChunkWarning", defaultValue: false) static let suppressKeys = [suppressDeleteFileWarnings, suppressClearWorkspace, suppressClearImagesWithConsole, suppressDeleteTemplate, .suppressDeleteChunkWarnings] }
isc
ddb5c0a6aefff728a2a5f2aca457979b
51.697674
165
0.818182
4.605691
false
false
false
false
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter10-Driving-SwiftUI-with-Combine/06-Unit-Testing-an-app-based-on-Combine/GithubUsers/GithubUsers/ContentView.swift
1
1726
// // ContentView.swift // GithubUsers // // Created by Giordano Scalzo on 06/08/2021. // import SwiftUI import Combine struct GithubUser: Decodable, Identifiable { let id: Int let login: String let avatarUrl: String } class Github: ObservableObject { @Published var users: [GithubUser] = [] private var cancellableSet: Set<AnyCancellable> = [] func load() { let url = URL(string: "https://api.github.com/users")! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase URLSession.shared .dataTaskPublisher(for: URLRequest(url: url)) .map(\.data) .decode(type: [GithubUser].self, decoder: decoder) .replaceError(with: []) .receive(on: RunLoop.main) .assign(to: \.users, on: self) .store(in: &cancellableSet) } } struct ContentView: View { @StateObject var github = Github() var body: some View { List(github.users) { GithubUserView(user: $0) } .task { github.load() } } } struct GithubUserView: View { let user: GithubUser var body: some View { HStack { AsyncImage(url: URL(string: user.avatarUrl)) { image in image .resizable() .scaledToFill() } placeholder: { Color.purple.opacity(0.1) } .frame(width: 40, height: 40) .cornerRadius(20) Spacer() Text(user.login) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
e0ac8097e631ae35e46b126f061a3c60
22.324324
67
0.54635
4.347607
false
false
false
false
IndisputableLabs/Swifthereum
Swifthereum/Classes/Web3/Network/URLRequest.swift
1
1917
// // URLRequest.swift // Crisp // // Created by Ronald Mannak on 1/12/17. // Copyright © 2017 A Puzzle A Day. All rights reserved. // import Foundation extension URLRequest { public init?<A>(resource: Resource<A>) { /* Merge server and resource parameters. Add parameters to either body or URL, depending on encoding requested by resource */ var endPoint = resource.server.domain let parameters: JSONDictionary = { // Merges the server's default parameters with the method parameter and the resource specific parameters let methodParameter: JSONDictionary = ["method" : resource.method] var serverParameters: JSONDictionary = resource.server.defaultParameters serverParameters = serverParameters.merge(with: methodParameter) if let parameters = resource.parameters { let messageParameters: JSONDictionary = ["params" : parameters] serverParameters = serverParameters.merge(with: messageParameters) } return serverParameters }() var body: Data? = nil switch resource.encoding { case .json: body = parameters.jsonEncodedData case .url: if let parameters = parameters.urlEncodedString { print("parameters: \(parameters)") endPoint += "?\(parameters)" } case .body: body = parameters.bodyEncodedData } guard let url = URL(string: endPoint) else { return nil } self.init(url: url) httpBody = body httpMethod = resource.httpMethod.rawValue // Set headers addValue(resource.encoding.contentType(), forHTTPHeaderField: "Content-Type") addValue(resource.encoding.contentType(), forHTTPHeaderField: "Accept") } }
mit
bc1e08aa59b83f666270faaa73472f43
33.836364
116
0.610125
5.249315
false
false
false
false
waltflanagan/AdventOfCode
2017/AdventOfCode.playground/Pages/2018 Day 9.xcplaygroundpage/Contents.swift
1
479
//: [Previous](@previous) import Foundation // 1 1 3 1 3 5 7 // (1 + 2) % 3 = 1 // (1 + 2) % 4 = 3 // (3 + 2) % 5 = 1 // ( var example1 = Game(players: 9, maxMarble: 50) example1.play() // for pair in [(13,7999), (17,1104), (21,6111), (30,5807), (464,7091800)] { var example2 = Game(players: pair.0, maxMarble: pair.1) print("\(example2.play())") } //var realGame = Game(players: 464, maxMarble: 7091800) //print("\(realGame.play())") //: [Next](@next)
mit
abc57acbb3df9cc95b638951d9c85c97
12.685714
73
0.551148
2.575269
false
false
false
false
anatoliyv/RevealMenuController
Example/RevealMenuController/ViewController.swift
1
2231
// // ViewController.swift // RevealMenuController // // Created by Anatoliy Voropay on 08/31/2016. // Copyright (c) 2016 Anatoliy Voropay. All rights reserved. // import UIKit import RevealMenuController class ViewController: UIViewController { @IBAction func presentActionScheet(_ sender: AnyObject) { let position: RevealMenuController.Position = sender.tag == 0 ? .top : sender.tag == 1 ? .center : .bottom let revealController = RevealMenuController(title: "Contact Support", position: position) let webImage = UIImage(named: "IconHome") let emailImage = UIImage(named: "IconEmail") let phoneImage = UIImage(named: "IconCall") let webAction = RevealMenuAction(title: "Open web page", image: webImage, handler: { (controller, action) in print(action.title!) controller.dismiss(animated: true, completion: nil) }) revealController.addAction(webAction) // Add first group let techGroup = RevealMenuActionGroup(title: "Contact tech. support", actions: [ RevealMenuAction(title: "[email protected]", image: emailImage, handler: { (controller, action) in print(action.title!) }), RevealMenuAction(title: "1-866-752-7753", image: phoneImage, handler: { (controller, action) in print(action.title!) }) ]) revealController.addAction(techGroup) // Add second group let customersGroup = RevealMenuActionGroup(title: "Contact custommers support", actions: [ RevealMenuAction(title: "[email protected]", image: emailImage, handler: { (controller, action) in print(action.title!) }), RevealMenuAction(title: "1-800-676-2775", image: phoneImage, handler: { (controller, action) in print(action.title!) }) ]) revealController.addAction(customersGroup) // Display controller revealController.displayOnController(self) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
0b38801e7fafa979f45d30eed89b642e
37.465517
116
0.62035
4.638254
false
false
false
false
sunfei/RxSwift
RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift
4
1600
// // UIImageView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/1/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UIImageView { public func rx_subscribeImageTo(source: Observable<UIImage?>) -> Disposable { return rx_subscribeImageTo(false)(source) } public func rx_subscribeImageTo (animated: Bool) -> Observable<UIImage?> -> Disposable { return { source in return source.subscribe(AnonymousObserver { event in MainScheduler.ensureExecutingOnScheduler() switch event { case .Next(let boxedValue): let value = boxedValue.value if animated && value != nil { let transition = CATransition() transition.duration = 0.25 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionFade self.layer.addAnimation(transition, forKey: kCATransition) } else { self.layer.removeAllAnimations() } self.image = value case .Error(let error): bindingErrorToInterface(error) break case .Completed: break } }) } } }
mit
272b08796fa805aae2a867827e356ed0
31.02
116
0.521875
5.947955
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/PBMClickthroughBrowserViewTest.swift
1
4720
/*   Copyright 2018-2021 Prebid.org, 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.  */ import XCTest class PBMClickthroughBrowserViewTest: XCTestCase, ClickthroughBrowserViewDelegate { // MARK: - Properties var clickThroughBrowserView : ClickthroughBrowserView! let testURL = URL(string: "openx.com")! var expectationBrowserClosePressed: XCTestExpectation? var expectationBrowserDidLeaveApp: XCTestExpectation? var expectationLoad1: XCTestExpectation? var expectationLoad2: XCTestExpectation? // MARK: - Setup override func setUp() { super.setUp() self.clickThroughBrowserView = PBMFunctions.bundleForSDK().loadNibNamed("ClickthroughBrowserView", owner: nil, options: nil)!.first as? ClickthroughBrowserView } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() self.clickThroughBrowserView = nil } // MARK: - Test Buttons func testExternalBrowserButtonPressed() { self.clickThroughBrowserView.clickThroughBrowserViewDelegate = self expectationBrowserDidLeaveApp = expectation(description:"expectationBrowserDidLeaveApp") self.clickThroughBrowserView.openURL(testURL) self.clickThroughBrowserView.externalBrowserButtonPressed() waitForExpectations(timeout: 1) } func testExternalBrowserButtonPressedWithoutURL() { self.clickThroughBrowserView.clickThroughBrowserViewDelegate = self expectationBrowserDidLeaveApp = expectation(description:"expectationBrowserDidLeaveApp") expectationBrowserDidLeaveApp?.isInverted = true self.clickThroughBrowserView.externalBrowserButtonPressed() waitForExpectations(timeout: 1) } func testCloseButtonPressed() { self.clickThroughBrowserView.clickThroughBrowserViewDelegate = self expectationBrowserClosePressed = expectation(description:"expectationBrowserClosePressed"); self.clickThroughBrowserView.closeButtonPressed() waitForExpectations(timeout: 1) } func testDecidePolicyForNavigationActionWithNoURL() { self.clickThroughBrowserView.navigationHandler.webView(self.clickThroughBrowserView.webView!, decidePolicyFor: WKNavigationAction(), decisionHandler: { policy in XCTAssertEqual(policy, .cancel) }) } func testDecidePolicyForNavigationAction() { let navigationAction = MockWKNavigationAction() navigationAction.mockedRequest = URLRequest(url: testURL) self.clickThroughBrowserView.navigationHandler.webView(self.clickThroughBrowserView.webView!, decidePolicyFor: navigationAction, decisionHandler: { policy in XCTAssertEqual(policy, .allow) }) } func testDecidePolicyForNavigationActionWithDifferentSchema() { self.clickThroughBrowserView.clickThroughBrowserViewDelegate = self for strScheme in PBMConstants.urlSchemesForAppStoreAndITunes { expectationBrowserDidLeaveApp = expectation(description:"expectationBrowserDidLeaveApp") expectationBrowserClosePressed = expectation(description:"expectationBrowserClosePressed"); let navigationAction = MockWKNavigationAction() navigationAction.mockedRequest = URLRequest(url: URL(string: "\(strScheme)://test")!) self.clickThroughBrowserView.navigationHandler.webView(self.clickThroughBrowserView.webView!, decidePolicyFor: navigationAction, decisionHandler: { policy in XCTAssertEqual(policy, .cancel) }) waitForExpectations(timeout: 3) } } // MARK: - PBMClickthroughBrowserViewDelegate func clickThroughBrowserViewCloseButtonTapped() { expectationBrowserClosePressed?.fulfill() } func clickThroughBrowserViewWillLeaveApp() { expectationBrowserDidLeaveApp?.fulfill() } }
apache-2.0
3c721f370cbf13fbf48c8a1976087c60
36.672
169
0.704183
5.572781
false
true
false
false
jkolb/Shkadov
Shkadov/utility/Time.swift
1
4596
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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. */ public protocol TimeSource : class { var currentTime: Time { get } } public typealias TimeType = UInt64 private let millisecondsPerSecond: TimeType = 1_000 private let nanosecondsPerSecond: TimeType = 1_000_000_000 private let millisecondsPerNanosecond = nanosecondsPerSecond / millisecondsPerSecond public struct Time : Comparable, Equatable, Hashable { public static let zero = Time(nanoseconds: 0) public let nanoseconds: TimeType public init(seconds: Double) { precondition(seconds >= 0.0) self.nanoseconds = TimeType(seconds * Double(nanosecondsPerSecond)) } public init(milliseconds: TimeType) { self.nanoseconds = milliseconds * millisecondsPerNanosecond } public init(nanoseconds: TimeType) { self.nanoseconds = nanoseconds } public var milliseconds: TimeType { return nanoseconds / millisecondsPerNanosecond } public var seconds: Double { return Double(nanoseconds) / Double(nanosecondsPerSecond) } public var hashValue: Int { return nanoseconds.hashValue } public static func ==(a: Time, b: Time) -> Bool { return a.nanoseconds == b.nanoseconds } public static func <(a: Time, b: Time) -> Bool { return a.nanoseconds < b.nanoseconds } } public func -(a: Time, b: Time) -> Duration { if a < b { return Duration(nanoseconds: b.nanoseconds - a.nanoseconds) } else { return Duration(nanoseconds: a.nanoseconds - b.nanoseconds) } } public func +(a: Time, b: Duration) -> Time { return Time(nanoseconds: a.nanoseconds + b.nanoseconds) } public struct Duration: Comparable, Equatable { public static let zero = Duration(nanoseconds: 0) public var nanoseconds: TimeType public init(seconds: Double) { precondition(seconds >= 0.0) self.nanoseconds = TimeType(seconds * Double(nanosecondsPerSecond)) } public init(milliseconds: TimeType) { self.nanoseconds = milliseconds * millisecondsPerNanosecond } public init(nanoseconds: TimeType) { self.nanoseconds = nanoseconds } public var milliseconds: TimeType { return nanoseconds / millisecondsPerNanosecond } public var seconds: Double { return Double(nanoseconds) / Double(nanosecondsPerSecond) } public static func ==(a: Duration, b: Duration) -> Bool { return a.nanoseconds == b.nanoseconds } public static func <(a: Duration, b: Duration) -> Bool { return a.nanoseconds < b.nanoseconds } } public func +(a: Duration, b: Duration) -> Duration { return Duration(nanoseconds: a.nanoseconds + b.nanoseconds) } public func -(a: Duration, b: Duration) -> Duration { return Duration(nanoseconds: a.nanoseconds - b.nanoseconds) } public func *(a: Duration, b: TimeType) -> Duration { return Duration(nanoseconds: a.nanoseconds * b) } public func /(a: Duration, b: TimeType) -> Duration { return Duration(nanoseconds: a.nanoseconds / b) } public func +=(a: inout Duration, b: Duration) { a.nanoseconds = a.nanoseconds + b.nanoseconds } public func -=(a: inout Duration, b: Duration) { a.nanoseconds = a.nanoseconds - b.nanoseconds } public func *=(a: inout Duration, b: TimeType) { a.nanoseconds = a.nanoseconds * b } public func /=(a: inout Duration, b: TimeType) { a.nanoseconds = a.nanoseconds / b }
mit
a89b276c9cef3091854636ebbb0c6c2d
29.236842
84
0.688425
4.402299
false
false
false
false
Allow2CEO/browser-ios
Client/Extensions/UIImageViewExtensions.swift
1
3712
/* 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 Storage import WebImage public extension UIImageView { public func setIcon(_ icon: Favicon?, withPlaceholder placeholder: UIImage, completion: (()->())? = nil) { if let icon = icon { guard let imageURL = URL(string: icon.url) else { completion?(); return } //self.image = placeholder ImageCache.shared.image(imageURL, type: .square, callback: { (image) in if image == nil { self.sd_setImage(with: imageURL, completed: { (img, err, type, url) in self.image = img if let img = img { ImageCache.shared.cache(img, url: imageURL, type: .square, callback: nil) } completion?() }) } else { self.image = image completion?() } }) } else { self.image = placeholder completion?() } } } open class ImageOperation : NSObject, SDWebImageOperation { open var cacheOperation: Operation? var cancelled: Bool { if let cacheOperation = cacheOperation { return cacheOperation.isCancelled } return false } @objc open func cancel() { if let cacheOperation = cacheOperation { cacheOperation.cancel() } } } // This is an extension to SDWebImage's api to allow passing in a cache to be used for lookup. public typealias CompletionBlock = (_ img: UIImage?, _ err: NSError, _ type: SDImageCacheType, _ key: String) -> Void extension UIImageView { // This is a helper function for custom async loaders. It starts an operation that will check for the image in // a cache (either one passed in or the default if none is specified). If its found in the cache its returned, // otherwise, block is run and should return an image to show. fileprivate func runBlockIfNotInCache(_ key: String, cache: SDImageCache, completed: @escaping CompletionBlock, block: @escaping () -> UIImage?) { self.sd_cancelCurrentImageLoad() let operation = ImageOperation() operation.cacheOperation = cache.queryDiskCache(forKey: key, done: { (image, cacheType) -> Void in let err = NSError(domain: "UIImage+Extensions.runBlockIfNotInCache", code: 0, userInfo: nil) // If this was cancelled, don't bother notifying the caller if operation.cancelled { return } // If it was found in the cache, we can just use it if let image = image { self.image = image self.setNeedsLayout() } else { // Otherwise, the block has a chance to load it let image = block() if image != nil { self.image = image cache.store(image, forKey: key) } } completed(image, err, cacheType, key) }) self.sd_setImageLoadOperation(operation, forKey: "UIImageViewImageLoad") } public func moz_getImageFromCache(_ key: String, cache: SDImageCache, completed: @escaping CompletionBlock) { // This cache is filled outside of here. If we don't find the key in it, nothing to do here. runBlockIfNotInCache(key, cache: cache, completed: completed) { _ in return nil} } }
mpl-2.0
e5f5c0a7ded1d9ff5e72b3381ab87422
38.073684
150
0.577586
4.839635
false
false
false
false
jlandon/Alexandria
Sources/Alexandria/NSAttributedString+Extensions.swift
1
17314
// // NSAttributedString+Extensions.swift // // Created by Ben Kreeger on 12/11/15. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // 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 extension NSAttributedString { /** Returns a new mutable string with characters from a given character set removed. See http://panupan.com/2012/06/04/trim-leading-and-trailing-whitespaces-from-nsmutableattributedstring/ - Parameters: - charSet: The character set with which to remove characters. - returns: A new string with the matching characters removed. */ public func trimmingCharacters(in set: CharacterSet) -> NSAttributedString { let modString = NSMutableAttributedString(attributedString: self) modString.trimCharacters(in: set) return NSAttributedString(attributedString: modString) } } extension NSMutableAttributedString { /** Modifies this instance of the string to remove characters from a given character set from the beginning and end of the string. See http://panupan.com/2012/06/04/trim-leading-and-trailing-whitespaces-from-nsmutableattributedstring/ - Parameters: - charSet: The character set with which to remove characters. */ public func trimCharacters(in set: CharacterSet) { var range = (string as NSString).rangeOfCharacter(from: set) // Trim leading characters from character set. while range.length != 0 && range.location == 0 { replaceCharacters(in: range, with: "") range = (string as NSString).rangeOfCharacter(from: set) } // Trim trailing characters from character set. range = (string as NSString).rangeOfCharacter(from: set, options: .backwards) while range.length != 0 && NSMaxRange(range) == length { replaceCharacters(in: range, with: "") range = (string as NSString).rangeOfCharacter(from: set, options: .backwards) } } } extension NSMutableAttributedString { private var range: NSRange { return NSRange(location: 0, length: length) } private var paragraphStyle: NSMutableParagraphStyle { let style = attributes(at: 0, effectiveRange: nil)[.paragraphStyle] as? NSMutableParagraphStyle return style ?? NSMutableParagraphStyle() } } // MARK: - Font extension NSMutableAttributedString { /** Applies a font to the entire string. - parameter font: The font. */ @discardableResult public func font(_ font: UIFont) -> Self { if length > 0 { addAttribute(.font, value: font, range: range) } return self } /** Applies a font to the entire string. - parameter name: The font name. - parameter size: The font size. Note: If the specified font name cannot be loaded, this method will fallback to the system font at the specified size. */ @discardableResult public func font(name: String, size: CGFloat) -> Self { if length > 0 { addAttribute(.font, value: UIFont(name: name, size: size) ?? .systemFont(ofSize: size), range: range) } return self } } // MARK: - Paragraph style extension NSMutableAttributedString { /** Applies a text alignment to the entire string. - parameter alignment: The text alignment. */ @discardableResult public func alignment(_ alignment: NSTextAlignment) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.alignment = alignment addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies line spacing to the entire string. - parameter lineSpacing: The line spacing amount. */ @discardableResult public func lineSpacing(_ lineSpacing: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.lineSpacing = lineSpacing addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies paragraph spacing to the entire string. - parameter paragraphSpacing: The paragraph spacing amount. */ @discardableResult public func paragraphSpacing(_ paragraphSpacing: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.paragraphSpacing = paragraphSpacing addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a line break mode to the entire string. - parameter mode: The line break mode. */ @discardableResult public func lineBreak(_ mode: NSLineBreakMode) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.lineBreakMode = mode addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a line height multiplier to the entire string. - parameter multiple: The line height multiplier. */ @discardableResult public func lineHeight(multiple: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.lineHeightMultiple = multiple addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a first line head indent to the string. - parameter indent: The first line head indent amount. */ @discardableResult public func firstLineHeadIndent(_ indent: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.firstLineHeadIndent = indent addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a head indent to the string. - parameter indent: The head indent amount. */ @discardableResult public func headIndent(_ indent: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.headIndent = indent addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a tail indent to the string. - parameter indent: The tail indent amount. */ @discardableResult public func tailIndent(_ indent: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.tailIndent = indent addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a minimum line height to the entire string. - parameter height: The minimum line height. */ @discardableResult public func minimumLineHeight(_ height: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.minimumLineHeight = height addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a maximum line height to the entire string. - parameter height: The maximum line height. */ @discardableResult public func maximumLineHeight(_ height: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.maximumLineHeight = height addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a base writing direction to the entire string. - parameter direction: The base writing direction. */ @discardableResult public func baseWritingDirection(_ direction: NSWritingDirection) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.baseWritingDirection = direction addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } /** Applies a paragraph spacing before amount to the string. - parameter spacing: The distance between the paragraph’s top and the beginning of its text content. */ @discardableResult public func paragraphSpacingBefore(_ spacing: CGFloat) -> Self { if length > 0 { let paragraphStyle = self.paragraphStyle paragraphStyle.paragraphSpacingBefore = spacing addAttribute(.paragraphStyle, value: paragraphStyle, range: range) } return self } } // MARK: - Foreground color extension NSMutableAttributedString { /** Applies the given color over the entire string, as the foreground color. - parameter color: The color to apply. */ @discardableResult @nonobjc public func color(_ color: UIColor, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.foregroundColor, value: color.alpha(alpha), range: range) } return self } /** Applies the given color over the entire string, as the foreground color. - parameter color: The color to apply. */ @discardableResult public func color(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.foregroundColor, value: UIColor(red: red, green: green, blue: blue, alpha: alpha), range: range) } return self } /** Applies the given color over the entire string, as the foreground color. - parameter color: The color to apply. */ @discardableResult public func color(white: CGFloat, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.foregroundColor, value: UIColor(white: white, alpha: alpha), range: range) } return self } /** Applies the given color over the entire string, as the foreground color. - parameter color: The color to apply. */ @discardableResult @nonobjc public func color(_ hex: UInt32, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.foregroundColor, value: UIColor(hex: hex, alpha: alpha), range: range) } return self } } // MARK: - Underline, kern, strikethrough, stroke, shadow, text effect extension NSMutableAttributedString { /** Applies a single underline under the entire string. - parameter style: The `NSUnderlineStyle` to apply. Defaults to `.styleSingle`. */ @discardableResult public func underline(style: NSUnderlineStyle = .single, color: UIColor? = nil) -> Self { if length > 0 { addAttribute(.underlineStyle, value: style.rawValue, range: range) if let color = color { addAttribute(.underlineColor, value: color, range: range) } } return self } /** Applies a kern (spacing) value to the entire string. - parameter value: The space between each character in the string. */ @discardableResult public func kern(_ value: CGFloat) -> Self { if length > 0 { addAttribute(.kern, value: value, range: range) } return self } /** Applies a strikethrough to the entire string. - parameter style: The `NSUnderlineStyle` to apply. Defaults to `.styleSingle`. - parameter color: The underline color. Defaults to the color of the text. */ @discardableResult public func strikethrough(style: NSUnderlineStyle = .single, color: UIColor? = nil) -> Self { if length > 0 { addAttribute(.strikethroughStyle, value: style.rawValue, range: range) if let color = color { addAttribute(.strikethroughColor, value: color, range: range) } } return self } /** Applies a stroke to the entire string. - parameter color: The stroke color. - parameter width: The stroke width. */ @discardableResult public func stroke(color: UIColor, width: CGFloat) -> Self { if length > 0 { addAttributes([ .strokeColor : color, .strokeWidth : width ], range: range) } return self } /** Applies a shadow to the entire string. - parameter color: The shadow color. - parameter radius: The shadow blur radius. - parameter offset: The shadow offset. */ @discardableResult public func shadow(color: UIColor, radius: CGFloat, offset: CGSize) -> Self { if length > 0 { let shadow = NSShadow() shadow.shadowColor = color shadow.shadowBlurRadius = radius shadow.shadowOffset = offset addAttribute(.shadow, value: shadow, range: range) } return self } } // MARK: - Background color extension NSMutableAttributedString { /** Applies a background color to the entire string. - parameter color: The color to apply. */ @discardableResult @nonobjc public func backgroundColor(_ color: UIColor, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.backgroundColor, value: color.alpha(alpha), range: range) } return self } /** Applies a background color to the entire string. - parameter red: The red color component. - parameter green: The green color component. - parameter blue: The blue color component. - parameter alpha: The alpha component. */ @discardableResult public func backgroundColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.backgroundColor, value: UIColor(red: red, green: green, blue: blue, alpha: alpha), range: range) } return self } /** Applies a background color to the entire string. - parameter white: The white color component. - parameter alpha: The alpha component. */ @discardableResult public func backgroundColor(white: CGFloat, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.backgroundColor, value: UIColor(white: white, alpha: alpha), range: range) } return self } /** Applies a background color to the entire string. - parameter hex: The hex color value. - parameter alpha: The alpha component. */ @discardableResult @nonobjc public func backgroundColor(_ hex: UInt32, alpha: CGFloat = 1) -> Self { if length > 0 { addAttribute(.backgroundColor, value: UIColor(hex: hex, alpha: alpha), range: range) } return self } } extension NSMutableAttributedString { /** Applies a baseline offset to the entire string. - parameter offset: The offset value. */ @discardableResult public func baselineOffset(_ offset: Float) -> Self { if length > 0 { addAttribute(.baselineOffset, value: NSNumber(value: offset), range: range) } return self } } public func +(lhs: NSMutableAttributedString, rhs: NSAttributedString) -> NSMutableAttributedString { let lhs = NSMutableAttributedString(attributedString: lhs) lhs.append(rhs) return lhs } public func +=(lhs: NSMutableAttributedString, rhs: NSAttributedString) { lhs.append(rhs) }
mit
c17a12f398b6ff36668fa7e05f9f73cc
29.425308
123
0.615354
5.214458
false
false
false
false
coryoso/HanekeSwift
Haneke/UIImage+Haneke.swift
1
3257
// // UIImage+Haneke.swift // Haneke // // Created by Hermes Pique on 8/10/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit extension Image { func hnk_imageByScalingToSize(toSize: CGSize) -> Image { UIGraphicsBeginImageContextWithOptions(toSize, !hnk_hasAlpha(), 0.0) drawInRect(CGRectMake(0, 0, toSize.width, toSize.height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } func hnk_hasAlpha() -> Bool { let alpha = CGImageGetAlphaInfo(self.CGImage) switch alpha { case .First, .Last, .PremultipliedFirst, .PremultipliedLast, .Only: return true case .None, .NoneSkipFirst, .NoneSkipLast: return false } } func hnk_data(compressionQuality compressionQuality: Float = 1.0) -> NSData! { let hasAlpha = self.hnk_hasAlpha() let data = hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, CGFloat(compressionQuality)) return data } func hnk_decompressedImage() -> UIImage! { let originalImageRef = self.CGImage let originalBitmapInfo = CGImageGetBitmapInfo(originalImageRef) let alphaInfo = CGImageGetAlphaInfo(originalImageRef) // See: http://stackoverflow.com/questions/23723564/which-cgimagealphainfo-should-we-use var bitmapInfo = originalBitmapInfo switch (alphaInfo) { case .None: let rawBitmapInfoWithoutAlpha = bitmapInfo.rawValue & ~CGBitmapInfo.AlphaInfoMask.rawValue let rawBitmapInfo = rawBitmapInfoWithoutAlpha | CGImageAlphaInfo.NoneSkipFirst.rawValue bitmapInfo = CGBitmapInfo(rawValue: rawBitmapInfo) case .PremultipliedFirst, .PremultipliedLast, .NoneSkipFirst, .NoneSkipLast: break case .Only, .Last, .First: // Unsupported return self } let colorSpace = CGColorSpaceCreateDeviceRGB() let pixelSize = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale) guard let context = CGBitmapContextCreate(nil, Int(ceil(pixelSize.width)), Int(ceil(pixelSize.height)), CGImageGetBitsPerComponent(originalImageRef), 0, colorSpace, bitmapInfo.rawValue) else { return self } let imageRect = CGRectMake(0, 0, pixelSize.width, pixelSize.height) UIGraphicsPushContext(context) // Flip coordinate system. See: http://stackoverflow.com/questions/506622/cgcontextdrawimage-draws-image-upside-down-when-passed-uiimage-cgimage CGContextTranslateCTM(context, 0, pixelSize.height) CGContextScaleCTM(context, 1.0, -1.0) // UIImage and drawInRect takes into account image orientation, unlike CGContextDrawImage. self.drawInRect(imageRect) UIGraphicsPopContext() guard let decompressedImageRef = CGBitmapContextCreateImage(context) else { return self } let scale = UIScreen.mainScreen().scale let image = UIImage(CGImage: decompressedImageRef, scale:scale, orientation:UIImageOrientation.Up) return image } }
apache-2.0
3e93feebf3d2b3a38544fd4dc0a99b29
39.209877
200
0.672091
5.003072
false
false
false
false
MadAppGang/SmartLog
iOS/SmartLog/Entities/Session.swift
1
1091
// // Session.swift // SmartLog // // Created by Dmytro Lisitsyn on 6/16/16. // Copyright © 2016 MadAppGang. All rights reserved. // import Foundation func == (lhs: Session, rhs: Session) -> Bool { return lhs.hashValue == rhs.hashValue } struct Session: Equatable, Hashable { let id: Int let dateStarted: Date var activityType: ActivityType = .any var sent = false var duration: TimeInterval? var samplesCount: (accelerometerData: Int?, hrData: Int?) var markersCount: Int? var notes: String? var hashValue: Int { return id.hashValue } init(id: Int, dateStarted: Date) { self.id = id self.dateStarted = dateStarted } } extension Session { var durationValue: TimeInterval { return duration ?? 0 } var samplesCountValue: (accelerometerData: Int, hrData: Int) { return (accelerometerData: samplesCount.accelerometerData ?? 0, hrData: samplesCount.hrData ?? 0) } var markersCountValue: Int { return markersCount ?? 0 } }
mit
6eb14e5bfe98c55fe12a88d4e8bb956d
19.961538
105
0.622936
3.978102
false
true
false
false
squaremeals/squaremeals-ios-app
SquareMeals/View/MealPlanDayViewController.swift
1
2223
// // MealPlanDayViewController.swift // SquareMeals // // Created by Gregory Johnson on 10/18/17. // Copyright © 2017 Shakd, LLC. All rights reserved. // import UIKit public protocol MealPlanDayViewControllerDelegate: class { func mealPlanDayViewControllerDidLoad(controller: MealPlanDayViewController) func mealPlanDayViewControllerShouldLoadMore(controller: MealPlanDayViewController) func mealPlanDayViewControllerMealSelected(_ meal: Meal, controller: MealPlanDayViewController) } public final class MealPlanDayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { public weak var delegate: MealPlanDayViewControllerDelegate? @IBOutlet fileprivate weak var tableView: UITableView! public var meals: [Meal] = [] { didSet { tableView.reloadData() } } override public func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Meal Plan" navigationController?.setNavigationBarHidden(true, animated: false) tableView.dataSource = self tableView.delegate = self tableView.registerCell(type: MealTableViewCell.self) delegate?.mealPlanDayViewControllerDidLoad(controller: self) } public func startLoading() { } public func stopLoading() { } //MARK:- UITableViewDataSource public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: MealTableViewCell = tableView.dequeueCell(for: indexPath) let meal = meals[indexPath.row] cell.configure(for: meal) if indexPath.row == meals.count - 1 { delegate?.mealPlanDayViewControllerShouldLoadMore(controller: self) } return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let meal = meals[indexPath.row] delegate?.mealPlanDayViewControllerMealSelected(meal, controller: self) } }
mit
f0d7389b357cc78fff110f1c36126963
29.861111
108
0.682268
5.380145
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Comments/WPStyleGuide+Comments.swift
2
1172
import Foundation import WordPressShared /// This class groups all of the styles used by all of the CommentsViewController. /// extension WPStyleGuide { public struct Comments { static let gravatarPlaceholderImage = UIImage(named: "gravatar") ?? UIImage() static let backgroundColor = UIColor.listForeground static let pendingIndicatorColor = UIColor.muriel(color: MurielColor(name: .yellow, shade: .shade20)) static let detailFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular) static let detailTextColor = UIColor.textSubtle private static let titleTextColor = UIColor.text private static let titleTextStyle = UIFont.TextStyle.headline static let titleBoldAttributes: [NSAttributedString.Key: Any] = [ .font: WPStyleGuide.fontForTextStyle(titleTextStyle, fontWeight: .semibold), .foregroundColor: titleTextColor ] static let titleRegularAttributes: [NSAttributedString.Key: Any] = [ .font: WPStyleGuide.fontForTextStyle(titleTextStyle, fontWeight: .regular), .foregroundColor: titleTextColor ] } }
gpl-2.0
de04432f3897769135f2bb0c9d232642
38.066667
109
0.709044
5.351598
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/ThanksViewModel.swift
1
12109
import KsApi import Prelude import ReactiveExtensions import ReactiveSwift import UIKit public typealias ThanksPageData = ( project: Project, reward: Reward, checkoutData: KSRAnalytics.CheckoutPropertiesData? ) public protocol ThanksViewModelInputs { /// Call to configure the VM func configure(with data: ThanksPageData) /// Call when close button is tapped func closeButtonTapped() /// Call when category cell is tapped func categoryCellTapped(_ category: KsApi.Category) /// Call when project cell is tapped func projectTapped(_ project: Project) /// Call when signup button is tapped on games newsletter alert func gamesNewsletterSignupButtonTapped() /// Call when the current user has been updated in the environment func userUpdated() /// Call when the view controller view did load func viewDidLoad() } public protocol ThanksViewModelOutputs { /// Emits backed project subheader text to display var backedProjectText: Signal<NSAttributedString, Never> { get } /// Emits when view controller should dismiss var dismissToRootViewControllerAndPostNotification: Signal<Notification, Never> { get } /// Emits DiscoveryParams when should go to Discovery var goToDiscovery: Signal<DiscoveryParams, Never> { get } /// Emits project when should go to Project page var goToProject: Signal<(Project, [Project], RefTag), Never> { get } /// Emits when a user pledges a project for the first time. var postContextualNotification: Signal<(), Never> { get } /// Emits when a user updated notification should be posted var postUserUpdatedNotification: Signal<Notification, Never> { get } /// Emits when should show games newsletter alert var showGamesNewsletterAlert: Signal<(), Never> { get } /// Emits newsletter title when should show games newsletter opt-in alert var showGamesNewsletterOptInAlert: Signal<String, Never> { get } /// Emits when should show rating alert var showRatingAlert: Signal<(), Never> { get } /// Emits array of projects and a category when should show recommendations var showRecommendations: Signal<([Project], KsApi.Category, OptimizelyExperiment.Variant), Never> { get } /// Emits a User that can be used to replace the current user in the environment var updateUserInEnvironment: Signal<User, Never> { get } } public protocol ThanksViewModelType { var inputs: ThanksViewModelInputs { get } var outputs: ThanksViewModelOutputs { get } } public final class ThanksViewModel: ThanksViewModelType, ThanksViewModelInputs, ThanksViewModelOutputs { public init() { let project = self.configureWithDataProperty.signal .skipNil() .map(first) let rewardAndCheckoutData = self.configureWithDataProperty.signal .skipNil() .map { ($0.reward, $0.checkoutData) } self.backedProjectText = project.map { let string = Strings.You_have_successfully_backed_project_html( project_name: $0.name ) return string.simpleHtmlAttributedString(font: UIFont.ksr_subhead(), bold: UIFont.ksr_subhead().bolded) ?? NSAttributedString(string: "") } .takeWhen(self.viewDidLoadProperty.signal) let shouldShowGamesAlert = project .map { project in project.category.rootId == KsApi.Category.gamesId && !(AppEnvironment.current.currentUser?.newsletters.games ?? false) && !AppEnvironment.current.userDefaults.hasSeenGamesNewsletterPrompt } self.showGamesNewsletterAlert = shouldShowGamesAlert .filter(isTrue) .takeWhen(self.viewDidLoadProperty.signal) .ignoreValues() self.showGamesNewsletterOptInAlert = self.gamesNewsletterSignupButtonTappedProperty.signal .filter { AppEnvironment.current.countryCode == "DE" } .map(Strings.profile_settings_newsletter_games) self.showRatingAlert = shouldShowGamesAlert .filter { $0 == false && !AppEnvironment.current.userDefaults.hasSeenAppRating && AppEnvironment.current.config?.iTunesLink != nil && shouldShowPledgeDialog() == false } .takeWhen(self.viewDidLoadProperty.signal) .ignoreValues() .on(value: { AppEnvironment.current.userDefaults.hasSeenAppRating = true }) self.dismissToRootViewControllerAndPostNotification = self.closeButtonTappedProperty.signal .mapConst(Notification(name: .ksr_projectBacked)) self.goToDiscovery = self.categoryCellTappedProperty.signal.skipNil() .map { DiscoveryParams.defaults |> DiscoveryParams.lens.category .~ $0 } let rootCategory: Signal<KsApi.Category, Never> = project .map { toBase64($0.category) } .flatMap { AppEnvironment.current.apiService.fetchGraphCategory(id: $0) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .map { (categoryEnvelope: KsApi.CategoryEnvelope) -> KsApi.Category in categoryEnvelope.node.parent ?? categoryEnvelope.node } .demoteErrors() } let projects = Signal.combineLatest(project, rootCategory) .flatMap { relatedProjects(toProject: $0.0, inCategory: $0.1) } .filter { projects in !projects.isEmpty } self.showRecommendations = Signal.zip(projects, rootCategory).map { projects, category in let variant = OptimizelyExperiment.nativeProjectCardsExperimentVariant() return (projects, category, variant) } self.goToProject = self.showRecommendations .map(first) .takePairWhen(self.projectTappedProperty.signal.skipNil()) .map { projects, project in (project, projects, RefTag.thanks) } self.updateUserInEnvironment = self.gamesNewsletterSignupButtonTappedProperty.signal .map { AppEnvironment.current.currentUser ?? nil } .skipNil() .switchMap { user in AppEnvironment.current.apiService.updateUserSelf(user |> \.newsletters.games .~ true) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .demoteErrors() } self.postContextualNotification = self.viewDidLoadProperty.signal .filter { shouldShowPledgeDialog() } self.postUserUpdatedNotification = self.userUpdatedProperty.signal .mapConst(Notification(name: .ksr_userUpdated)) self.showGamesNewsletterAlert .observeValues { AppEnvironment.current.userDefaults.hasSeenGamesNewsletterPrompt = true } self.projectTappedProperty.signal.skipNil() .map { project in (project, recommendedParams) } .combineLatest(with: rewardAndCheckoutData) .observeValues { projectAndParams, rewardAndCheckoutData in let (project, params) = projectAndParams let (reward, checkoutData) = rewardAndCheckoutData AppEnvironment.current.ksrAnalytics.trackProjectCardClicked( page: .thanks, project: project, checkoutData: checkoutData, typeContext: .recommended, location: .curated, params: params, reward: reward ) } Signal.combineLatest( self.configureWithDataProperty.signal.skipNil(), self.viewDidLoadProperty.signal.ignoreValues() ) .map(first) .observeValues { AppEnvironment.current.ksrAnalytics.trackThanksPageViewed( project: $0.project, reward: $0.reward, checkoutData: $0.checkoutData ) } } // MARK: - ThanksViewModelType public var inputs: ThanksViewModelInputs { return self } public var outputs: ThanksViewModelOutputs { return self } // MARK: - ThanksViewModelInputs fileprivate let configureWithDataProperty = MutableProperty<ThanksPageData?>(nil) public func configure(with data: ThanksPageData) { self.configureWithDataProperty.value = data } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } fileprivate let closeButtonTappedProperty = MutableProperty(()) public func closeButtonTapped() { self.closeButtonTappedProperty.value = () } fileprivate let categoryCellTappedProperty = MutableProperty<KsApi.Category?>(nil) public func categoryCellTapped(_ category: KsApi.Category) { self.categoryCellTappedProperty.value = category } fileprivate let projectTappedProperty = MutableProperty<Project?>(nil) public func projectTapped(_ project: Project) { self.projectTappedProperty.value = project } fileprivate let gamesNewsletterSignupButtonTappedProperty = MutableProperty(()) public func gamesNewsletterSignupButtonTapped() { self.gamesNewsletterSignupButtonTappedProperty.value = () } fileprivate let userUpdatedProperty = MutableProperty(()) public func userUpdated() { self.userUpdatedProperty.value = () } // MARK: - ThanksViewModelOutputs public let dismissToRootViewControllerAndPostNotification: Signal<Notification, Never> public let goToDiscovery: Signal<DiscoveryParams, Never> public let backedProjectText: Signal<NSAttributedString, Never> public let goToProject: Signal<(Project, [Project], RefTag), Never> public let postContextualNotification: Signal<(), Never> public let postUserUpdatedNotification: Signal<Notification, Never> public let showRatingAlert: Signal<(), Never> public let showGamesNewsletterAlert: Signal<(), Never> public let showGamesNewsletterOptInAlert: Signal<String, Never> public let showRecommendations: Signal<([Project], KsApi.Category, OptimizelyExperiment.Variant), Never> public let updateUserInEnvironment: Signal<User, Never> } /* This is a work around that fixes the incompatibility between the types of category id returned by the server (Int) and the type we need to send when requesting category by id through GraphQL (base64 encoded String). This will be removed once we start consuming GraphQL to fetch Discovery projects. */ private func toBase64(_ category: Project.Category) -> String { let id = category.parentId ?? category.id let decodedId = Category.decode(id: "\(id)") return decodedId.toBase64() } private func relatedProjects( toProject project: Project, inCategory category: KsApi.Category ) -> SignalProducer<[Project], Never> { let base = DiscoveryParams.lens.perPage .~ 3 <> DiscoveryParams.lens.backed .~ false let similarToParams = DiscoveryParams.defaults |> base |> DiscoveryParams.lens.similarTo .~ project let staffPickParams = DiscoveryParams.defaults |> base |> DiscoveryParams.lens.staffPicks .~ true |> DiscoveryParams.lens.category .~ category let recommendedProjects = AppEnvironment.current.apiService.fetchDiscovery(params: recommendedParams) .demoteErrors() .map { shuffle(projects: $0.projects) } .uncollect() let similarToProjects = AppEnvironment.current.apiService.fetchDiscovery(params: similarToParams) .demoteErrors() .map { $0.projects } .uncollect() let staffPickProjects = AppEnvironment.current.apiService.fetchDiscovery(params: staffPickParams) .demoteErrors() .map { $0.projects } .uncollect() return SignalProducer.concat(recommendedProjects, similarToProjects, staffPickProjects) .filter { $0.id != project.id } .uniqueValues { $0.id } .take(first: 3) .collect() } private func shouldShowPledgeDialog() -> Bool { return PushNotificationDialog.canShowDialog(for: .pledge) && AppEnvironment.current.currentUser?.stats.backedProjectsCount == 0 } // Shuffle an array without mutating the input argument. // Based on the Fisher-Yates shuffle algorithm https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle. private func shuffle(projects xs: [Project]) -> [Project] { var ys = xs let length = ys.count if length > 1 { for i in 0...length - 1 { let j = Int(arc4random_uniform(UInt32(length - 1))) let temp = ys[i] ys[i] = ys[j] ys[j] = temp } return ys } else { return xs } } private let recommendedParams = DiscoveryParams.defaults |> DiscoveryParams.lens.backed .~ false |> DiscoveryParams.lens.perPage .~ 6 |> DiscoveryParams.lens.recommended .~ true
apache-2.0
0326433e1a9e45b66709bb335d9d64a7
34.825444
109
0.728632
4.579803
false
false
false
false
wang-chuanhui/CHSDK
Source/Utils/UIColor.swift
1
2044
// // UIColor.swift // Pods // // Created by 王传辉 on 2017/8/7. // // import UIKit extension UIColor: Compatible { } public extension NameSpace where Base: UIColor { static func integer(red: Int, green: Int, blue: Int, alpha: CGFloat = 1) -> UIColor { return UIColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha) } static var random: UIColor { let red = Int(arc4random_uniform(255)) let green = Int(arc4random_uniform(255)) let blue = Int(arc4random_uniform(255)) let color = UIColor(integer: red, green: green, blue: blue) return color } static func hexColor(_ hex: String) -> UIColor { let str = hex.replacingOccurrences(of: "#", with: "") let zero = str.startIndex let two = str.index(zero, offsetBy: 2) let four = str.index(two, offsetBy: 2) let red = String(str[zero..<two]) let green = String(str[two..<four]) let blue = String(str[four...]) var r: UInt64 = 0 var g: UInt64 = 0 var b: UInt64 = 0 Scanner(string: red).scanHexInt64(&r) Scanner(string: green).scanHexInt64(&g) Scanner(string: blue).scanHexInt64(&b) return UIColor(integer: Int(r), green: Int(g), blue: Int(b)) } func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { let rect = CGRect(origin: CGPoint.zero, size: size) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(base.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() if image != nil { return image! } return UIImage() } } public extension UIColor { convenience init(integer red: Int, green: Int, blue: Int, alpha: CGFloat = 1) { self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha) } }
mit
550f50ffa2cbafdecd9c61a16edcb2fc
30.353846
117
0.598626
3.816479
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/Tool/Ping/Model/SimplePingHelper.swift
1
2528
// // SimplePingHelper.swift // Pods // // Created by Chris Anderson on 2/14/16. // // import UIKit import LANScanner class SimplePingHelper: NSObject, SimplePingDelegate { private var address:String private var simplePing:SimplePing? private var target:AnyObject private var selector:Selector private var startTime:NSDate? private var time:NSTimeInterval = 0 static func start(address:String, target:AnyObject, selector:Selector) { SimplePingHelper(address: address, target: target, selector: selector).start() } init(address: String, target:AnyObject, selector:Selector) { self.simplePing = SimplePing(hostName:address) self.target = target self.selector = selector self.address = address super.init() self.simplePing!.delegate = self } func start() { self.startTime = NSDate() self.simplePing?.start() self.performSelector(#selector(SimplePingHelper.endTime), withObject: nil, afterDelay: 1) } // MARK: - Helper Methods func killPing() { self.time = floor(abs((self.startTime?.timeIntervalSinceNow)!) * 1000) self.simplePing?.stop() self.simplePing = nil } func successPing() { self.killPing() self.target.performSelector(self.selector, withObject: [ "status": true, "address": self.address, "time":self.time ]) } func failPing(reason: String) { self.killPing() self.target.performSelector(self.selector, withObject: [ "status": false, "address": self.address, "error": reason ]) } func endTime() { if let _ = self.simplePing { self.failPing("timeout") return } } // MARK: - SimplePing Delegate func simplePing(pinger: SimplePing!, didStartWithAddress address: NSData!) { self.simplePing?.sendPingWithData(nil) } func simplePing(pinger: SimplePing!, didFailWithError error: NSError!) { self.failPing("didFailWithError") } func simplePing(pinger: SimplePing!, didFailToSendPacket packet: NSData!, error: NSError!) { self.failPing("didFailToSendPacked") } func simplePing(pinger: SimplePing!, didReceivePingResponsePacket packet: NSData!) { self.successPing() } }
gpl-2.0
2ac71005413bc175a2cd931c48acce59
24.795918
97
0.595728
4.530466
false
false
false
false
practicalswift/swift
test/Parse/multiline_string.swift
27
2539
// RUN: %target-swift-frontend -dump-ast %s | %FileCheck %s import Swift // ===---------- Multiline --------=== _ = """ One ""Alpha"" """ // CHECK: "One\n\"\"Alpha\"\"" _ = """ Two Beta """ // CHECK: " Two\nBeta" _ = """ Three Gamma """ // CHECK: " Three\n Gamma" _ = """ Four Delta """ // CHECK: " Four\n Delta" _ = """ Five\n Epsilon """ // CHECK: "Five\n\n\nEpsilon" _ = """ Six Zeta """ // CHECK: "Six\nZeta\n" _ = """ Seven Eta\n """ // CHECK: "Seven\nEta\n" _ = """ \""" "\"" ""\" Iota """ // CHECK: "\"\"\"\n\"\"\"\n\"\"\"\nIota" _ = """ \("Nine") Kappa """ // CHECK: "\nKappa" _ = """ first second third """ // CHECK: "first\n second\nthird" _ = """ first second third """ // CHECK: "first\n\tsecond\nthird" _ = """ \\ """ // CHECK: "\\" _ = """ \\ """ // CHECK: "\\" _ = """ ABC """ // CHECK: "\nABC" _ = """ ABC """ // CHECK: "\nABC" _ = """ ABC """ // CHECK: "\nABC" // contains tabs _ = """ Twelve Nu """ // CHECK: "Twelve\nNu" _ = """ newline \ elided """ // CHECK: "newline elided" // contains trailing whitepsace _ = """ trailing \ \(""" substring1 \ \(""" substring2 \ substring3 """) """) \ whitepsace """ // CHECK: "trailing " // CHECK: "substring1 " // CHECK: "substring2 substring3" // CHECK: " whitepsace" // contains trailing whitepsace _ = """ foo\ bar """ // CHECK: "foo\nbar" // contains trailing whitepsace _ = """ foo\ bar """ // CHECK: "foo\nbar" _ = """ foo \ bar """ // CHECK: "foo bar" _ = """ ABC """ // CHECK: "\nABC" _ = """ ABC """ // CHECK: "\nABC\n" _ = """ """ // CHECK: "\n" _ = """ """ // CHECK: "" _ = """ """ // CHECK: "" _ = "\(""" \("a" + """ valid """) """) literal" // CHECK: "a" // CHECK: " valid" // CHECK: " literal" _ = "hello\(""" world """)" // CHECK: "hello" // CHECK: "world" _ = """ hello\(""" world """) abc """ // CHECK: "hello" // CHECK: "world" // CHECK: "\nabc" _ = "hello\(""" "world' """)abc" // CHECK: "hello" // CHECK: "\"world'" // CHECK: "abc" _ = """ welcome \( /* ')' or '"""' in comment. """ */ "to\(""" Swift """)" // ) or """ in comment. ) ! """ // CHECK: "welcome\n" // CHECK: "to" // CHECK: "Swift" // CHECK: "\n!"
apache-2.0
9f502a1d46358beeae1f312ecbf88bb3
9.668067
59
0.381252
2.771834
false
false
false
false
ImranRaheem/iOS-11-samples
Emojifier/Emojifier/AVCaptureDevice+Extension.swift
1
3052
// // AVCaptureDevice+Extension.swift // BestChannelFinder // // Created by imran on 16/6/17. // Copyright © 2017 Imran. All rights reserved. // import AVFoundation extension AVCaptureDevice { private func availableFormatsFor(preferredFps: Float64) -> [AVCaptureDevice.Format] { var availableFormats: [AVCaptureDevice.Format] = [] for format in formats { let ranges = format.videoSupportedFrameRateRanges for range in ranges where range.minFrameRate <= preferredFps && preferredFps <= range.maxFrameRate { availableFormats.append(format) } } return availableFormats } private func formatWithHighestResolution(_ availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format? { var maxWidth: Int32 = 0 var selectedFormat: AVCaptureDevice.Format? for format in availableFormats { let desc = format.formatDescription let dimensions = CMVideoFormatDescriptionGetDimensions(desc) let width = dimensions.width if width >= maxWidth { maxWidth = width selectedFormat = format } } return selectedFormat } private func formatFor(preferredSize: CGSize, availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format? { for format in availableFormats { let desc = format.formatDescription let dimensions = CMVideoFormatDescriptionGetDimensions(desc) if dimensions.width >= Int32(preferredSize.width) && dimensions.height >= Int32(preferredSize.height) { return format } } return nil } func updateFormatWithPreferredVideoSpec(preferredSpec: VideoSpec) { let availableFormats: [AVCaptureDevice.Format] if let preferredFps = preferredSpec.fps { availableFormats = availableFormatsFor(preferredFps: Float64(preferredFps)) } else { availableFormats = formats } var selectedFormat: AVCaptureDevice.Format? if let preferredSize = preferredSpec.size { selectedFormat = formatFor(preferredSize: preferredSize, availableFormats: availableFormats) } else { selectedFormat = formatWithHighestResolution(availableFormats) } print("selected format: \(String(describing: selectedFormat))") if let selectedFormat = selectedFormat { do { try lockForConfiguration() } catch { fatalError("") } activeFormat = selectedFormat if let preferredFps = preferredSpec.fps { activeVideoMinFrameDuration = CMTimeMake(1, preferredFps) activeVideoMaxFrameDuration = CMTimeMake(1, preferredFps) unlockForConfiguration() } } } }
mit
fee147f45e60fc239ac557153af2e5d5
33.280899
120
0.606686
5.587912
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/PendingTransactionPage/PendingTransactionStateProvider/DepositPendingTransactionStateProvider.swift
1
3724
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import PlatformUIKit import RxCocoa import RxSwift import ToolKit final class DepositPendingTransactionStateProvider: PendingTransactionStateProviding { private typealias LocalizationIds = LocalizationConstants.Transaction.Deposit.Completion // MARK: - PendingTransactionStateProviding func connect(state: Observable<TransactionState>) -> Observable<PendingTransactionPageState> { state.compactMap { [weak self] state -> PendingTransactionPageState? in guard let self = self else { return nil } switch state.executionStatus { case .notStarted, .pending, .inProgress: return self.pending(state: state) case .error: return nil case .completed: return self.success(state: state) } } } // MARK: - Private Functions private func success(state: TransactionState) -> PendingTransactionPageState { let date = Calendar.current.date(byAdding: .day, value: 5, to: Date()) ?? Date() let value = DateFormatter.medium.string(from: date) let amount = state.amount let currency = amount.currency return .init( title: String(format: LocalizationIds.Success.title, amount.displayString), subtitle: String( format: LocalizationIds.Success.description, amount.displayString, amount.displayCode, value ), compositeViewType: .composite( .init( baseViewType: .badgeImageViewModel( .primary( image: currency.logoResource, contentColor: .white, backgroundColor: currency.isFiatCurrency ? .fiat : currency.brandUIColor, cornerRadius: .roundedHigh, accessibilityIdSuffix: "PendingTransactionSuccessBadge" ) ), sideViewAttributes: .init( type: .image(PendingStateViewModel.Image.success.imageResource), position: .radiusDistanceFromCenter ) ) ), effect: .complete, primaryButtonViewModel: .primary(with: LocalizationConstants.okString), action: state.action ) } private func pending(state: TransactionState) -> PendingTransactionPageState { let amount = state.amount let currency = amount.currency return .init( title: String( format: LocalizationIds.Pending.title, amount.displayString ), subtitle: LocalizationIds.Pending.description, compositeViewType: .composite( .init( baseViewType: .badgeImageViewModel( .primary( image: amount.currency.logoResource, contentColor: .white, backgroundColor: currency.isFiatCurrency ? .fiat : currency.brandUIColor, cornerRadius: .roundedHigh, accessibilityIdSuffix: "PendingTransactionPendingBadge" ) ), sideViewAttributes: .init(type: .loader, position: .radiusDistanceFromCenter), cornerRadiusRatio: 0.5 ) ), action: state.action ) } }
lgpl-3.0
824a65067f753733a0b10a743baabc4b
38.189474
101
0.553049
6.053659
false
false
false
false
sekouperry/bemyeyes-ios
BeMyEyes Tests/DataHelper.swift
2
3113
// // DataHelper.swift // BeMyEyes // // Created by Tobias Due Munk on 19/11/14. // Copyright (c) 2014 Be My Eyes. All rights reserved. // import UIKit extension BMEUser { class func idealUser() -> BMEUser { let user = BMEUser() if let image = UIImage(named: "ProfileSarah.png") { user.setValue(image, forKey: "profileImage") } user.setValue("Sara", forKey: "firstName") user.setValue(345, forKey: "totalPoints") user.setValue(13, forKey: "peopleHelped") let currentLevel = BMEUserLevel() currentLevel.title = "Trusted Helper" currentLevel.threshold = 200 user.setValue(currentLevel, forKey: "currentLevel") let nextLevel = BMEUserLevel() nextLevel.threshold = 500 user.setValue(nextLevel, forKey: "nextLevel") var point1 = BMEPointEntry() point1.setValue(30, forKey: "point") point1.setValue("finish_helping_request", forKey: "event") point1.setValue(NSDate().dateByAddingTimeInterval(-60*2), forKey: "date") var point2 = BMEPointEntry() point2.setValue(5, forKey: "point") point2.setValue("answer_push_message", forKey: "event") point2.setValue(NSDate().dateByAddingTimeInterval(-60*60*3), forKey: "date") var point3 = BMEPointEntry() point3.setValue(30, forKey: "point") point3.setValue("finish_helping_request", forKey: "event") point3.setValue(NSDate().dateByAddingTimeInterval(-60*60*24), forKey: "date") var point4 = BMEPointEntry() point4.setValue(30, forKey: "point") point4.setValue("finish_helping_request", forKey: "event") point4.setValue(NSDate().dateByAddingTimeInterval(-60*60*72), forKey: "date") user.setValue([point1, point2, point3, point4], forKey: "lastPointEntries") return user } } extension BMECommunityStats { class func idealStats() -> BMECommunityStats { var stats = BMECommunityStats() stats.sighted = 218711 stats.blind = 19053 stats.helped = 75888 return stats } } //@"signup"]) { // S_ENTRY_SIGNUP_DESCRIPTION; // String:@"answer_push_message"]) { // S_ENTRY_ANSWER_PUSH_MESSAGE_DESCRIPTION; // String:@"answer_push_message_technical_error"] // S_ENTRY_ANSWER_PUSH_MESSAGE_TECHNICAL_ERROR_DE // String:@"finish_helping_request"]) { // S_ENTRY_FINISH_HELPING_REQUEST_DESCRIPTION; // String:@"finish_10_helping_request_in_a_week"] // S_ENTRY_FINISH_10_HELPING_REQUESTS_IN_A_WEEK_D // String:@"finish_5_high_fives_in_a_week"]) { // S_ENTRY_FINISH_5_HIGH_FIVES_IN_A_WEEK_DESCRIPT // String:@"share_on_twitter"]) { // S_ENTRY_SHARE_ON_TWITTER_DESCRIPTION; // String:@"share_on_facebook"]) { // S_ENTRY_SHARE_ON_FACEBOOK_DESCRIPTION; // String:@"watch_video"]) { // S_ENTRY_WATCH_VIDEO_DESCRIPTION;
mit
8a4b161f9220477f02032732d0a4b4fa
36.963415
85
0.598137
3.764208
false
false
false
false
PekanMmd/Pokemon-XD-Code
enums/XGASM.swift
1
16668
// // XGASM.swift // GoD Tool // // Created by The Steez on 18/09/2018. // import Foundation enum XGRegisters : UInt32 { case r0 = 0 case r1, r2,r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15 case r16, r17, r18, r19, r20, r21, r22, r23, r24, r25, r26, r27, r28, r29, r30, r31 // special purpose registers case sp, lr, ctr, srr0, srr1 var value: UInt32 { switch self { case .sp : return 1 case .lr : return 8 case .ctr : return 9 case .srr0: return 26 case .srr1: return 27 default: return self.rawValue } } } enum XGASM { case mr(XGRegisters, XGRegisters) case mr_(XGRegisters, XGRegisters) // same but affects condition register. denoted by 'mr.' normally case mfspr(XGRegisters, XGRegisters) case mflr(XGRegisters) case mfctr(XGRegisters) case mtspr(XGRegisters, XGRegisters) case mtlr(XGRegisters) case mtctr(XGRegisters) case bctr case cmpw(XGRegisters, XGRegisters) case cmplw(XGRegisters, XGRegisters) case cmpwi(XGRegisters, Int) case cmplwi(XGRegisters, UInt32) case li(XGRegisters, Int) case lis(XGRegisters, Int) case extsb(XGRegisters, XGRegisters) case extsh(XGRegisters, XGRegisters) case slw(XGRegisters, XGRegisters, XGRegisters) case srawi(XGRegisters, XGRegisters, UInt32) case rlwinm(XGRegisters, XGRegisters, UInt32, UInt32, UInt32) case rlwinm_(XGRegisters, XGRegisters, UInt32, UInt32, UInt32) // same but affects condition register. denoted by 'rlwinm.' normally case lha(XGRegisters, XGRegisters, Int) case lhax(XGRegisters, XGRegisters, XGRegisters) case lbz(XGRegisters, XGRegisters, Int) case lhz(XGRegisters, XGRegisters, Int) case lwz(XGRegisters, XGRegisters, Int) case lbzx(XGRegisters, XGRegisters, XGRegisters) case lhzx(XGRegisters, XGRegisters, XGRegisters) case lwzx(XGRegisters, XGRegisters, XGRegisters) case stb(XGRegisters, XGRegisters, Int) case sth(XGRegisters, XGRegisters, Int) case stw(XGRegisters, XGRegisters, Int) case stwu(XGRegisters, XGRegisters, Int) case stbx(XGRegisters, XGRegisters, XGRegisters) case sthx(XGRegisters, XGRegisters, XGRegisters) case stwx(XGRegisters, XGRegisters, XGRegisters) case lmw(XGRegisters, XGRegisters, Int) case stmw(XGRegisters, XGRegisters, Int) case add(XGRegisters, XGRegisters, XGRegisters) case addi(XGRegisters, XGRegisters, Int) case addis(XGRegisters, XGRegisters, Int) case addze(XGRegisters, XGRegisters) case sub(XGRegisters, XGRegisters, XGRegisters) case subi(XGRegisters, XGRegisters, Int) case neg(XGRegisters, XGRegisters) case mulli(XGRegisters, XGRegisters, Int) case mullw(XGRegisters, XGRegisters, XGRegisters) case divw(XGRegisters, XGRegisters, XGRegisters) case divwu(XGRegisters, XGRegisters, XGRegisters) case or(XGRegisters, XGRegisters, XGRegisters) case ori(XGRegisters, XGRegisters, UInt32) case and(XGRegisters, XGRegisters, XGRegisters) case and_(XGRegisters, XGRegisters, XGRegisters) case andi_(XGRegisters, XGRegisters, UInt32) case b(Int) case ba(Int) case bl(Int) case bla(Int) case blr case beq(Int) case bne(Int) case blt(Int) case ble(Int) case bgt(Int) case bge(Int) case nop // convenience instructions - not real PPC instructions // from offset to offset case b_f(Int, Int) case bl_f(Int, Int) case beq_f(Int, Int) case bne_f(Int, Int) case blt_f(Int, Int) case ble_f(Int, Int) case bgt_f(Int, Int) case bge_f(Int, Int) // to label with name case b_l(String) case bl_l(String) case beq_l(String) case bne_l(String) case blt_l(String) case ble_l(String) case bgt_l(String) case bge_l(String) // raw binary case raw(UInt32) // labels for conviently specifying addresses case label(String) var code: UInt32 { return codeAtOffset(0) } private func codeForAdd() -> UInt32 { switch self { case .add(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (266 << 1) case .addi(let rd, let ra, let simm): return (UInt32(14) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(simm)) & 0xFFFF) case .addis(let rd, let ra, let simm): return (UInt32(15) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(simm)) & 0xFFFF) case .addze(let rd, let ra): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (202 << 1) default: return 0 } } private func codeForSub() -> UInt32 { switch self { case .sub(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (rb.value << 16) | (ra.value << 11) | (40 << 1) case .subi(let rd, let ra, let simm): return XGASM.addi(rd, ra, -simm).code case .neg(let rd, let ra): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (104 << 1) default: return 0 } } private func codeForLoadImm() -> UInt32 { switch self { case .li(let rd, let simm): return XGASM.addi(rd, .r0, simm).code case .lis(let rd, let simm): return XGASM.addis(rd, .r0, simm).code default: return 0 } } private func codeForExtend() -> UInt32 { switch self { case .extsb(let rd, let rs): return (UInt32(31) << 26) | (rs.value << 21) | (rd.value << 16) | (954 << 1) case .extsh(let rd, let rs): return (UInt32(31) << 26) | (rs.value << 21) | (rd.value << 16) | (922 << 1) default: return 0 } } private func codeForLoad() -> UInt32 { switch self { case .lbz(let rd, let ra, let d): return (UInt32(34) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .lha(let rd, let ra, let d): return (UInt32(42) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .lhz(let rd, let ra, let d): return (UInt32(40) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .lwz(let rd, let ra, let d): return (UInt32(32) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .lbzx(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (87 << 1) case .lhax(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (343 << 1) case .lhzx(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (279 << 1) case .lwzx(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (23 << 1) default: return 0 } } private func codeForStore() -> UInt32 { switch self { case .stb(let rs, let ra, let d): return (UInt32(38) << 26) | (rs.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .sth(let rs, let ra, let d): return (UInt32(44) << 26) | (rs.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .stw(let rs, let ra, let d): return (UInt32(36) << 26) | (rs.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .stwu(let rs, let ra, let d): return (UInt32(37) << 26) | (rs.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .stbx(let rs, let ra, let rb): return (UInt32(31) << 26) | (rs.value << 21) | (ra.value << 16) | (rb.value << 11) | (215 << 1) case .sthx(let rs, let ra, let rb): return (UInt32(31) << 26) | (rs.value << 21) | (ra.value << 16) | (rb.value << 11) | (407 << 1) case .stwx(let rs, let ra, let rb): return (UInt32(31) << 26) | (rs.value << 21) | (ra.value << 16) | (rb.value << 11) | (151 << 1) default: return 0 } } private func codeForLoadStoreMultiple() -> UInt32 { switch self { case .lmw(let rd, let ra, let d): return (UInt32(46) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) case .stmw(let rd, let ra, let d): return (UInt32(47) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(d)) & 0xFFFF) default: return 0 } } private func codeForShift() -> UInt32 { switch self { case .slw(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (24 << 1) case .srawi(let rd, let ra, let sh): return (UInt32(31) << 26) | (ra.value << 21) | (rd.value << 16) | (sh << 11) | (824 << 1) case .rlwinm(let rd, let ra, let sh, let mb, let me): return (UInt32(21) << 26) | (ra.value << 21) | (rd.value << 16) | (sh << 11) | (mb << 6) | (me << 1) case .rlwinm_(let rd, let ra, let sh, let mb, let me): return XGASM.rlwinm(rd,ra,sh,mb,me).code | 1 default: return 0 } } private func codeForOrMr() -> UInt32 { switch self { case .or(let rd, let ra, let rb): return (UInt32(31) << 26) | (ra.value << 21) | (rd.value << 16) | (rb.value << 11) | (444 << 1) case .ori(let rd, let ra, let uimm): return (UInt32(24) << 26) | (ra.value << 21) | (rd.value << 16) | (uimm & 0xFFFF) case .mr(let rd, let rs): return XGASM.or(rd, rs, rs).code case .mr_(let rd, let rs): return XGASM.mr(rd, rs).code | 1 default: return 0 } } private func codeForAnd() -> UInt32 { switch self { case .and(let rd, let ra, let rb): return (UInt32(31) << 26) | (ra.value << 21) | (rd.value << 16) | (rb.value << 11) | (28 << 1) case .and_(let rd, let ra, let rb): var result = (UInt32(31) << 26) | (ra.value << 21) | (rd.value << 16) | (rb.value << 11) result |= (28 << 1) + 1 return result case .andi_(let rd, let ra, let uimm): return (UInt32(28) << 26) | (ra.value << 21) | (rd.value << 16) | (uimm & 0xFFFF) default: return 0 } } func instructionForBranchToLabel(labels: [String : Int]) -> XGASM { switch self { case .b_l(let name): return .b(labels[name] ?? 0) case .bl_l(let name): return .bl(labels[name] ?? 0) case .beq_l(let name): return .beq(labels[name] ?? 0) case .bne_l(let name): return .bne(labels[name] ?? 0) case .blt_l(let name): return .blt(labels[name] ?? 0) case .ble_l(let name): return .ble(labels[name] ?? 0) case .bgt_l(let name): return .bgt(labels[name] ?? 0) case .bge_l(let name): return .bge(labels[name] ?? 0) default: return .nop } } func codeAtOffset(_ offset: Int) -> UInt32 { // split into sub functions so compiler can relax switch self { // add / subtract case .add, .addi, .addis, .addze: return codeForAdd() case .sub: fallthrough case .subi: fallthrough case .neg: return codeForSub() // load immediate case .li: fallthrough case .lis: return codeForLoadImm() // extend case .extsb: fallthrough case .extsh: return codeForExtend() // load and zero case .lbz: fallthrough case .lha: fallthrough case .lhz: fallthrough case .lwz: fallthrough // load and zero indexed case .lbzx: fallthrough case .lhax: fallthrough case .lhzx: fallthrough case .lwzx: return codeForLoad() // store case .stb: fallthrough case .sth: fallthrough case .stw: fallthrough case .stwu: fallthrough // store indexed case .stbx: fallthrough case .sthx: fallthrough case .stwx: return codeForStore() // load / store multiple case .lmw: fallthrough case .stmw: return codeForLoadStoreMultiple() // shift / rotate case .slw: fallthrough case .srawi: fallthrough case .rlwinm: fallthrough case .rlwinm_: return codeForShift() // and case .and: fallthrough case .and_: fallthrough case .andi_: return codeForAnd() // or case .or: fallthrough case .ori: fallthrough // mr case .mr: fallthrough case .mr_: return codeForOrMr() // link register case .mfspr(let rd, let spr): return (UInt32(31) << 26) | (rd.value << 21) | (spr.value << 16) | (339 << 1) case .mflr(let rd): return XGASM.mfspr(rd, .lr).code case .mfctr(let rd): return XGASM.mfspr(rd, .ctr).code case .mtspr(let spr, let rs): return (UInt32(31) << 26) | (rs.value << 21) | (spr.value << 16) | (467 << 1) case .mtlr(let rs): return XGASM.mtspr(.lr, rs).code case .mtctr(let rs): return XGASM.mtspr(.ctr, rs).code case .bctr: return 0x4e800420 // compare case .cmpw(let ra, let rb): return (UInt32(31) << 26) | (ra.value << 16) | (rb.value << 11) case .cmpwi(let ra, let simm): return (UInt32(11) << 26) | (ra.value << 16) | (UInt32(bitPattern: Int32(simm)) & 0xFFFF) case .cmplw(let ra, let rb): return (UInt32(31) << 26) | (ra.value << 16) | (rb.value << 11) | (32 << 1) case .cmplwi(let ra, let uimm): return (UInt32(10) << 26) | (ra.value << 16) | uimm // multiply / divide case .mulli(let rd, let ra, let simm): return (UInt32(7) << 26) | (rd.value << 21) | (ra.value << 16) | (UInt32(bitPattern: Int32(simm)) & 0xFFFF) case .mullw(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (235 << 1) case .divw(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (491 << 1) case .divwu(let rd, let ra, let rb): return (UInt32(31) << 26) | (rd.value << 21) | (ra.value << 16) | (rb.value << 11) | (459 << 1) // relative branches case .b_f(let o, let t): let to = t > 0x80000000 ? t - 0x80000000 : t let offset = o > 0x80000000 ? o - 0x80000000 : o return 0x48000000 | (UInt32(bitPattern: Int32(to - offset) & 0x3FFFFFF)) case .bl_f(let o, let t): return XGASM.b_f(o, t).code + 1 // blr case .blr: return 0x4e800020 // conditional relative branches case .beq_f(let o, let t): return 0x41820000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) case .bne_f(let o, let t): return 0x40820000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) case .blt_f(let o, let t): return 0x41800000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) case .ble_f(let o, let t): return 0x40810000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) case .bgt_f(let o, let t): return 0x41810000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) case .bge_f(let o, let t): return 0x40800000 | (UInt32(bitPattern: Int32(t - o)) & 0xFFFF) // absolute branches case .b(let target): return XGASM.b_f(offset, target).code case .bl(let target): return XGASM.bl_f(offset, target).code case .beq(let target): return XGASM.beq_f(offset, target).code case .bne(let target): return XGASM.bne_f(offset, target).code case .blt(let target): return XGASM.blt_f(offset, target).code case .ble(let target): return XGASM.ble_f(offset, target).code case .bgt(let target): return XGASM.bgt_f(offset, target).code case .bge(let target): return XGASM.bge_f(offset, target).code case .ba(let t): return XGASM.b_f(0, t).code + 2 case .bla(let t): return XGASM.b_f(0, t).code + 3 // nop case .nop: return 0x60000000 // raw case .raw(let value): return value case .label: return XGASM.nop.codeAtOffset(offset) case .b_l: fallthrough case .bl_l: fallthrough case .beq_l: fallthrough case .bne_l: fallthrough case .blt_l: fallthrough case .ble_l: fallthrough case .bgt_l: fallthrough case .bge_l: return XGASM.nop.codeAtOffset(offset) } } static func loadImmediateShifted32bit(register: XGRegisters, value: UInt32, moveToRegister: XGRegisters? = nil) -> (XGASM, XGASM) { if register == .r0 { printg("Warning: Using loadImmediateShifted32bit with register 0 leads to unexpected results") } let endRegister = moveToRegister ?? register let lowOrder = value & 0xFFFF let addition = lowOrder < 0x8000 let highOrder = value >> 16 + (addition ? 0 : 1) let shift = XGASM.lis(register, highOrder.int) var add = XGASM.nop if addition { add = .addi(endRegister, register, lowOrder.int) } else { add = .subi(endRegister, register, 0x10000 - lowOrder.int) } return (shift, add) } static func mod(_ targetRegister: XGRegisters, _ valueRegister: XGRegisters, _ divisorRegister: XGRegisters) -> ASM { guard targetRegister != divisorRegister else { printg("Couldn't create assembly for mod operation. Target register is the same as divisor register.") return [] } guard targetRegister != valueRegister else { printg("Couldn't create assembly for mod operation. Target register is the same as value register.") return [] } return [ .divw(targetRegister, valueRegister, divisorRegister), .mullw(targetRegister, targetRegister, divisorRegister), .sub(targetRegister, valueRegister, targetRegister) ] } }
gpl-2.0
bf640f1f4c9ee0a73b6ff66e20097d0c
27.639175
133
0.62707
2.659646
false
false
false
false
coach-plus/ios
Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift
6
2206
// // UIBarButtonItem+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxSwift private var rx_tap_key: UInt8 = 0 extension Reactive where Base: UIBarButtonItem { /// Bindable sink for `enabled` property. public var isEnabled: Binder<Bool> { return Binder(self.base) { element, value in element.isEnabled = value } } /// Bindable sink for `title` property. public var title: Binder<String> { return Binder(self.base) { element, value in element.title = value } } /// Reactive wrapper for target action pattern on `self`. public var tap: ControlEvent<()> { let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in Observable.create { [weak control = self.base] observer in guard let control = control else { observer.on(.completed) return Disposables.create() } let target = BarButtonItemTarget(barButtonItem: control) { observer.on(.next(())) } return target } .takeUntil(self.deallocated) .share() } return ControlEvent(events: source) } } @objc final class BarButtonItemTarget: RxTarget { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) } override func dispose() { super.dispose() #if DEBUG MainScheduler.ensureRunningOnMainThread() #endif barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } @objc func action(_ sender: AnyObject) { callback() } } #endif
mit
675e8ad8a05398a5b34652a87ce57871
24.344828
82
0.575057
4.835526
false
false
false
false
squallml/weiboSwift
weiboSwift/weiboSwift/Classes/Home/HomeViewController.swift
1
1613
// // HomeViewController.swift // weiboSwift // // Created by 胡锦龙 on 16/9/6. // Copyright © 2016年 魔龙. All rights reserved. // import UIKit class HomeViewController: BaseViewController { // MARK:- 懒加载属性 private lazy var titleBtn:TitleButton = TitleButton() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() visitorView.addRotationAnim() // 没有登录时返回 if !isLogin{ return } // 设置导航栏内容 setupNavigationBar() } } // MARK:- 设置UI界面 extension HomeViewController{ private func setupNavigationBar(){ // 左Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention") // 右Item navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop") // 设置 titleView navigationItem.titleView = titleBtn titleBtn.setTitle("胡锦龙", forState: .Normal) titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside) } } // MARK:- 事件监听的函数 extension HomeViewController{ @objc private func titleBtnClick(titleBtn:UIButton){ titleBtn.selected = !titleBtn.selected // 创建弹出View let popoverVc = PopoverViewController() popoverVc.modalPresentationStyle = .Custom presentViewController(popoverVc, animated: true, completion: nil) } }
apache-2.0
0416dcfd031a51c4332c1c4c780959f2
23.688525
123
0.636786
5.087838
false
false
false
false