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
CoderYLiu/30DaysOfSwift
Project 16 - SlideMenu/SlideMenu/MenuTableViewController.swift
1
1891
// // MenuTableViewController.swift // SlideMenu <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/22. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit class MenuTableViewController: UITableViewController { var menuItems = ["Everyday Moments", "Popular", "Editors", "Upcoming", "Fresh", "Stock-photos", "Trending"] var currentItem = "Everyday Moments" override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none self.view.backgroundColor = UIColor(red:0.109, green:0.114, blue:0.128, alpha:1) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MenuTableViewCell cell.titleLabel.text = menuItems[indexPath.row] cell.titleLabel.textColor = (menuItems[indexPath.row] == currentItem) ? UIColor.white : UIColor.gray cell.backgroundColor = UIColor.clear return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let menuTableViewController = segue.source as! MenuTableViewController if let selectedRow = menuTableViewController.tableView.indexPathForSelectedRow?.row { currentItem = menuItems[selectedRow] } } }
mit
8cc002db4ceb9a1ae88f0dce3d571bc9
33.962963
111
0.681674
5.075269
false
false
false
false
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Apple/BFKit/BFBiometrics.swift
1
7758
// // BFBiometrics.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import LocalAuthentication // MARK: - BFBiometrics struct /// This struct adds some useful functions to use biometric authentications. public enum BFBiometrics { // MARK: - Variables /// Biometric result enum. public enum Result: String { /// Success. case success /// Authentication Failed. case authenticationFailed /// User Cancel. case userCancel /// User Fallback. case userFallback /// System Cancel. case systemCancel /// Passcode Not Set. case passcodeNotSet /// Biometric Not Available. case notAvailable /// Biometric Not Enrolled. case notEnrolled /// Biometric Lockout. case lockout /// App Cancel. case appCancel /// Invalid Context. case invalidContext /// Not Interactive. case notInteractive /// Error. case error } // MARK: - Functions /// Returns if the Biometrics authentication can be used. /// /// - Returns: Returns an error code as Result enum. public static func canUseBiometric() -> Result { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { return .success } else { return handleError(error) } } /// Shows the Biometrics authentication. /// /// - Parameters: /// - reason: Text to show in the alert. /// - fallbackTitle: Default title "Enter Password" is used when this property is left nil. If set to empty string, the button will be hidden. /// - completion: Completion handler. /// - result: Returns the Biometrics result, from the Result enum. public static func useBiometric(localizedReason: String, fallbackTitle: String? = nil, completion: @escaping (_ result: Result) -> Void) { let context = LAContext() context.localizedFallbackTitle = fallbackTitle let canUseBiometric = self.canUseBiometric() if canUseBiometric == .success { context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: localizedReason) { success, error in if success == true, error == nil { completion(.success) } else { completion(handleError(error as NSError?)) } } } else { completion(canUseBiometric) } } /// Handles the Biometrics errors. /// /// - Parameter error: Error. /// - Returns: Returns the error as Result enum. private static func handleError(_ error: NSError?) -> BFBiometrics.Result { guard let error = error else { return .error } return handleErrorOS8(error) } /// Handles the Biometrics errors for iOS 11 or below. /// /// - Parameter error: Error. /// - Returns: Returns the error as Result enum. @available(iOS 11.0, *) private static func handleErrorOS11(_ error: NSError) -> Result { switch error { case LAError.authenticationFailed: return .authenticationFailed case LAError.userCancel: return .userCancel case LAError.userFallback: return .userFallback case LAError.systemCancel: return .systemCancel case LAError.passcodeNotSet: return .passcodeNotSet case LAError.biometryNotAvailable: return .notAvailable case LAError.biometryNotEnrolled: return .notEnrolled case LAError.biometryLockout: return .lockout case LAError.appCancel: return .appCancel case LAError.invalidContext: return .invalidContext case LAError.notInteractive: return .notInteractive default: return .error } } /// Handles the Biometrics errors for iOS 9 or below. /// /// - Parameter error: Error. /// - Returns: Returns the error as Result enum. @available(iOS 9.0, *) private static func handleErrorOS9(_ error: NSError) -> Result { if #available(iOS 11.0, *) { return handleErrorOS11(error) } else { switch error { case LAError.authenticationFailed: return .authenticationFailed case LAError.userCancel: return .userCancel case LAError.userFallback: return .userFallback case LAError.systemCancel: return .systemCancel case LAError.passcodeNotSet: return .passcodeNotSet case LAError.touchIDNotAvailable: return .notAvailable case LAError.touchIDNotEnrolled: return .notEnrolled case LAError.touchIDLockout: return .lockout case LAError.appCancel: return .appCancel case LAError.invalidContext: return .invalidContext case LAError.notInteractive: return .notInteractive default: return .error } } } /// Handles the Biometrics errors for iOS 8 or below. /// /// - Parameter error: Error. /// - Returns: Returns the error as Result enum. @available(iOS 8.0, *) private static func handleErrorOS8(_ error: NSError) -> Result { if #available(iOS 9.0, *) { return handleErrorOS9(error) } else { switch error { case LAError.authenticationFailed: return .authenticationFailed case LAError.userCancel: return .userCancel case LAError.userFallback: return .userFallback case LAError.systemCancel: return .systemCancel case LAError.passcodeNotSet: return .passcodeNotSet case LAError.touchIDNotAvailable: return .notAvailable case LAError.touchIDNotEnrolled: return .notEnrolled case LAError.notInteractive: return .notInteractive default: return .error } } } }
mit
691d13ef6ef74d5ea50bef1ce569f6d7
29.664032
148
0.594225
5.266802
false
false
false
false
jonatascb/Calculadora
Calculadora/CalculatorBrain.swift
1
7400
// // CalculatorGraphViewController.swift // Calculadora // // Created by Computação Gráfica 2 on 21/05/15. // Copyright (c) 2015 DCC UFRJ. All rights reserved. // import Foundation class CalculatorBrain { var elementos = Array<Elemento>() var variaveis = Dictionary<String, Double>() var description: String { get { var elementosRestantes = elementos var (descricao, novosElementos, _) = descrever(elementosRestantes) while (novosElementos.count > 0) { var (proximaDescricao, proximosElementos, _) = descrever(novosElementos) descricao = proximaDescricao + ", " + descricao novosElementos = proximosElementos } return descricao } } private var operacoes = Dictionary<String, Elemento>() var program: AnyObject { get { return elementos.map { $0.description } } set { if let simbolos = newValue as? Array<String> { var newElementos = [Elemento]() for simbolo in simbolos { if let operador = operacoes[simbolo] { newElementos.append(operador) } else if let operando = NSNumberFormatter().numberFromString(simbolo)?.doubleValue { newElementos.append(.Operando(operando)) } else { newElementos.append(.Variavel(simbolo)) } } elementos = newElementos } } } init() { operacoes["×"] = Elemento.OperacaoBinaria("×", 2, { $0 * $1 }) operacoes["÷"] = Elemento.OperacaoBinaria("÷", 2, { $1 / $0 }) operacoes["+"] = Elemento.OperacaoBinaria("+", 1, { $0 + $1 }) operacoes["−"] = Elemento.OperacaoBinaria("−", 1, { $1 - $0 }) operacoes["√"] = Elemento.OperacaoUnaria("√", sqrt) operacoes["SEN"] = Elemento.OperacaoUnaria("SEN", sin) operacoes["COS"] = Elemento.OperacaoUnaria("COS", cos) operacoes["π"] = Elemento.Constante("π", { M_PI }) } private func descrever(elementos: Array<Elemento>) -> (resultado: String, elementosRestantes: Array<Elemento>, precedencia: Int) { if !elementos.isEmpty { var elementosRestantes = elementos let elemento = elementosRestantes.removeLast() switch elemento { case Elemento.Operando(let operando): return (operando.description, elementosRestantes, elemento.precedencia) case Elemento.Variavel(let variavel): return (variavel, elementosRestantes, elemento.precedencia) case Elemento.Constante(let constante, _): return (constante, elementosRestantes, elemento.precedencia) case Elemento.OperacaoUnaria(let operacao, _): let (resto, elementosRestantes, _) = descrever(elementosRestantes) return (operacao + "(" + resto + ")", elementosRestantes, elemento.precedencia) case Elemento.OperacaoBinaria(let operacao, let precedencia, _): var (resto1, elementosRestantes1, precedencia1) = descrever(elementosRestantes) var (resto2, elementosRestantes2, precedencia2) = descrever(elementosRestantes1) if(precedencia > precedencia1) { resto1 = "(" + resto1 + ")" } if(precedencia > precedencia2) { resto2 = "(" + resto2 + ")" } return (resto2 + operacao + resto1, elementosRestantes2, precedencia) } } return ("?", elementos, Int.max) } func avaliar(elementos: Array<Elemento>) -> (resultado: Double?, elementosRestantes: Array<Elemento>) { if !elementos.isEmpty { var elementosRestantes = elementos let elemento = elementosRestantes.removeLast() switch elemento { case Elemento.Operando(let operando): return (operando, elementosRestantes) case Elemento.Variavel(let variavel): if let valorVariavel = variaveis[variavel] { return (valorVariavel, elementosRestantes) } return (nil, elementosRestantes) case Elemento.Constante(_, let operacao): return (operacao(), elementosRestantes) case Elemento.OperacaoUnaria(_, let operacao): let avaliacaoOperando = avaliar(elementosRestantes) if let operando = avaliacaoOperando.resultado { return (operacao(operando), avaliacaoOperando.elementosRestantes) } case Elemento.OperacaoBinaria(_, _, let operacao): let avaliacaoOperando1 = avaliar(elementosRestantes) if let operando1 = avaliacaoOperando1.resultado { let avaliacaoOperando2 = avaliar(avaliacaoOperando1.elementosRestantes) if let operando2 = avaliacaoOperando2.resultado { return (operacao(operando1, operando2), avaliacaoOperando2.elementosRestantes) } } default: return (nil, []) } } return (nil, elementos) } func avaliar() -> Double? { let (resultado, elementosRestantes) = avaliar(elementos) println("\(elementos) = \(resultado) com \(elementosRestantes) restando.") return resultado } func inserirOperando(operando: Double) -> Double? { elementos.append(Elemento.Operando(operando)) return avaliar() } func inserirOperando(simbolo: String) -> Double? { elementos.append(Elemento.Variavel(simbolo)) return avaliar() } func executarOperacao(simbolo: String) -> Double? { if let operacao = operacoes[simbolo] { elementos.append(operacao) } return avaliar() } }
mit
751625b7efeb0e9348c61b31ef51537f
33.344186
132
0.470405
4.663929
false
false
false
false
acastano/swift-bootstrap
persistencekit/Sources/Classes/Common/CoreData/Local+Helpers.swift
1
5790
import CoreData import Foundation public extension Local { //MARK: - Queries class func firstWithPredicate<T: NSFetchRequestResult>(_ predicate:NSPredicate?, sort:NSSortDescriptor?, entity:String, context:NSManagedObjectContext) -> T? { var object: T? let sorts: [NSSortDescriptor]? = sort != nil ? [sort!] : nil if let results: [T] = resultsWithPredicate(predicate, sorts:sorts, entity:entity, context:context) , results.count > 0 { object = results[0] } return object } class func resultsWithPredicate<T: NSFetchRequestResult>(_ predicate:NSPredicate?, sorts:[NSSortDescriptor]?, entity:String, context:NSManagedObjectContext) -> [T]? { let fetchRequest = NSFetchRequest<T>(entityName:entity) fetchRequest.predicate = predicate if let sorts = sorts { fetchRequest.sortDescriptors = sorts } let results: [T]? do { results = try context.fetch(fetchRequest) } catch { results = nil } return results } class func resultsWithPredicate(_ predicate:NSPredicate?, propertiesToFetch:[String], resultType:NSFetchRequestResultType, sort:NSSortDescriptor?, entity:String, context:NSManagedObjectContext) -> [Any]? { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:entity) fetchRequest.predicate = predicate fetchRequest.resultType = resultType fetchRequest.returnsDistinctResults = true fetchRequest.propertiesToFetch = propertiesToFetch if sort != nil { fetchRequest.sortDescriptors = [sort!] } let results: [Any]? do { results = try context.fetch(fetchRequest) } catch { results = nil } return results } class func fetchedResultsController<T: NSFetchRequestResult>(_ predicate:NSPredicate?, sorts:[NSSortDescriptor]?, fetchLimit:Int?, entity:String, section:String?) -> NSFetchedResultsController<T> { let fetchRequest = NSFetchRequest<T>(entityName:entity) fetchRequest.fetchBatchSize = 20 if fetchLimit != nil { fetchRequest.fetchLimit = fetchLimit! } if predicate != nil { fetchRequest.predicate = predicate } if let sorts = sorts { fetchRequest.sortDescriptors = sorts } let context = mainContext() let fetchedResultsController = NSFetchedResultsController(fetchRequest:fetchRequest, managedObjectContext:context, sectionNameKeyPath:section, cacheName:nil) return fetchedResultsController } //MARK: Save class func saveMainContext() { let context = mainContext() saveContext(context) } class func saveContext(_ context:NSManagedObjectContext) { if context.hasChanges { context.performAndWait { do { try context.save() } catch {} self.saveParentContext(context) } } } private class func saveParentContext(_ context:NSManagedObjectContext) { if let parentContext = context.parent, parentContext.hasChanges { parentContext.perform { do { try parentContext.save() } catch {} } } } //MARK: - Delete class func deleteAll<T:NSFetchRequestResult>(entity:T.Type) where T: NSObject { let context = mainContext() deleteAll(entity: entity, predicate:nil, context:context) } class func deleteAll<T:NSFetchRequestResult>(entity:T.Type, predicate:NSPredicate?) where T: NSObject { let context = mainContext() deleteAll(entity: entity, predicate:predicate, context:context) } class func deleteAll<T:NSFetchRequestResult>(entity:T.Type, predicate:NSPredicate?, context:NSManagedObjectContext) where T: NSObject { if let results: [T] = resultsWithPredicate(predicate, sorts:nil, entity:entity.className(), context:context) { for object in results { delete(object, context:context) } } } class func delete(_ object:NSFetchRequestResult, context:NSManagedObjectContext) { if let object = object as? NSManagedObject { context.delete(object) } } class func concurrentContext() -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType:.privateQueueConcurrencyType) context.parent = mainContext() context.undoManager = nil return context } }
apache-2.0
5907cec2e17fd75b07ec29602383f020
24.964126
209
0.512263
6.835891
false
false
false
false
data-licious/ceddl4swift
ceddl4swift/Example/HealthCareInsuranceExample.swift
1
5871
// // HealthCareInsuranceExample.swift // ceddl4swift // // Created by Sachin Vas on 23/10/16. // Copyright © 2016 Sachin Vas. All rights reserved. // import Foundation /// Generates the healthcare inurance example from the CEDDL specification on /// page 31. This example extends CEDDL with 3 new Object (Member, Application and /// Plan). /// /// We create a new class HealthcareDigitalData which extends DigitalData. /// HealthcareDigitalData adds Objects for (Member, Application and Plan) based on CustomObject. /// public class HealthCareInsuranceExample { public func healthcareInsuranceExample() { // As another example, to collect data in the healthcare insurance industry, it might be more // convenient to model a few entirely new objects to capture relevant information. // One such bespoke object could be digitalData.member, used to capture a member’ s // account details with the institution, which may frequently be insurance related. This could // include sub-objects as detailed below: // // Example Member object // digitalData.member[n] = { // memberID: "2723 49202388 01", // age: "41", // groupRelationship: "436378", // groupName: "Employer\, Inc.", // relation: "Spouse", // gender: "M", // originalJoinDate: "2011-01-21", // postalCode: "15214" // } let member: CustomObject = (((((((CustomObject() .custom("memberID", value: "2723 49202388 01" as AnyObject) as! CustomObject) .custom("age", value: "41" as AnyObject) as! CustomObject) .custom("groupRelationship", value: "436378" as AnyObject) as! CustomObject) .custom("groupName", value: "Employer, Inc." as AnyObject) as! CustomObject) .custom("relation", value: "Spouse" as AnyObject) as! CustomObject) .custom("gender", value: "M" as AnyObject) as! CustomObject) .custom("originalJoinDate", value: "2011-01-21" as AnyObject) as! CustomObject) .custom("postalCode", value: "15214" as AnyObject) as! CustomObject // Other useful objects may include an Application object and a Plan object, with additional subobjects // under each. // Example Application object // // digitalData.application = { // appID: "7565-2373-0086-8937", // source: "Telephone", // status: "Pending", // creationDate: new Date("December 15, 2013 14:20:02"), // completionDate: new Date("December 15, 2013 16:05:16") // } // Setup the dates. let creationDate = getCreationDate() let completeDate = completionDate() let application: CustomObject = ((((CustomObject() .custom("appID", value: "7565-2373-0086-8937" as AnyObject) as! CustomObject) .custom("source", value: "Telephone" as AnyObject) as! CustomObject) .custom("status", value: "Pending" as AnyObject) as! CustomObject) .custom("creationDate", value: creationDate as AnyObject) as! CustomObject) .custom("completionDate", value: completeDate as AnyObject) as! CustomObject // Example Plan object // // digitalData.plan = { // name: "Family Advantage 250", // type: "EPO", // policyStatus: "Current", // premium: 454.25, // effectiveDate: new Date("December 15, 2013 16:05:16") // } let effectiveDate = completionDate() let plan: CustomObject = ((((CustomObject() .custom("name", value: "Family Advantage 250" as AnyObject) as! CustomObject) .custom("type", value: "EPO" as AnyObject) as! CustomObject) .custom("policyStatus", value: "Current" as AnyObject) as! CustomObject) .custom("premium", value: 454.25 as AnyObject) as! CustomObject) .custom("effectiveDate", value: effectiveDate as AnyObject) as! CustomObject let healthCareDigitalData = HealthCareDigitalData() .addMember(member) .setApplication(application) .setPlan(plan) // Add an existing object _ = healthCareDigitalData.pageInstanceId("MyHomePage-Production") do { let healthCareDigitalData = healthCareDigitalData.getMap() if let json = try Utility.loadJSONFromFile(type(of: self), name: "healthcare-example") as? Dictionary<String, AnyObject> { assert(healthCareDigitalData == json, "Digital Data is not equal to contents of file") } else { assert(false, "Unable to generate dictionary from file") } } catch let error { print(error) } } private func completionDate() -> Date { let calendar = Calendar(identifier: .gregorian) var dateComponents = DateComponents() dateComponents.year = 2013 dateComponents.month = 11 dateComponents.day = 15 dateComponents.hour = 16 dateComponents.minute = 05 dateComponents.second = 16 return calendar.date(from: dateComponents)! } private func getCreationDate() -> Date { let calendar = Calendar(identifier: .gregorian) var dateComponents = DateComponents() dateComponents.year = 2013 dateComponents.month = 11 dateComponents.day = 15 dateComponents.hour = 14 dateComponents.minute = 20 dateComponents.second = 02 return calendar.date(from: dateComponents)! } }
bsd-3-clause
7bec8330af483158b2dcec70ce4d3a27
41.832117
134
0.595262
4.624113
false
false
false
false
dduan/swift
test/SourceKit/CodeFormat/indent-switch.swift
9
4710
func foo() { var test : Int = 1 switch (test) { case 0: println("It's zero") case 1: println("It's one") println("Really, it's one") default: println("It's something else") } } func foo2() { var test : Int = 1 switch (test) { case 0: println("It's zero") case 1: println("It's one") println("Really, it's one") default: println("It's something else") } } func foo3() { var test : Int = 1 switch (test) { // case 0 case 0: println("It's zero") // case 1 case 1: println("It's one") println("Really, it's one") // default default: println("It's something else") } } // RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >%t.response // RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=9 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=10 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=11 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=16 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=17 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=18 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=19 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=20 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=21 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=22 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=23 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=24 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=25 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=30 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=31 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=32 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=33 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=34 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=35 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=36 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=37 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=38 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=39 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=40 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=41 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=42 -length=1 %s >>%t.response // RUN: FileCheck --strict-whitespace %s <%t.response // CHECK: key.sourcetext: " switch (test) {" // CHECK: key.sourcetext: " case 0:" // CHECK: key.sourcetext: " println(\"It's zero\")" // CHECK: key.sourcetext: " case 1:" // CHECK: key.sourcetext: " println(\"It's one\")" // CHECK: key.sourcetext: " println(\"Really, it's one\")" // CHECK: key.sourcetext: " default:" // CHECK: key.sourcetext: " println(\"It's something else\")" // CHECK: key.sourcetext: " }" // CHECK: key.sourcetext: " switch (test)" // CHECK: key.sourcetext: " {" // CHECK: key.sourcetext: " case 0:" // CHECK: key.sourcetext: " println(\"It's zero\")" // CHECK: key.sourcetext: " case 1:" // CHECK: key.sourcetext: " println(\"It's one\")" // CHECK: key.sourcetext: " println(\"Really, it's one\")" // CHECK: key.sourcetext: " default:" // CHECK: key.sourcetext: " println(\"It's something else\")" // CHECK: key.sourcetext: " }" // CHECK: key.sourcetext: " switch (test)" // CHECK: key.sourcetext: " {" // CHECK: key.sourcetext: " // case 0" // CHECK: key.sourcetext: " case 0:" // CHECK: key.sourcetext: " println(\"It's zero\")" // CHECK: key.sourcetext: " // case 1" // CHECK: key.sourcetext: " case 1:" // CHECK: key.sourcetext: " println(\"It's one\")" // CHECK: key.sourcetext: " println(\"Really, it's one\")" // CHECK: key.sourcetext: " // default" // CHECK: key.sourcetext: " default:" // CHECK: key.sourcetext: " println(\"It's something else\")" // CHECK: key.sourcetext: " }"
apache-2.0
b378185c186874686b5f019e1750546e
40.315789
72
0.603185
3.082461
false
true
false
false
antitypical/TesseractCore
TesseractCore/Dictionary+HigherOrder.swift
1
1778
// Copyright (c) 2015 Rob Rix. All rights reserved. extension Dictionary { init<S: SequenceType where S.Generator.Element == Element>(_ elements: S) { self.init() var generator = elements.generate() let next: () -> Element? = { generator.next() } for (key, value) in GeneratorOf(next) { updateValue(value, forKey: key) } } func filter(includeKeyAndValue: Element -> Bool) -> Dictionary { return Dictionary(lazy(self).filter(includeKeyAndValue)) } func map<K: Hashable, V>(transform: Element -> (K, V)) -> Dictionary<K, V> { return Dictionary<K, V>(lazy(self).map(transform)) } func flatMap<K: Hashable, V, S: SequenceType where S.Generator.Element == Dictionary<K, V>.Element>(transform: Element -> S) -> Dictionary<K, V> { return reduce(Dictionary<K, V>(minimumCapacity: count)) { $0 + transform($1) } } func reduce<Into>(initial: Into, combine: (Into, Element) -> Into) -> Into { return Swift.reduce(self, initial, combine) } subscript (keys: Set<Key>) -> Dictionary { var result: Dictionary = [:] for key in keys { if let value = self[key] { result.updateValue(value, forKey: key) } } return result } } public func + <Key: Hashable, Value, S: SequenceType where S.Generator.Element == Dictionary<Key, Value>.Element> (var left: Dictionary<Key, Value>, right: S) -> Dictionary<Key, Value> { var generator = right.generate() let next: () -> (Key, Value)? = { generator.next() } for (key, value) in GeneratorOf(next) { left.updateValue(value, forKey: key) } return left } func + <Key: Hashable, Value: Hashable> (var left: Dictionary<Key, Set<Value>>, right: (Key, Value)) -> Dictionary<Key, Set<Value>> { let set: Set<Value> = [right.1] left[right.0] = left[right.0]?.union(set) ?? set return left }
mit
70e577325115d161bef1aa8b168113a6
30.192982
186
0.663667
3.16934
false
false
false
false
indragiek/CocoaMarkdown
Example-Mac/AppDelegate.swift
1
4055
// // AppDelegate.swift // Example-Mac // // Created by Indragie on 1/15/15. // Copyright (c) 2015 Indragie Karunaratne. All rights reserved. // import Cocoa import CocoaMarkdown @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet var textView: NSTextView! @IBOutlet weak var openPanelAUxiliaryView: NSView! @IBOutlet weak var linksBaseUrlTextField: NSTextField! func applicationDidFinishLaunching(_ notification: Notification) { if let testFileUrl = Bundle.main.url(forResource:"test", withExtension: "md") { renderMarkdownFile(atUrl: testFileUrl) } } @IBAction func selectMarkdownFile(_ sender: Any) { let panel = NSOpenPanel() panel.allowedFileTypes = ["md", "markdown"] panel.allowsMultipleSelection = false panel.prompt = "Render" panel.accessoryView = openPanelAUxiliaryView if #available(OSX 10.11, *) { panel.isAccessoryViewDisclosed = true } panel.beginSheetModal(for: window, completionHandler: { (response) in if response == .OK { if let selectedFileUrl = panel.url { var linksBaseUrl: URL? = nil if self.linksBaseUrlTextField.stringValue.count > 0 { linksBaseUrl = URL(string: self.linksBaseUrlTextField.stringValue) } self.renderMarkdownFile(atUrl: selectedFileUrl, withLinksBaseUrl: linksBaseUrl) } } }) } func renderMarkdownFile(atUrl url: URL, withLinksBaseUrl linksBaseUrl: URL? = nil) { let document = CMDocument(contentsOfFile: url.path, options: CMDocumentOptions(rawValue: 0)) if linksBaseUrl != nil { document?.linksBaseURL = linksBaseUrl } let textAttributes = CMTextAttributes() // Customize the color and font of header elements textAttributes.addStringAttributes([ .foregroundColor: NSColor(red: 0.0, green: 0.446, blue: 0.657, alpha: 1.0)], forElementWithKinds: .anyHeader) if #available(OSX 10.11, *) { textAttributes.addFontAttributes([ .family: "Avenir Next" , .traits: [ NSFontDescriptor.TraitKey.symbolic: NSFontDescriptor.SymbolicTraits.italic.rawValue, NSFontDescriptor.TraitKey.weight: NSFont.Weight.semibold]], forElementWithKinds: .anyHeader) // Set specific font traits for header1 and header2 textAttributes.setFontTraits([.weight: NSFont.Weight.heavy], forElementWithKinds: [.header1, .header2]) } textAttributes.addFontAttributes([ .size: 48 ], forElementWithKinds: .header1) // Customize the font and paragraph alignment of block-quotes textAttributes.addFontAttributes([.family: "Snell Roundhand", .size: 19], forElementWithKinds: .blockQuote) textAttributes.addParagraphStyleAttributes([ .alignment: NSTextAlignment.center.rawValue], forElementWithKinds: .blockQuote) // Customize the background color of code elements textAttributes.addStringAttributes([ .backgroundColor: NSColor(white: 0.9, alpha: 0.5)], forElementWithKinds: [.inlineCode, .codeBlock]) let renderer = CMAttributedStringRenderer(document: document, attributes: textAttributes)! renderer.register(CMHTMLStrikethroughTransformer()) renderer.register(CMHTMLSuperscriptTransformer()) renderer.register(CMHTMLUnderlineTransformer()) if let renderedAttributedString = renderer.render(), let textStorage = textView.textStorage { textStorage.replaceCharacters(in: NSRange(location: 0, length: textStorage.length), with: renderedAttributedString) } } }
mit
7ad68d777860af0d03825400121cbad4
44.561798
154
0.633785
5.165605
false
false
false
false
russbishop/swift
test/Interpreter/SDK/archiving_generic_swift_class.swift
1
6744
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=tvos // UNSUPPORTED: OS=watchos import Foundation final class Foo<T: NSCoding>: NSObject, NSCoding { var one, two: T init(one: T, two: T) { self.one = one self.two = two } @objc required convenience init(coder: NSCoder) { let one = coder.decodeObject(forKey: "one") as! T let two = coder.decodeObject(forKey :"two") as! T self.init(one: one, two: two) } @objc(encodeWithCoder:) func encode(with encoder: NSCoder) { encoder.encode(one, forKey: "one") encoder.encode(two, forKey: "two") } } // FIXME: W* macro equivalents should be in the Darwin/Glibc overlay func WIFEXITED(_ status: Int32) -> Bool { return (status & 0o177) == 0 } func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xFF } // FIXME: "environ" should be in the Darwin overlay too @_silgen_name("_NSGetEnviron") func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>> var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _NSGetEnviron().pointee } func driver() { // Create a pipe to connect the archiver to the unarchiver. var pipes: [Int32] = [0, 0] guard pipe(&pipes) == 0 else { fatalError("pipe failed") } let pipeRead = pipes[0], pipeWrite = pipes[1] var archiver: pid_t = 0, unarchiver: pid_t = 0 let envp = environ do { // Set up the archiver's stdout to feed into our pipe. var archiverActions: posix_spawn_file_actions_t? = nil guard posix_spawn_file_actions_init(&archiverActions) == 0 else { fatalError("posix_spawn_file_actions_init failed") } defer { posix_spawn_file_actions_destroy(&archiverActions) } guard posix_spawn_file_actions_adddup2(&archiverActions, pipeWrite, STDOUT_FILENO) == 0 && posix_spawn_file_actions_addclose(&archiverActions, pipeRead) == 0 else { fatalError("posix_spawn_file_actions_add failed") } // Spawn the archiver process. let archiverArgv: [UnsafeMutablePointer<Int8>?] = [ Process.unsafeArgv[0], UnsafeMutablePointer(("-archive" as StaticString).utf8Start), nil ] guard posix_spawn(&archiver, Process.unsafeArgv[0], &archiverActions, nil, archiverArgv, envp) == 0 else { fatalError("posix_spawn failed") } } do { // Set up the unarchiver's stdin to read from our pipe. var unarchiverActions: posix_spawn_file_actions_t? = nil guard posix_spawn_file_actions_init(&unarchiverActions) == 0 else { fatalError("posix_spawn_file_actions_init failed") } defer { posix_spawn_file_actions_destroy(&unarchiverActions) } guard posix_spawn_file_actions_adddup2(&unarchiverActions, pipeRead, STDIN_FILENO) == 0 && posix_spawn_file_actions_addclose(&unarchiverActions, pipeWrite) == 0 else { fatalError("posix_spawn_file_actions_add failed") } // Spawn the unarchiver process. var unarchiver: pid_t = 0 let unarchiverArgv: [UnsafeMutablePointer<Int8>?] = [ Process.unsafeArgv[0], UnsafeMutablePointer(("-unarchive" as StaticString).utf8Start), nil ] guard posix_spawn(&unarchiver, Process.unsafeArgv[0], &unarchiverActions, nil, unarchiverArgv, envp) == 0 else { fatalError("posix_spawn failed") } } // Wash our hands of the pipe, now that the subprocesses have started. close(pipeRead) close(pipeWrite) // Wait for the subprocesses to finish. var waiting: Set<pid_t> = [archiver, unarchiver] while !waiting.isEmpty { var status: Int32 = 0 let pid = wait(&status) if pid == -1 { // If the error was EINTR, just wait again. if errno == EINTR { continue } // If we have no children to wait for, stop. if errno == ECHILD { break } fatalError("wait failed") } waiting.remove(pid) // Ensure the process exited successfully. guard WIFEXITED(status) && WEXITSTATUS(status) == 0 else { fatalError("subprocess exited abnormally") } } } func archive() { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(Foo<NSString>(one: "one", two: "two"), forKey: "strings") archiver.encode(Foo<NSNumber>(one: 1, two: 2), forKey: "numbers") archiver.finishEncoding() // Output the archived data over stdout, which should be piped to stdin // on the unarchiver process. while true { let status = write(STDOUT_FILENO, data.bytes, data.length) if status == data.length { break } if errno == EINTR { continue } fatalError("write failed") } } func unarchive() { // FIXME: Pre-instantiate the generic classes that were archived, since // the ObjC runtime doesn't know how. NSStringFromClass(Foo<NSNumber>.self) NSStringFromClass(Foo<NSString>.self) // Read in the data from stdin, where the archiver process should have // written it. var rawData: [UInt8] = [] var buffer = [UInt8](repeating: 0, count: 4096) while true { let count = read(STDIN_FILENO, &buffer, 4096) if count == 0 { break } if count == -1 { if errno == EINTR { continue } fatalError("read failed") } rawData += buffer[0..<count] } // Feed it into an unarchiver. let data = NSData(bytes: rawData, length: rawData.count) let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data) guard let strings = unarchiver.decodeObject(forKey: "strings") as? Foo<NSString> else { fatalError("unable to unarchive Foo<NSString>") } guard let numbers = unarchiver.decodeObject(forKey: "numbers") as? Foo<NSNumber> else { fatalError("unable to unarchive Foo<NSNumber>") } // CHECK-LABEL: <_TtGC4main3FooCSo8NSString_: {{0x[0-9a-f]+}}> #0 // CHECK: one: one // CHECK: two: two // CHECK-LABEL: <_TtGC4main3FooCSo8NSNumber_: {{0x[0-9a-f]+}}> #0 // CHECK: one: 1 // CHECK: two: 2 dump(strings) dump(numbers) } // Pick a mode based on the command-line arguments. // The test launches as a "driver" which then respawns itself into reader // and writer subprocesses. if Process.arguments.count < 2 { driver() } else if Process.arguments[1] == "-archive" { archive() } else if Process.arguments[1] == "-unarchive" { unarchive() } else { fatalError("invalid commandline argument") }
apache-2.0
59a054116c0a04908393936892d5e0bc
30.661972
96
0.632414
3.92093
false
false
false
false
shahen94/react-native-video-processing
ios/GPUImage/examples/iOS/FilterShowcaseSwift/FilterShowcaseSwift/FilterOperationTypes.swift
131
2527
import Foundation import GPUImage enum FilterSliderSetting { case Disabled case Enabled(minimumValue:Float, maximumValue:Float, initialValue:Float) } #if os(iOS) typealias FilterSetupFunction = (camera:GPUImageVideoCamera, outputView:GPUImageView) -> (filter:GPUImageOutput, secondOutput:GPUImageOutput?) #else typealias FilterSetupFunction = (camera:GPUImageAVCamera, outputView:GPUImageView) -> (filter:GPUImageOutput, secondOutput:GPUImageOutput?) #endif enum FilterOperationType { case SingleInput case Blend case Custom(filterSetupFunction:FilterSetupFunction) } protocol FilterOperationInterface { var filter: GPUImageOutput { get } var listName: String { get } var titleName: String { get } var sliderConfiguration: FilterSliderSetting { get } var filterOperationType: FilterOperationType { get } func configureCustomFilter(input:(filter:GPUImageOutput, secondInput:GPUImageOutput?)) func updateBasedOnSliderValue(sliderValue:CGFloat) } class FilterOperation<FilterClass: GPUImageOutput where FilterClass: GPUImageInput>: FilterOperationInterface { var internalFilter: FilterClass? var secondInput: GPUImageOutput? let listName: String let titleName: String let sliderConfiguration: FilterSliderSetting let filterOperationType: FilterOperationType let sliderUpdateCallback: ((filter:FilterClass, sliderValue:CGFloat) -> ())? init(listName: String, titleName: String, sliderConfiguration: FilterSliderSetting, sliderUpdateCallback:((filter:FilterClass, sliderValue:CGFloat) -> ())?, filterOperationType: FilterOperationType) { self.listName = listName self.titleName = titleName self.sliderConfiguration = sliderConfiguration self.filterOperationType = filterOperationType self.sliderUpdateCallback = sliderUpdateCallback switch (filterOperationType) { case .Custom: break default: self.internalFilter = FilterClass() } } var filter: GPUImageOutput { return internalFilter! } func configureCustomFilter(input:(filter:GPUImageOutput, secondInput:GPUImageOutput?)) { self.internalFilter = (input.filter as! FilterClass) self.secondInput = input.secondInput } func updateBasedOnSliderValue(sliderValue:CGFloat) { if let updateFunction = sliderUpdateCallback { updateFunction(filter:internalFilter!, sliderValue:sliderValue) } } }
mit
bfcacfde7c6b23f34f79a89b088ec7ba
35.637681
204
0.734468
4.945205
false
true
false
false
peferron/algo
EPI/Binary Search Trees/Find the k largest elements in a BST/swift/main.swift
1
1092
public class Node { let value: Int let left: Node? let right: Node? public init(value: Int, left: Node? = nil, right: Node? = nil) { self.value = value self.left = left self.right = right } } extension Node { public func largest(count: Int) -> [Int] { var result = right?.largest(count: count) ?? [] if result.count < count { result.append(self.value) result += left?.largest(count: count - result.count) ?? [] } return result } // Iterative implementation. /* public func largest(count: Int) -> [Int] { var result = [Int]() var current: Node? = self var stack = [Node]() while result.count < count { if let c = current { stack.append(c) current = c.right } else if let last = stack.popLast() { result.append(last.value) current = last.left } else { break } } return result } */ }
mit
80eb8921aedf8ff07ae7c50622e8fe1f
22.234043
70
0.480769
4.216216
false
false
false
false
gregomni/swift
test/Sema/availability_versions.swift
2
67560
// RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module // RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -typecheck %s 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0' // Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed // RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -typecheck -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | %FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:' // REQUIRES: OS=macosx func markUsed<T>(_ t: T) {} @available(OSX, introduced: 10.9) func globalFuncAvailableOn10_9() -> Int { return 9 } @available(OSX, introduced: 10.51) func globalFuncAvailableOn10_51() -> Int { return 10 } @available(OSX, introduced: 10.52) func globalFuncAvailableOn10_52() -> Int { return 11 } // Top level should reflect the minimum deployment target. let ignored1: Int = globalFuncAvailableOn10_9() let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Functions without annotations should reflect the minimum deployment target. func functionWithoutAvailability() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Functions with annotations should refine their bodies. @available(OSX, introduced: 10.51) func functionAvailableOn10_51() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // Nested functions should get their own refinement context. @available(OSX, introduced: 10.52) func innerFunctionAvailableOn10_52() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() } let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Don't allow script-mode globals to marked potentially unavailable. Their // initializers are eagerly executed. @available(OSX, introduced: 10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}} var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51() // Still allow other availability annotations on script-mode globals @available(OSX, deprecated: 10.51) var deprecatedGlobalInScriptMode: Int = 5 if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } else { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) @available(iOS, introduced: 8.0) func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 } if #available(OSX 10.51, iOS 8.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() } if #available(iOS 9.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Multiple unavailable references in a single statement let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 2{{add 'if #available' version check}} _ = globalFuncAvailableOn10_9() let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Overloaded global functions @available(OSX, introduced: 10.9) func overloadedFunction() {} @available(OSX, introduced: 10.51) func overloadedFunction(_ on1010: Int) {} overloadedFunction() overloadedFunction(0) // expected-error {{'overloadedFunction' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Unavailable methods class ClassWithUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) func methAvailableOn10_9() {} @available(OSX, introduced: 10.51) func methAvailableOn10_51() {} @available(OSX, introduced: 10.51) class func classMethAvailableOn10_51() {} func someOtherMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } func callUnavailableMethods(_ o: ClassWithUnavailableMethod) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callUnavailableMethodsViaIUO(_ o: ClassWithUnavailableMethod!) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callUnavailableClassMethod() { // expected-note@-1 2{{add @available attribute to enclosing global function}} ClassWithUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_51 = ClassWithUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } class SubClassWithUnavailableMethod : ClassWithUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} func someMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class SubClassOverridingUnavailableMethod : ClassWithUnavailableMethod { // expected-note@-1 2{{add @available attribute to enclosing class}} override func methAvailableOn10_51() { // expected-note@-1 2{{add @available attribute to enclosing instance method}} methAvailableOn10_9() super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_9 = super.methAvailableOn10_9 m10_9() let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } func someMethod() { methAvailableOn10_9() // Calling our override should be fine methAvailableOn10_51() } } class ClassWithUnavailableOverloadedMethod { @available(OSX, introduced: 10.9) func overloadedMethod() {} @available(OSX, introduced: 10.51) func overloadedMethod(_ on1010: Int) {} } func callUnavailableOverloadedMethod(_ o: ClassWithUnavailableOverloadedMethod) { // expected-note@-1 {{add @available attribute to enclosing global function}} o.overloadedMethod() o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Initializers class ClassWithUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) required init() { } @available(OSX, introduced: 10.51) required init(_ val: Int) { } convenience init(s: String) { // expected-note@-1 {{add @available attribute to enclosing initializer}} self.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) convenience init(onlyOn1010: String) { self.init(5) } } func callUnavailableInitializer() { // expected-note@-1 2{{add @available attribute to enclosing global function}} _ = ClassWithUnavailableInitializer() _ = ClassWithUnavailableInitializer(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let i = ClassWithUnavailableInitializer.self _ = i.init() _ = i.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class SuperWithWithUnavailableInitializer { @available(OSX, introduced: 10.9) init() { } @available(OSX, introduced: 10.51) init(_ val: Int) { } } class SubOfClassWithUnavailableInitializer : SuperWithWithUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} override init(_ val: Int) { // expected-note@-1 {{add @available attribute to enclosing initializer}} super.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } override init() { super.init() } @available(OSX, introduced: 10.51) init(on1010: Int) { super.init(22) } } // Properties class ClassWithUnavailableProperties { // expected-note@-1 4{{add @available attribute to enclosing class}} var nonLazyAvailableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} var nonLazyAvailableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} let nonLazyLetAvailableOn10_51Stored : Int = 10 // Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable. // We don't support potentially unavailable stored properties yet. var storedPropertyOfUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} @available(OSX, introduced: 10.9) lazy var availableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} lazy var availableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.9) var availableOn10_9Computed: Int { get { let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: Int = availableOn10_51Stored } return availableOn10_9Stored } set(newVal) { availableOn10_9Stored = newVal } } @available(OSX, introduced: 10.51) var availableOn10_51Computed: Int { get { return availableOn10_51Stored } set(newVal) { availableOn10_51Stored = newVal } } var propWithSetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} get { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return 0 } @available(OSX, introduced: 10.51) set(newVal) { _ = globalFuncAvailableOn10_51() } } var propWithGetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} @available(OSX, introduced: 10.51) get { _ = globalFuncAvailableOn10_51() return 0 } set(newVal) { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } var propWithGetterAndSetterOnlyAvailableOn10_51 : Int { @available(OSX, introduced: 10.51) get { return 0 } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties { get { return ClassWithUnavailableProperties() } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties { @available(OSX, introduced: 10.51) get { return ClassWithUnavailableProperties() } set(newVal) { } } } @available(OSX, introduced: 10.51) class ClassWithReferencesInInitializers { var propWithInitializer10_51: Int = globalFuncAvailableOn10_51() var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51() lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} } func accessUnavailableProperties(_ o: ClassWithUnavailableProperties) { // expected-note@-1 17{{add @available attribute to enclosing global function}} // Stored properties let _: Int = o.availableOn10_9Stored let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Stored = 9 o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Computed Properties let _: Int = o.availableOn10_9Computed let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Computed = 9 o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Getter allowed on 10.9 but setter is not let _: Int = o.propWithSetterOnlyAvailableOn10_51 o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Setter is allowed on 10.51 and greater o.propWithSetterOnlyAvailableOn10_51 = 5 } // Setter allowed on 10.9 but getter is not o.propWithGetterOnlyAvailableOn10_51 = 5 let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Getter is allowed on 10.51 and greater let _: Int = o.propWithGetterOnlyAvailableOn10_51 } // Tests for nested member refs // Both getters are potentially unavailable. let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} // Nested getter is potentially unavailable, outer getter is available let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Nested getter is available, outer getter is potentially unavailable let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Both getters are always available. let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // Nesting in source of assignment var v: Int v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = v // muffle warning // Inout requires access to both getter and setter func takesInout(_ i : inout Int) { } takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} takesInout(&o.availableOn10_9Computed) takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // _silgen_name @_silgen_name("SomeName") @available(OSX, introduced: 10.51) func funcWith_silgen_nameAvailableOn10_51(_ p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51 // Enums @available(OSX, introduced: 10.51) enum EnumIntroducedOn10_51 { case Element } @available(OSX, introduced: 10.52) enum EnumIntroducedOn10_52 { case Element } @available(OSX, introduced: 10.51) enum CompassPoint { case North case South case East @available(OSX, introduced: 10.52) case West case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51) // expected-error@+1 {{enum cases with associated values cannot be marked potentially unavailable with '@available'}} @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52) // expected-error@+1 2{{enum cases with associated values cannot be marked potentially unavailable with '@available'}} @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52) case WithUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} case WithUnavailablePayload1(p : EnumIntroducedOn10_52), WithUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} } @available(OSX, introduced: 10.52) func functionTakingEnumIntroducedOn10_52(_ e: EnumIntroducedOn10_52) { } func useEnums() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: CompassPoint = .North let _: CompassPoint = .West // expected-error {{'West' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.52, *) { let _: CompassPoint = .West } // Pattern matching on an enum element does not require it to be definitely available if #available(OSX 10.51, *) { let point: CompassPoint = .North switch (point) { case .North, .South, .East: markUsed("NSE") case .West: // We do not expect an error here markUsed("W") case .WithUnavailablePayload(_): markUsed("WithUnavailablePayload") case .WithUnavailablePayload1(_): markUsed("WithUnavailablePayload1") case .WithUnavailablePayload2(_): markUsed("WithUnavailablePayload2") case .WithAvailableByEnumPayload(_): markUsed("WithAvailableByEnumPayload") case .WithAvailableByEnumElementPayload1(_): markUsed("WithAvailableByEnumElementPayload1") case .WithAvailableByEnumElementPayload2(_): markUsed("WithAvailableByEnumElementPayload2") case .WithAvailableByEnumElementPayload(let p): markUsed("WithAvailableByEnumElementPayload") // For the moment, we do not incorporate enum element availability into // TRC construction. Perhaps we should? functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} } } } // Classes @available(OSX, introduced: 10.9) class ClassAvailableOn10_9 { func someMethod() {} class func someClassMethod() {} var someProp : Int = 22 } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51 { // expected-note {{enclosing scope here}} func someMethod() {} class func someClassMethod() { let _ = ClassAvailableOn10_51() } var someProp : Int = 22 @available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}} func someMethodAvailableOn10_9() { } @available(OSX, introduced: 10.52) var propWithGetter: Int { // expected-note{{enclosing scope here}} @available(OSX, introduced: 10.51) // expected-error {{declaration cannot be more available than enclosing scope}} get { return 0 } } } func classAvailability() { // expected-note@-1 3{{add @available attribute to enclosing global function}} ClassAvailableOn10_9.someClassMethod() ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = ClassAvailableOn10_9.self _ = ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let o10_9 = ClassAvailableOn10_9() let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o10_9.someMethod() o10_51.someMethod() let _ = o10_9.someProp let _ = o10_51.someProp } func castingUnavailableClass(_ o : AnyObject) { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } protocol Creatable { init() } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51_Creatable : Creatable { required init() {} } func create<T : Creatable>() -> T { return T() } class ClassWithGenericTypeParameter<T> { } class ClassWithTwoGenericTypeParameter<T, S> { } func classViaTypeParameter() { // expected-note@-1 9{{add @available attribute to enclosing global function}} let _ : ClassAvailableOn10_51_Creatable = // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} create() let _ = create() as ClassAvailableOn10_51_Creatable // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Unavailable class used in declarations class ClassWithDeclarationsOfUnavailableClasses { // expected-note@-1 5{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.51) init() {} var propertyOfUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} @available(OSX, introduced: 10.51) static var unavailableStaticPropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51() @available(OSX, introduced: 10.51) static var unavailableStaticPropertyOfOptionalUnavailableType: ClassAvailableOn10_51? func methodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableParameterType(_ o : ClassAvailableOn10_51) { } func methodWithUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add @available attribute to enclosing instance method}} return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableReturnType() -> ClassAvailableOn10_51 { return ClassAvailableOn10_51() } func methodWithUnavailableLocalDeclaration() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) func unavailableMethodWithUnavailableLocalDeclaration() { let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() } } func referToUnavailableStaticProperty() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithDeclarationsOfUnavailableClasses.unavailableStaticPropertyOfUnavailableType // expected-error {{'unavailableStaticPropertyOfUnavailableType' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class ClassExtendingUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing class}} } @available(OSX, introduced: 10.51) class UnavailableClassExtendingUnavailableClass : ClassAvailableOn10_51 { } // Method availability is contravariant class SuperWithAlwaysAvailableMembers { func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}} } var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}} get { return 9 } set(newVal) {} } var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } set(newVal) {} // expected-note {{overridden declaration is here}} } var getterShouldAlwaysBeAvailableProperty: Int { get { return 9 } // expected-note {{overridden declaration is here}} set(newVal) {} } } class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers { @available(OSX, introduced: 10.51) override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}} } @available(OSX, introduced: 10.51) override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} get { return 10 } set(newVal) {} } override var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } @available(OSX, introduced: 10.51) set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} // This is a terrible diagnostic. rdar://problem/20427938 } override var getterShouldAlwaysBeAvailableProperty: Int { @available(OSX, introduced: 10.51) get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} set(newVal) {} } } class SuperWithLimitedMemberAvailability { @available(OSX, introduced: 10.51) func someMethod() { } @available(OSX, introduced: 10.51) var someProperty: Int { get { return 10 } set(newVal) {} } } class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability { // expected-note@-1 2{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) override func someMethod() { super.someMethod() // expected-error {{'someMethod()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { super.someMethod() } } @available(OSX, introduced: 10.9) override var someProperty: Int { get { let _ = super.someProperty // expected-error {{'someProperty' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _ = super.someProperty } return 9 } set(newVal) {} } } // Inheritance and availability @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_9 { } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.9) protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } // We allow nominal types to conform to protocols that are less available than the types themselves. @available(OSX, introduced: 10.9) class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { } func castToUnavailableProtocol() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51() let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } class SomeGenericClass<T> { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} } func GenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } func GenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } struct GenericType<T> { // expected-note {{add @available attribute to enclosing generic struct}} func nonGenericWhereClause() where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} struct NestedType where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add @available attribute to enclosing struct}} } // Extensions extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing extension}} @available(OSX, introduced: 10.51) extension ClassAvailableOn10_51 { func m() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class ClassToExtend { } @available(OSX, introduced: 10.51) extension ClassToExtend { func extensionMethod() { } @available(OSX, introduced: 10.52) func extensionMethod10_52() { } class ExtensionClass { } // We rely on not allowing nesting of extensions, so test to make sure // this emits an error. // CHECK:error: declaration is only valid at file scope extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}} } // We allow protocol extensions for protocols that are less available than the // conforming class. extension ClassToExtend : ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.51) extension ClassToExtend { // expected-note {{enclosing scope here}} @available(OSX, introduced: 10.9) // expected-error {{declaration cannot be more available than enclosing scope}} func extensionMethod10_9() { } } func useUnavailableExtension() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let o = ClassToExtend() o.extensionMethod() // expected-error {{'extensionMethod()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Availability of synthesized designated initializers. @available(OSX, introduced: 10.51) class WidelyAvailableBase { init() {} @available(OSX, introduced: 10.52) init(thing: ()) {} } @available(OSX, introduced: 10.53) class EsotericSmallBatchHipsterThing : WidelyAvailableBase {} @available(OSX, introduced: 10.53) class NestedClassTest { class InnerClass : WidelyAvailableBase {} } // Useless #available(...) checks func functionWithDefaultAvailabilityAndUselessCheck(_ p: Bool) { // Default availability reflects minimum deployment: 10.9 and up if #available(OSX 10.9, *) { // no-warning let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}} } else { // Make sure we generate a warning about an unnecessary check even if the else branch of if is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } // This 'if' is strictly to limit the scope of the guard fallthrough if p { guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}} // Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } } // We don't want * generate a warn about useless checks; the check may be required on // another platform if #available(iOS 8.0, *) { } if #available(OSX 10.51, *) { // Similarly do not want '*' to generate a warning in a refined TRC. if #available(iOS 8.0, *) { } } } @available(OSX, unavailable) func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}} func functionWithUnavailableInDeadBranch() { if #available(iOS 8.0, *) { } else { // This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it. _ = globalFuncAvailableOn10_51() // no-warning @available(OSX 10.51, *) func localFuncAvailableOn10_51() { _ = globalFuncAvailableOn10_52() // no-warning } localFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } guard #available(iOS 8.0, *) else { _ = globalFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } } @available(OSX, introduced: 10.51) func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}} if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } // #available(...) outside if statement guards func injectToOptional<T>(_ v: T) -> T? { return v } if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok // Refining context inside guard if #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}} let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } // Tests for the guard control construct. func useGuardAvailable() { // expected-note@-1 3{{add @available attribute to enclosing global function}} // Guard fallthrough should refine context guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return } let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } if globalFuncAvailableOn10_51() > 0 { guard #available(OSX 10.52, *), let x = injectToOptional(globalFuncAvailableOn10_52()) else { return } _ = x } let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func twoGuardsInSameBlock(_ p: Int) { // expected-note@-1 {{add @available attribute to enclosing global function}} if (p > 0) { guard #available(OSX 10.51, *) else { return } let _ = globalFuncAvailableOn10_51() guard #available(OSX 10.52, *) else { return } let _ = globalFuncAvailableOn10_52() } let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Refining while loops while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} while #available(OSX 10.51, *), // expected-note {{enclosing scope here}} globalFuncAvailableOn10_51() > 10 { let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} while globalFuncAvailableOn10_51() > 11, let _ = injectToOptional(5), #available(OSX 10.52, *) { let _ = globalFuncAvailableOn10_52(); } while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } // Tests for Fix-It replacement text // The whitespace in the replacement text is particularly important here -- it reflects the level // of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard // code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we // take whatever indentation was there before and add 4 spaces to it). functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}} let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(macOS 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}} func fixitForReferenceInGlobalFunction() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } public func fixitForReferenceInGlobalFunctionWithDeclModifier() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceInGlobalFunctionWithAttribute() -> Never { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} _ = 0 // Avoid treating the call to functionAvailableOn10_51 as an implicit return functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func takesAutoclosure(_ c : @autoclosure () -> ()) { } class ClassForFixit { // expected-note@-1 12{{add @available attribute to enclosing class}} {{1-1=@available(macOS 10.51, *)\n}} func fixitForReferenceInMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceNestedInMethod() { // expected-note@-1 3{{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} func inner() { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } let _: () -> () = { () in functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } takesAutoclosure(functionAvailableOn10_51()) // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(macOS 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}} } var fixitForReferenceInPropertyAccessor: Int { // expected-note@-1 {{add @available attribute to enclosing property}} {{3-3=@available(macOS 10.51, *)\n }} get { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} return 5 } } var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing static property}} {{3-3=@available(macOS 10.51, *)\n }} var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7 // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} func fixitForRefInGuardOfIf() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} if (globalFuncAvailableOn10_51() > 1066) { let _ = 5 let _ = 6 } // expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(macOS 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}} } } extension ClassToExtend { // expected-note@-1 {{add @available attribute to enclosing extension}} func fixitForReferenceInExtensionMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } } enum EnumForFixit { // expected-note@-1 2{{add @available attribute to enclosing enum}} {{1-1=@available(macOS 10.51, *)\n}} case CaseWithUnavailablePayload(p: ClassAvailableOn10_51) // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} case CaseWithUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } @objc class Y { var z = 0 } @objc class X { @objc var y = Y() } func testForFixitWithNestedMemberRefExpr() { // expected-note@-1 2{{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.52, *)\n}} let x = X() x.y.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(macOS 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} // Access via dynamic member reference let anyX: AnyObject = x anyX.y?.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(macOS 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} } // Protocol Conformances protocol ProtocolWithRequirementMentioningUnavailable { // expected-note@-1 2{{add @available attribute to enclosing protocol}} func hasUnavailableParameter(_ p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} func hasUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} @available(OSX 10.51, *) func hasUnavailableWithAnnotation(_ p: ClassAvailableOn10_51) -> ClassAvailableOn10_51 } protocol HasMethodF { associatedtype T func f(_ p: T) // expected-note 3{{protocol requirement here}} } class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} } class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF { // Even though this function is less available than its requirement, // it is available on a deployment targets, so the conformance is safe. @available(OSX, introduced: 10.9) func f(_ p: Int) { } } class SuperHasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-note {{'f' declared here}} } class TriesToConformWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} // The conformance here is generating an error on f in the super class. } @available(OSX, introduced: 10.51) class ConformsWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Limiting this class to only be available on 10.51 and newer means that // the witness in SuperHasMethodF is safe for the requirement on HasMethodF. // in order for this class to be referenced we must be running on 10.51 or // greater. } class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Now the witness is this f() (which is always available) and not the f() // from the super class, so conformance is safe. override func f(_ p: Int) { } } // Attempt to conform in protocol extension with unavailable witness // in extension class HasNoMethodF1 { } extension HasNoMethodF1 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} } class HasNoMethodF2 { } @available(OSX, introduced: 10.51) extension HasNoMethodF2 : HasMethodF { // This is OK, because the conformance was introduced by an extension. func f(_ p: Int) { } } @available(OSX, introduced: 10.51) class HasNoMethodF3 { } @available(OSX, introduced: 10.51) extension HasNoMethodF3 : HasMethodF { // We expect this conformance to succeed because on every version where HasNoMethodF3 // is available, HasNoMethodF3's f() is as available as the protocol requirement func f(_ p: Int) { } } @available(OSX, introduced: 10.51) protocol HasMethodFOn10_51 { func f(_ p: Int) } class ConformsToUnavailableProtocolWithUnavailableWitness : HasMethodFOn10_51 { @available(OSX, introduced: 10.51) func f(_ p: Int) { } } @available(OSX, introduced: 10.51) class HasNoMethodF4 { } @available(OSX, introduced: 10.52) extension HasNoMethodF4 : HasMethodFOn10_51 { // This is OK, because the conformance was introduced by an extension. func f(_ p: Int) { } } @available(OSX, introduced: 10.51) protocol HasTakesClassAvailableOn10_51 { func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}} } class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}} } } class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } class TakesClassAvailableOn10_51_A { } extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}} } } class TakesClassAvailableOn10_51_B { } extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } // We want conditional availability to play a role in picking a witness for a // protocol requirement. class TestAvailabilityAffectsWitnessCandidacy : HasMethodF { // Test that we choose the less specialized witness, because the more specialized // witness is conditionally unavailable. @available(OSX, introduced: 10.51) func f(_ p: Int) { } func f<T>(_ p: T) { } } protocol HasUnavailableMethodF { @available(OSX, introduced: 10.51) func f(_ p: String) } class ConformsWithUnavailableFunction : HasUnavailableMethodF { @available(OSX, introduced: 10.9) func f(_ p: String) { } } func useUnavailableProtocolMethod(_ h: HasUnavailableMethodF) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func useUnavailableProtocolMethod<H : HasUnavailableMethodF> (_ h: H) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Short-form @available() annotations @available(OSX 10.51, *) class ClassWithShortFormAvailableOn10_51 { } @available(OSX 10.53, *) class ClassWithShortFormAvailableOn10_53 { } @available(OSX 10.54, *) class ClassWithShortFormAvailableOn10_54 { } @available(OSX 10.9, *) func funcWithShortFormAvailableOn10_9() { let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX 10.51, *) func funcWithShortFormAvailableOn10_51() { let _ = ClassWithShortFormAvailableOn10_51() } @available(iOS 14.0, *) func funcWithShortFormAvailableOniOS14() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(iOS 14.0, OSX 10.53, *) func funcWithShortFormAvailableOniOS14AndOSX10_53() { let _ = ClassWithShortFormAvailableOn10_51() } // Not idiomatic but we need to be able to handle it. @available(iOS 8.0, *) @available(OSX 10.51, *) func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() { let _ = ClassWithShortFormAvailableOn10_51() } @available(OSX 10.51, *) @available(OSX 10.53, *) @available(OSX 10.52, *) func funcWithMultipleShortFormAnnotationsForTheSamePlatform() { let _ = ClassWithShortFormAvailableOn10_53() let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available in macOS 10.54 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX 10.9, *) @available(OSX, unavailable) func unavailableWins() { } // expected-note {{'unavailableWins()' has been explicitly marked unavailable here}} func useShortFormAvailable() { // expected-note@-1 4{{add @available attribute to enclosing global function}} funcWithShortFormAvailableOn10_9() funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithShortFormAvailableOniOS14() funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available in macOS 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available in macOS 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} unavailableWins() // expected-error {{'unavailableWins()' is unavailable}} }
apache-2.0
81499c6d52f00e829e84e26e6fa7a791
41.251407
357
0.707948
3.807055
false
false
false
false
hejunbinlan/Operations
examples/Permissions/Pods/YapDatabaseExtensions/framework/YapDatabaseExtensions/Common/Read.swift
1
32836
// // Created by Daniel Thorpe on 22/04/2015. // // import YapDatabase // MARK: - YapDatabaseTransaction extension YapDatabaseReadTransaction { /** Reads the object sored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional AnyObject. */ public func readAtIndex(index: YapDB.Index) -> AnyObject? { return objectForKey(index.key, inCollection: index.collection) } /** Reads the object sored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional Object. */ public func readAtIndex<Object where Object: Persistable>(index: YapDB.Index) -> Object? { return readAtIndex(index) as? Object } /** Unarchives a value type if stored at this index :param: index The YapDB.Index value. :returns: An optional Value. */ public func readAtIndex< Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(index: YapDB.Index) -> Value? { return Value.ArchiverType.unarchive(readAtIndex(index)) } } extension YapDatabaseReadTransaction { /** Reads any metadata sored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional AnyObject. */ public func readMetadataAtIndex(index: YapDB.Index) -> AnyObject? { return metadataForKey(index.key, inCollection: index.collection) } /** Reads metadata which is an object type sored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional MetadataObject. */ public func readMetadataAtIndex< MetadataObject where MetadataObject: NSCoding>(index: YapDB.Index) -> MetadataObject? { return readMetadataAtIndex(index) as? MetadataObject } /** Unarchives metadata which is a value type if stored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional MetadataValue. */ public func readMetadataAtIndex< MetadataValue where MetadataValue: Saveable, MetadataValue.ArchiverType: NSCoding, MetadataValue.ArchiverType.ValueType == MetadataValue>(index: YapDB.Index) -> MetadataValue? { return MetadataValue.ArchiverType.unarchive(readMetadataAtIndex(index)) } } extension YapDatabaseReadTransaction { /** Reads the objects sored at these indexes using the transaction. :param: indexes An array of YapDB.Index values. :returns: An array of Object instances. */ public func readAtIndexes< Object where Object: Persistable>(indexes: [YapDB.Index]) -> [Object] { return indexes.unique().flatMap { self.readAtIndex($0) } } /** Reads the values sored at these indexes using the transaction. :param: indexes An array of YapDB.Index values. :returns: An array of Value instances. */ public func readAtIndexes< Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(indexes: [YapDB.Index]) -> [Value] { return indexes.unique().flatMap { self.readAtIndex($0) } } } extension YapDatabaseReadTransaction { /** Reads the Object sored by key in this transaction. :param: key A String :returns: An optional Object */ public func read< Object where Object: Persistable>(key: String) -> Object? { return objectForKey(key, inCollection: Object.collection) as? Object } /** Reads the Value sored by key in this transaction. :param: key A String :returns: An optional Value */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(key: String) -> Value? { return Value.ArchiverType.unarchive(objectForKey(key, inCollection: Value.collection)) } } extension YapDatabaseReadTransaction { /** Reads the objects at the given keys in this transaction. Keys which have no corresponding objects will be filtered out. :param: keys An array of String instances :returns: An array of Object types. */ public func read< Object where Object: Persistable>(keys: [String]) -> [Object] { return keys.unique().flatMap { self.read($0) } } /** Reads the values at the given keys in this transaction. Keys which have no corresponding values will be filtered out. :param: keys An array of String instances :returns: An array of Value types. */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String]) -> [Value] { return keys.unique().flatMap { self.read($0) } } } extension YapDatabaseReadTransaction { /** Reads all the items in the database for a particular Persistable Object. Example usage: let people: [Person] = transaction.readAll() :returns: An array of Object types. */ public func readAll<Object where Object: Persistable>() -> [Object] { return (allKeysInCollection(Object.collection) as! [String]).flatMap { self.read($0) } } /** Reads all the items in the database for a particular Persistable Value. Example usage: let barcodes: [Barcode] = transaction.readAll() :returns: An array of Value types. */ public func readAll< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>() -> [Value] { return (allKeysInCollection(Value.collection) as! [String]).flatMap { self.read($0) } } } extension YapDatabaseReadTransaction { /** Returns an array of Object type for the given keys, with an array of keys which don't have corresponding objects in the database. let (people: [Person], missing) = transaction.filterExisting(keys) :param: keys An array of String instances :returns: An ([Object], [String]) tuple. */ public func filterExisting<Object where Object: Persistable>(keys: [String]) -> ([Object], [String]) { let existing: [Object] = read(keys) let existingKeys = existing.map { indexForPersistable($0).key } let missingKeys = keys.filter { !existingKeys.contains($0) } return (existing, missingKeys) } /** Returns an array of Value type for the given keys, with an array of keys which don't have corresponding values in the database. let (barcode: [Barcode], missing) = transaction.filterExisting(keys) :param: keys An array of String instances :returns: An ([Value], [String]) tuple. */ public func filterExisting< Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(keys: [String]) -> ([Value], [String]) { let existing: [Value] = read(keys) let existingKeys = existing.map { indexForPersistable($0).key } let missingKeys = keys.filter { !existingKeys.contains($0) } return (existing, missingKeys) } } // MARK: - YapDatabaseConnection extension YapDatabaseConnection { /** Synchronously reads the object sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional AnyObject. */ public func readAtIndex(index: YapDB.Index) -> AnyObject? { return read({ $0.readAtIndex(index) }) } /** Synchronously reads the Object sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional Object. */ public func readAtIndex<Object where Object: Persistable>(index: YapDB.Index) -> Object? { return read({ $0.readAtIndex(index) }) } /** Synchronously reads the Value sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional Value. */ public func readAtIndex< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(index: YapDB.Index) -> Value? { return read({ $0.readAtIndex(index) }) } } extension YapDatabaseConnection { /** Asynchronously reads the Object sored at this index using the connection. :param: index The YapDB.Index value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Object */ public func asyncReadAtIndex<Object where Object: Persistable>(index: YapDB.Index, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object?) -> Void) { asyncRead({ $0.readAtIndex(index) }, queue: queue, completion: completion) } /** Asynchronously reads the Value sored at this index using the connection. :param: index The YapDB.Index value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Value */ public func asyncReadAtIndex< Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(index: YapDB.Index, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value?) -> Void) { asyncRead({ $0.readAtIndex(index) }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchronously reads the metadata sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional AnyObject. */ public func readMetadataAtIndex(index: YapDB.Index) -> AnyObject? { return read { $0.readMetadataAtIndex(index) } } /** Synchronously reads the object metadata sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional MetadataObject. */ public func readMetadataAtIndex< MetadataObject where MetadataObject: NSCoding>(index: YapDB.Index) -> MetadataObject? { return read { $0.readMetadataAtIndex(index) as? MetadataObject } } /** Synchronously metadata which is a value type if stored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional MetadataValue. */ public func readMetadataAtIndex< MetadataValue where MetadataValue: Saveable, MetadataValue.ArchiverType: NSCoding, MetadataValue.ArchiverType.ValueType == MetadataValue>(index: YapDB.Index) -> MetadataValue? { return read { $0.readMetadataAtIndex(index) } } } extension YapDatabaseConnection { /** Synchronously reads the objects sored at these indexes using the connection. :param: indexes An array of YapDB.Index values. :returns: An array of Object instances. */ public func readAtIndexes<Object where Object: Persistable>(indexes: [YapDB.Index]) -> [Object] { return read({ $0.readAtIndexes(indexes) }) } /** Synchronously reads the values sored at these indexes using the connection. :param: indexes An array of YapDB.Index values. :returns: An array of Value instances. */ public func readAtIndexes< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(indexes: [YapDB.Index]) -> [Value] { return read({ $0.readAtIndexes(indexes) }) } } extension YapDatabaseConnection { /** Asynchronously reads the objects sored at these indexes using the connection. :param: indexes An array of YapDB.Index values. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances */ public func asyncReadAtIndexes<Object where Object: Persistable>(indexes: [YapDB.Index], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { asyncRead({ $0.readAtIndexes(indexes) }, queue: queue, completion: completion) } /** Asynchronously reads the values sored at these indexes using the connection. :param: indexes An array of YapDB.Index values. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances */ public func asyncReadAtIndexes< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(indexes: [YapDB.Index], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { asyncRead({ $0.readAtIndexes(indexes) }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchronously reads the Object sored by key in this connection. :param: key A String :returns: An optional Object */ public func read<Object where Object: Persistable>(key: String) -> Object? { return read({ $0.read(key) }) } /** Synchronously reads the Value sored by key in this connection. :param: key A String :returns: An optional Value */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(key: String) -> Value? { return read({ $0.read(key) }) } } extension YapDatabaseConnection { /** Asynchronously reads the Object sored by key in this connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Object */ public func asyncRead<Object where Object: Persistable>(key: String, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object?) -> Void) { asyncRead({ $0.read(key) }, queue: queue, completion: completion) } /** Asynchronously reads the Value sored by key in this connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Value */ public func asyncRead< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(key: String, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value?) -> Void) { asyncRead({ $0.read(key) }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchronously reads the Object instances sored by the keys in this connection. :param: keys An array of String instances :returns: An array of Object instances */ public func read<Object where Object: Persistable>(keys: [String]) -> [Object] { return read({ $0.read(keys) }) } /** Synchronously reads the Value instances sored by the keys in this connection. :param: keys An array of String instances :returns: An array of Value instances */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String]) -> [Value] { return read({ $0.read(keys) }) } } extension YapDatabaseConnection { /** Asynchronously reads the Object instances sored by the keys in this connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances */ public func asyncRead<Object where Object: Persistable>(keys: [String], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { asyncRead({ $0.read(keys) }, queue: queue, completion: completion) } /** Asynchronously reads the Value instances sored by the keys in this connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances */ public func asyncRead< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { asyncRead({ $0.read(keys) }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchronously reads all the items in the database for a particular Persistable Object. Example usage: let people: [Person] = connection.readAll() :returns: An array of Object types. */ public func readAll<Object where Object: Persistable>() -> [Object] { return read({ $0.readAll() }) } /** Synchronously reads all the items in the database for a particular Persistable Value. Example usage: let barcodes: [Barcode] = connection.readAll() :returns: An array of Value types. */ public func readAll< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>() -> [Value] { return read({ $0.readAll() }) } } extension YapDatabaseConnection { /** Asynchronously reads all the items in the database for a particular Persistable Object. Example usage: connection.readAll() { (people: [Person] in } :returns: An array of Object types. */ public func asyncReadAll<Object where Object: Persistable>(queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { asyncRead({ $0.readAll() }, queue: queue, completion: completion) } /** Asynchronously reads all the items in the database for a particular Persistable Value. Example usage: connection.readAll() { (barcodes: [Barcode] in } :returns: An array of Value types. */ public func asyncReadAll< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { asyncRead({ $0.readAll() }, queue: queue, completion: completion) } } extension YapDatabaseConnection { /** Synchronously returns an array of Object type for the given keys, with an array of keys which don't have corresponding objects in the database. let (people: [Person], missing) = connection.filterExisting(keys) :param: keys An array of String instances :returns: An ([Object], [String]) tuple. */ public func filterExisting<Object where Object: Persistable>(keys: [String]) -> (existing: [Object], missing: [String]) { return read({ $0.filterExisting(keys) }) } /** Synchronously returns an array of Value type for the given keys, with an array of keys which don't have corresponding values in the database. let (barcode: [Barcode], missing) = connection.filterExisting(keys) :param: keys An array of String instances :returns: An ([Value], [String]) tuple. */ public func filterExisting< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String]) -> (existing: [Value], missing: [String]) { return read({ $0.filterExisting(keys) }) } } // MARK: - YapDatabase extension YapDatabase { /** Synchronously reads the Object sored at this index using a new connection. :param: index The YapDB.Index value. :returns: An optional Object. */ public func readAtIndex<Object where Object: Persistable>(index: YapDB.Index) -> Object? { return newConnection().readAtIndex(index) } /** Synchronously reads the Value sored at this index using a new connection. :param: index The YapDB.Index value. :returns: An optional Value. */ public func readAtIndex< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(index: YapDB.Index) -> Value? { return newConnection().readAtIndex(index) } } extension YapDatabase { /** Asynchronously reads the Object sored at this index using a new connection. :param: index The YapDB.Index value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Object */ public func asyncReadAtIndex<Object where Object: Persistable>(index: YapDB.Index, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object?) -> Void) { newConnection().asyncReadAtIndex(index, queue: queue, completion: completion) } /** Asynchronously reads the Value sored at this index using a new connection. :param: index The YapDB.Index value. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Value */ public func asyncReadAtIndex< Value where Value: Saveable, Value: Persistable, Value.ArchiverType.ValueType == Value>(index: YapDB.Index, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value?) -> Void) { newConnection().asyncReadAtIndex(index, queue: queue, completion: completion) } } extension YapDatabase { /** Synchronously reads the object metadata sored at this index using the connection. :param: index The YapDB.Index value. :returns: An optional MetadataObject. */ public func readMetadataAtIndex< MetadataObject where MetadataObject: NSCoding>(index: YapDB.Index) -> MetadataObject? { return newConnection().readMetadataAtIndex(index) as? MetadataObject } /** Synchronously metadata which is a value type if stored at this index using the transaction. :param: index The YapDB.Index value. :returns: An optional MetadataValue. */ public func readMetadataAtIndex< MetadataValue where MetadataValue: Saveable, MetadataValue.ArchiverType: NSCoding, MetadataValue.ArchiverType.ValueType == MetadataValue>(index: YapDB.Index) -> MetadataValue? { return newConnection().readMetadataAtIndex(index) } } extension YapDatabase { /** Synchronously reads the objects sored at these indexes using a new connection. :param: indexes An array of YapDB.Index values. :returns: An array of Object instances. */ public func readAtIndexes<Object where Object: Persistable>(indexes: [YapDB.Index]) -> [Object] { return newConnection().readAtIndexes(indexes) } /** Synchronously reads the values sored at these indexes using a new connection. :param: indexes An array of YapDB.Index values. :returns: An array of Value instances. */ public func readAtIndexes< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(indexes: [YapDB.Index]) -> [Value] { return newConnection().readAtIndexes(indexes) } } extension YapDatabase { /** Asynchronously reads the objects sored at these indexes using a new connection. :param: indexes An array of YapDB.Index values. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances */ public func asyncReadAtIndexes<Object where Object: Persistable>(indexes: [YapDB.Index], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { return newConnection().asyncReadAtIndexes(indexes, queue: queue, completion: completion) } /** Asynchronously reads the values sored at these indexes using a new connection. :param: indexes An array of YapDB.Index values. :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances */ public func asyncReadAtIndexes< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(indexes: [YapDB.Index], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { return newConnection().asyncReadAtIndexes(indexes, queue: queue, completion: completion) } } extension YapDatabase { /** Synchronously reads the Object sored by key in a new connection. :param: key A String :returns: An optional Object */ public func read<Object where Object: Persistable>(key: String) -> Object? { return newConnection().read(key) } /** Synchronously reads the Value sored by key in a new connection. :param: key A String :returns: An optional Value */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(key: String) -> Value? { return newConnection().read(key) } } extension YapDatabase { /** Asynchronously reads the Object sored by key in a new connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Object */ public func asyncRead<Object where Object: Persistable>(key: String, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object?) -> Void) { newConnection().asyncRead(key, queue: queue, completion: completion) } /** Asynchronously reads the Value sored by key in a new connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an optional Value */ public func asyncRead< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(key: String, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value?) -> Void) { newConnection().asyncRead(key, queue: queue, completion: completion) } } extension YapDatabase { /** Synchronously reads the Object instances sored by the keys in a new connection. :param: keys An array of String instances :returns: An array of Object instances */ public func read< Object where Object: Persistable>(keys: [String]) -> [Object] { return newConnection().read(keys) } /** Synchronously reads the Value instances sored by the keys in a new connection. :param: keys An array of String instances :returns: An array of Value instances */ public func read< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String]) -> [Value] { return newConnection().read(keys) } } extension YapDatabase { /** Asynchronously reads the Object instances sored by the keys in a new connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Object instances */ public func asyncRead< Object where Object: Persistable>(keys: [String], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { newConnection().asyncRead(keys, queue: queue, completion: completion) } /** Asynchronously reads the Value instances sored by the keys in a new connection. :param: keys An array of String instances :param: queue A dispatch_queue_t, defaults to the main queue. :param: completion A closure which receives an array of Value instances */ public func asyncRead< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String], queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { newConnection().asyncRead(keys, queue: queue, completion: completion) } } extension YapDatabase { /** Synchronously reads all the items in the database for a particular Persistable Object in a new connection. Example usage: let people: [Person] = database.readAll() :returns: An array of Object types. */ public func readAll< Object where Object: Persistable>() -> [Object] { return newConnection().readAll() } /** Synchronously reads all the items in the database for a particular Persistable Value in a new connection. Example usage: let barcodes: [Barcode] = database.readAll() :returns: An array of Value types. */ public func readAll< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>() -> [Value] { return newConnection().readAll() } } extension YapDatabase { /** Asynchronously reads all the items in the database for a particular Persistable Object in a new connection. Example usage: database.readAll() { (people: [Person] in } :returns: An array of Object types. */ public func asyncReadAll< Object where Object: Persistable>(queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) { newConnection().asyncReadAll(queue, completion: completion) } /** Asynchronously reads all the items in the database for a particular Persistable Value in a new connection. Example usage: database.readAll() { (barcodes: [Barcode] in } :returns: An array of Object types. */ public func asyncReadAll< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) { newConnection().asyncReadAll(queue, completion: completion) } } extension YapDatabase { /** Synchronously returns an array of Object type for the given keys, with an array of keys which don't have corresponding objects in the database, using a new connection. let (people: [Person], missing) = database.filterExisting(keys) :param: keys An array of String instances :returns: An ([Object], [String]) tuple. */ public func filterExisting<Object where Object: Persistable>(keys: [String]) -> (existing: [Object], missing: [String]) { return newConnection().filterExisting(keys) } /** Synchronously returns an array of Value type for the given keys, with an array of keys which don't have corresponding values in the database, using a new connection. let (barcode: [Barcode], missing) = database.filterExisting(keys) :param: keys An array of String instances :returns: An ([Value], [String]) tuple. */ public func filterExisting< Value where Value: Saveable, Value: Persistable, Value.ArchiverType: NSCoding, Value.ArchiverType.ValueType == Value>(keys: [String]) -> (existing: [Value], missing: [String]) { return newConnection().filterExisting(keys) } }
mit
aacc1555e9bddc6582fee54c73ce6c02
30.452107
179
0.653368
4.483955
false
false
false
false
exis-io/swiftRiffleCocoapod
Pod/Classes/Deferred.swift
1
6736
// // Deferred.swift // Pods // // Created by damouse on 12/4/15. // // Homebaked, python Twisted inspired deferreds with A+ inspired syntax // These guys will chain callbacks and errbacks import Foundation import Mantle public class Deferred: Handler { // Callback and Errback ids let cb = CBID() let eb = CBID() var callbackFuntion: ([Any] -> Any?)? = nil var errbackFunction: ([Any] -> Any?)? = nil var next: Deferred? var callbackOccured: [Any]? = nil var errbackOccured: [Any]? = nil // this should not be public public init() { Session.handlers[cb] = self Session.handlers[eb] = self } func _then(fn: [Any] -> ()) -> Deferred { next = Deferred() callbackFuntion = { a in return fn(a) } if let args = callbackOccured { callbackOccured = nil callback(args) next!.callback(args) } return next! } func _error(fn: (String) -> ()) -> Deferred { next = Deferred() errbackFunction = { a in fn(a[0] as! String) } if let args = errbackOccured { errback(args) next!.errback(args) } return next! } public func callback(args: [Any]) -> Any? { callbackOccured = args print(args) if let f = callbackFuntion { if let d = f(args) as? Deferred { print("Have a deferred") } } if let n = next { n.callback(args) } return nil } public func errback(args: [Any]) -> Any? { errbackOccured = args if let handler = errbackFunction { handler(args) } if let n = next { n.errback(args) } return nil } // Session has deemed its our time to shine. Fire off this deferred func invoke(id: UInt64, args: [Any]) { if cb == id { callback(args) } else if eb == id { errback(args) } destroy() } func destroy() { Session.handlers[cb] = nil Session.handlers[eb] = nil } public func then(fn: () -> ()) -> Deferred { return _then() { a in fn() } } // public func then(fn: () -> (Deferred)) -> Deferred { // return _then() { a in fn() } // } public func error(fn: (String) -> ()) -> Deferred { return _error(fn) } } // Contains handler "then"s to replace handler functions public class HandlerDeferred: Deferred { var domain: Domain! public override func then(fn: () -> ()) -> Deferred { // this override is a special case. It overrides the base then, but cant go in the extension return _then([]) { a in return fn() } } func _then(types: [Any], _ fn: [Any] -> ()) -> Deferred { domain.callCore("CallExpects", args: [cb, types]) return _then(fn) } } // A deferred that callsback with a fixed number of arguments and types public class OneDeferred<A: PR>: Deferred { public func then(fn: (A) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0]) } } } public class TwoDeferred<A: PR, B: PR>: Deferred { public func then(fn: (A, B) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0], B.self <- a[1]) } } } public class ThreeDeferred<A: PR, B: PR, C: PR>: Deferred { public func then(fn: (A, B, C) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0], B.self <- a[1], C.self <- a[2]) } } } public class FourDeferred<A: PR, B: PR, C: PR, D: PR>: Deferred { public func then(fn: (A, B, C, D) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0], B.self <- a[1], C.self <- a[2], D.self <- a[3]) } } } public class FiveDeferred<A: PR, B: PR, C: PR, D: PR, E: PR>: Deferred { public func then(fn: (A, B, C, D, E) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0], B.self <- a[1], C.self <- a[2], D.self <- a[3], E.self <- a[4]) } } } public class SixDeferred<A: PR, B: PR, C: PR, D: PR, E: PR, F: PR>: Deferred { public func then(fn: (A, B, C, D, E, F) -> ()) -> Deferred { return _then() { a in return fn(A.self <- a[0], B.self <- a[1], C.self <- a[2], D.self <- a[3], E.self <- a[4], F.self <- a[5]) } } } // Saved old code // var callbackFuntion: ([Any] -> Any?)? = nil // var errbackFunction: ([Any] -> Any?)? = nil // // var pendingCallback: [Any]? // var pendingErrback: [Any]? // // var next: Deferred? // var root: Deferred! // func _then(fn: [Any] -> ()) -> Deferred { // next = Deferred() // callbackFuntion = { a in return fn(a) } // // if let args = pendingCallback { // pendingCallback = nil // callback(args) // next!.callback(args) // } // // return next! // } // // func _error(fn: (String) -> ()) -> Deferred { // next = Deferred() // errbackFunction = { a in fn(a[0] as! String) } // // if let args = pendingErrback { // pendingErrback = nil // errback(args) // next!.errback(args) // } // // return next! // } // // public func callback(args: [Any]) -> Any? { // // Fires off a deferred chain recursively. TODO: work in error logic, recovery, propogation, etc // var ret: Any? // // if let handler = callbackFuntion { // // if the next result is a deferred, wait for it to complete before returning (?) // ret = handler(args) // // // follow the chain // if let n = next { // if let arrayReturn = ret as? [Any] { // return n.callback(arrayReturn) // } // // return n.callback([ret]) // } else { // return ret // } // } else { // pendingCallback = args // return nil // } // } // // public func errback(args: [Any]) -> Any? { // if let handler = errbackFunction { // // if the next result is a deferred, wait for it to complete before returning (?) // let ret = handler(args) // // // follow the chain, propogate the calback to the next deferred // if let n = next { // return n.errback(args) // } else { // return ret // } // } else { // // No chain exists. TODO: Send the error to some well-known place // // Riffle.warn("Unhandled error: \(args)") // // pendingErrback = args // return nil // } // }
mit
ae2d4a9d92102522d8178863daff2fcb
26.950207
137
0.502821
3.521171
false
false
false
false
RaviDesai/RSDRestServices
Example/Tests/TestAPISite.swift
1
3191
// // TestAPISite.swift // RSDRESTServices // // Created by Ravi Desai on 10/26/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import XCTest import RSDRESTServices import RSDSerialization class TestAPISite: XCTestCase { func testInit() { let site = APISite(name: "Apple", uri: "http://www.apple.com") XCTAssertTrue(site.name == "Apple") XCTAssertTrue(site.uri == NSURL(string: "http://www.apple.com")) let site2 = APISite(name: "Apple", uri: nil) XCTAssertTrue(site2.name == "Apple") XCTAssertTrue(site2.uri == .None) } func testConvertToJSON() { let site = APISite(name: "Apple", uri: "http://www.apple.com") XCTAssertTrue(site.name == "Apple") XCTAssertTrue(site.uri == NSURL(string: "http://www.apple.com")) let json = site.convertToJSON() XCTAssertTrue(json.count == 2) XCTAssertTrue(json["Name"] as! String == "Apple") XCTAssertTrue(json["Uri"] as! String == "http://www.apple.com") } func testCreateFromJSON() { let dict = ["Name": "Apple", "Uri": "http://www.apple.com"] let jsonDict : JSONDictionary = dict let json : JSON = jsonDict let site = APISite.createFromJSON(json) XCTAssertTrue(site != nil) XCTAssertTrue(site!.name == "Apple") XCTAssertTrue(site!.uri == NSURL(string: "http://www.apple.com")) let dict2 = ["Name": "Apple"] let jsonDict2 : JSONDictionary = dict2 let json2 : JSON = jsonDict2 let site2 = APISite.createFromJSON(json2) XCTAssertTrue(site2!.name == "Apple") XCTAssertTrue(site2!.uri == nil) let dict3 = [String: String]() let jsonDict3 : JSONDictionary = dict3 let json3 : JSON = jsonDict3 let site3 = APISite.createFromJSON(json3) XCTAssertTrue(site3 == nil) let dict4 = ["Name": "Apple", "Uri": NSNumber(double: 3.14)] let jsonDict4 : JSONDictionary = dict4 let json4 : JSON = jsonDict4 let site4 = APISite.createFromJSON(json4) XCTAssertTrue(site4 != nil) XCTAssertTrue(site4!.name == "Apple") XCTAssertTrue(site4!.uri == nil) } func testLessThan() { let sites = [APISite(name: "Beta", uri: "http://www.beta.com"), APISite(name: "Alpha", uri: "http://www.alpha.com"), APISite(name: "Gamma", uri: "http://www.gamma.com")] let sortedSites = sites.sort() XCTAssertTrue(sortedSites[0].name == "Alpha") XCTAssertTrue(sortedSites[1].name == "Beta") XCTAssertTrue(sortedSites[2].name == "Gamma") } func testEquality() { var site0 = APISite(name: "Alpha", uri: nil) var site1 = APISite(name: "Alpha", uri: "http://www.alpha.com") XCTAssertFalse(site0 == site1) site1.uri = nil XCTAssertTrue(site0 == site1) site0.uri = NSURL(string: "http://alpha.com") site1.uri = NSURL(string: "http://alpha.com") XCTAssertTrue(site0 == site1) site0.name = "Beta" XCTAssertFalse(site0 == site1) } }
mit
7b32950550aecf63f8024e174639e1da
34.065934
177
0.587147
3.84801
false
true
false
false
aatalyk/swift-algorithm-club
Two-Sum Problem/Solution 2/2Sum.playground/Contents.swift
8
552
//: Playground - noun: a place where people can play func twoSumProblem(_ a: [Int], k: Int) -> ((Int, Int))? { var i = 0 var j = a.count - 1 while i < j { let sum = a[i] + a[j] if sum == k { return (i, j) } else if sum < k { i += 1 } else { j -= 1 } } return nil } let a = [2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100] if let (i, j) = twoSumProblem(a, k: 33) { i // 8 a[i] // 12 j // 10 a[j] // 21 a[i] + a[j] // 33 } twoSumProblem(a, k: 37) // nil
mit
695fc4e5decad8b0e25e2c0fcb90b886
18.034483
57
0.416667
2.53211
false
false
false
false
madoffox/Stretching
Stretching/Stretching/MoreSettingsView.swift
1
1672
// // MoreSettingsView.swift // Stretching // // Created by Admin on 16.12.16. // Copyright © 2016 Admin. All rights reserved. // import UIKit @IBDesignable class MoreSettingsView: UIView { var view: UIView! var nibName: String = "MoreSettingsView" @IBOutlet weak var restTimeSlider: UISlider! @IBOutlet weak var restTimeLabel: UILabel! @IBOutlet weak var trainingTimeSlider: UISlider! @IBOutlet weak var trainingTimeLabel: UILabel! @IBAction func trainingTimeSliderValueChanged(_ sender: UISlider) { trainingTimeLabel.text = "\(Int(trainingTimeSlider.value))" trainingDuration = UInt8(trainingTimeSlider.value) } @IBAction func restTimeSliderValueChanged() { restTimeLabel.text = "\(Int(restTimeSlider.value))" restDuration = UInt8(restTimeSlider.value) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { view = loadViewFromNib() view.frame = bounds view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] addSubview(view) } func loadViewFromNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView return view } }
mit
b15553f11b531dfcdffad5555e7721be
21.890411
101
0.594853
4.843478
false
false
false
false
david1mdavis/IOS-nRF-Toolbox
nRF Toolbox/Scanner/NORScannedPeripheral.swift
2
988
// // NORScannedPeripheral.swift // nRF Toolbox // // Created by Mostafa Berg on 28/04/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. // import UIKit import CoreBluetooth @objc class NORScannedPeripheral: NSObject { var peripheral : CBPeripheral var RSSI : Int32 var isConnected : Bool init(withPeripheral aPeripheral: CBPeripheral, andRSSI anRSSI:Int32 = 0, andIsConnected aConnectionStatus: Bool) { peripheral = aPeripheral RSSI = anRSSI isConnected = aConnectionStatus } func name()->String{ let peripheralName = peripheral.name if peripheral.name == nil { return "No name" }else{ return peripheralName! } } override func isEqual(_ object: Any?) -> Bool { if let otherPeripheral = object as? NORScannedPeripheral { return peripheral == otherPeripheral.peripheral } return false } }
bsd-3-clause
40d73757d8c5d44d99d8be19f1698676
24.307692
118
0.628166
4.65566
false
false
false
false
TMTBO/TTAMusicPlayer
TTAMusicPlayer/TTAMusicPlayer/Classes/Player/Utils/PlayerManager.swift
1
8947
// // PlayerManager.swift // MusicPlayer // // Created by ys on 16/11/22. // Copyright © 2016年 TobyoTenma. All rights reserved. // import UIKit import AVFoundation import MediaPlayer let kNONE_TIME = "00:00" let kNOW_PLAYING_MUSIC_INFO = "NowPlayingMusicInfo" let kNOW_PLAYING_MUSIC_URL = "NowPlayingMusicURL" @objc protocol PlayerManagerDelegate : NSObjectProtocol { @objc optional func playerManager(_ playerManager : PlayerManager, playingMusic : MPMediaItem) @objc optional func playerManagerUpdateProgressAndTime(_ playerManager : PlayerManager) @objc optional func playerManager(_ playerManager : PlayerManager, conrtolMusicIconAnimation isPause : Bool) } class PlayerManager: NSObject { static let shared = PlayerManager() weak var delegate : PlayerManagerDelegate? { didSet { // 这里要先将之前的一个计时器停掉,不然的切换音乐后,进入界面后不会更新进度条与播放时间 stopTimer() startTimer() controlMusicIconAnimation(with: false) } } /// 播放器 var audioPlayer : AVAudioPlayer? /// 所有音乐列表 var musics : [MPMediaItem] = [] /// 当前正在播放的音乐索引 var playingIndex : Int = 0 var timer : Timer? var currentTimeString : String { get { return getTimeString(with: audioPlayer?.currentTime) } } var durationTimeString : String { get { return getTimeString(with: audioPlayer?.duration) } } var currentTime : Float { get { return Float(self.audioPlayer?.currentTime ?? 0.0) } set { self.audioPlayer?.currentTime = TimeInterval(newValue) } } var durationTime : Float { get { return Float(self.audioPlayer?.duration ?? 0.0) } } /// 是否正在播放 var isPlaying : Bool { get { if let nowPlaying = audioPlayer?.isPlaying { return nowPlaying } else { return false } } } override init() { super.init() getMainData() useRemoteControlEvent() } override class func initialize() { try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try? AVAudioSession.sharedInstance().setActive(true) } /// 获取音乐数据 func getMainData() { let allMusic = MPMediaQuery.songs() musics = allMusic.items! } /// 根据当播放器的时间转为字符串 func getTimeString(with timeInterval : TimeInterval?) -> String { guard let currentTimeInterval = timeInterval else { return kNONE_TIME } let currentTime = String.tta_string(from: currentTimeInterval, with: "mm:ss") return currentTime ?? kNONE_TIME } } // MARK: - Play Control extension PlayerManager { /// 播放 func play(music : MPMediaItem) { guard let musicURL = music.assetURL else { return } if musicURL != audioPlayer?.url { audioPlayer = try! AVAudioPlayer(contentsOf: musicURL) audioPlayer?.delegate = self audioPlayer?.prepareToPlay() if let index = musics.index(of: music) { self.playingIndex = index } switchPlayerMusicInfo() updateLockScreen(with: 1.0) saveNowPlayingMusicInfo(with: playingIndex, url: musicURL) } controlMusicIconAnimation(with: false) audioPlayer?.play() startTimer() print("PlayMusic: \(music.title!)") } func play(musicURL : URL) { var nowPlayMusic : MPMediaItem? = MPMediaItem() if musicURL != audioPlayer?.url { audioPlayer = try! AVAudioPlayer(contentsOf: musicURL) audioPlayer?.delegate = self audioPlayer?.prepareToPlay() for (index, music) in musics.enumerated() { if let assetURL = music.assetURL, assetURL == musicURL { self.playingIndex = index nowPlayMusic = music break } } switchPlayerMusicInfo() updateLockScreen(with: 1.0) saveNowPlayingMusicInfo(with: playingIndex, url: musicURL) } controlMusicIconAnimation(with: false) audioPlayer?.play() startTimer() print("PlayMusicURL: \(musicURL), Music: \(nowPlayMusic?.title ?? "未命名歌曲")") } /// 暂停 func pause() { if let _ = audioPlayer?.isPlaying { updateLockScreen(with: 0.0) controlMusicIconAnimation(with: true) audioPlayer?.pause() stopTimer() print("PauseMusic") } } /// 下一曲 func next() { var nextIndex = playingIndex + 1 if nextIndex > musics.count - 1 { nextIndex = 0 } print("NextMusic") play(music: musics[nextIndex]) } /// 上一曲 func previous() { var nextIndex = playingIndex - 1 if nextIndex < 0 { nextIndex = musics.count - 1 } print("PreviewMusic") play(music : musics[nextIndex]) } /// 切换播放器音乐信息 func switchPlayerMusicInfo() { if let _ = self.delegate?.responds(to: #selector(self.delegate?.playerManager(_:playingMusic:))) { self.delegate?.playerManager?(self, playingMusic: musics[playingIndex]) } } /// 控制音乐图片的转动动画 func controlMusicIconAnimation(with isPause : Bool) { if let _ = delegate?.responds(to: #selector(delegate?.playerManager(_:conrtolMusicIconAnimation:))) { delegate?.playerManager?(self, conrtolMusicIconAnimation: isPause) } } } // MARK: - RemoteControl extension PlayerManager { func useRemoteControlEvent() { let center = MPRemoteCommandCenter.shared() center.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in print("RemoteControl Play") self.play(music: self.musics[self.playingIndex]) return MPRemoteCommandHandlerStatus.success } center.pauseCommand.addTarget(self, action: #selector(pause)) center.nextTrackCommand.addTarget(self, action: #selector(next)) center.previousTrackCommand.addTarget(self, action: #selector(previous)) } /// 更新锁屏界面信息 /// /// - Parameter rate: 播放速率,1.0 为正常播放, 0.0 为暂停 func updateLockScreen(with rate : Float) { let music = musics[playingIndex] MPNowPlayingInfoCenter.default().nowPlayingInfo = [MPMediaItemPropertyTitle : music.title ?? "Music", MPMediaItemPropertyAlbumTitle : music.albumTitle ?? "Playing",MPMediaItemPropertyArtist : music.artist ?? "TTAMusicPlayer",MPMediaItemPropertyPlaybackDuration : (music.playbackDuration),MPNowPlayingInfoPropertyElapsedPlaybackTime : (currentTime),MPNowPlayingInfoPropertyPlaybackRate : rate, MPMediaItemPropertyArtwork : music.artwork ?? MPMediaItemArtwork(image: #imageLiteral(resourceName: "cm2_default_cover_play"))] } } // MARK: - Timer extension PlayerManager { func startTimer() { guard timer == nil else { return } guard delegate != nil else { return } timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(updateRemoteInfoWithTimer), userInfo: nil, repeats: true) } func stopTimer() { timer?.invalidate() timer = nil } func updateRemoteInfoWithTimer() { updateLockScreen(with: 1.0) if let _ = self.delegate?.responds(to: #selector(self.delegate?.playerManagerUpdateProgressAndTime(_:))) { self.delegate?.playerManagerUpdateProgressAndTime?(self) } } } // MARK: - Save and read now playing music url in user default extension PlayerManager { func readNowPlayingMusicInfo() -> URL { if let userDefault = UserDefaults.standard.object(forKey: kNOW_PLAYING_MUSIC_INFO) as? [String : String] { guard let urlString = userDefault[kNOW_PLAYING_MUSIC_URL] else { return musics[0].assetURL!} return URL(string: urlString)! } return musics[0].assetURL! } func saveNowPlayingMusicInfo(with musicIndex : Int, url: URL) { let nowPlayingMusicInfoDic = [kNOW_PLAYING_MUSIC_URL : String(describing: url)] UserDefaults.standard.set(nowPlayingMusicInfoDic, forKey: kNOW_PLAYING_MUSIC_INFO) } } // MARK: - AVAudioPlayerDelegate extension PlayerManager : AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { next() } }
mit
3545a2ff4f0732332b5aff2135dc6190
32.061069
529
0.616139
4.667026
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Demos/TweetView demo/TweetOptionsView.swift
2
2940
// // TweetOptionsView.swift // DemoApp // // Created by Rajul Arora on 11/1/17. // Copyright © 2017 Twitter. All rights reserved. // import UIKit enum TweetOption { case style case theme case actions } class TweetOptionsView: UIView { // MARK: - Private Variables fileprivate static let cellIdenfitier = "optionCell" private lazy var tableView: UITableView = { [unowned self] in let tableView = UITableView(frame: .zero, style: .plain) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.rowHeight = 48.0 tableView.delegate = self tableView.dataSource = self tableView.isScrollEnabled = false tableView.register(TweetOptionTableViewCell.self, forCellReuseIdentifier: TweetOptionsView.cellIdenfitier) return tableView }() fileprivate var options: [TweetOption] = [.style, .theme, .actions] // MARK: - Init init() { super.init(frame: .zero) addSubview(tableView) setupTableView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Methods private func setupTableView() { tableView.topAnchor.constraint(equalTo: topAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true } // MARK: - Public Methods func tweetSettings() -> [TweetOption: Any] { var dict: [TweetOption: Any] = [:] options.forEach { dict[$0] = setting(for: $0) } return dict } private func setting(for option: TweetOption) -> Any? { guard let index = options.index(of: option) else { return nil } let indexPath = IndexPath(row: index, section: 0) if let cell = tableView.cellForRow(at: indexPath) as? TweetOptionTableViewCell { return cell.tweetSetting() } else { return nil } } } // MARK: - UITableViewDataSource extension TweetOptionsView: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: TweetOptionsView.cellIdenfitier, for: indexPath) } } // MARK: - UITableViewDelegate extension TweetOptionsView: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? TweetOptionTableViewCell { cell.selectionStyle = .none cell.configure(option: options[indexPath.row]) } } }
mit
160978cf960dea4f70ab0297aded988f
28.989796
114
0.667574
4.740323
false
false
false
false
mmrmmlrr/ModelsTreeKit
ModelsTreeKit/Classes/UIKit/TableViewAdapter.swift
1
13907
// // TableViewAdapter.swift // SessionSwift // // Created by aleksey on 18.10.15. // Copyright © 2015 aleksey chernish. All rights reserved. // import Foundation import UIKit public class TableViewAdapter<ObjectType>: NSObject, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate{ typealias DataSourceType = ObjectsDataSource<ObjectType> public var animatesReload = false public var nibNameForObjectMatching: ((ObjectType, IndexPath) -> String)! public var canEditRowAtIndexPath: ((IndexPath) -> Bool)? public var commitWithEditingStyle: ((UITableViewCellEditingStyle, IndexPath) -> Void)? public var editActionsForRowAtIndexPath: ((IndexPath) -> [UITableViewRowAction])? public var footerClassForSectionIndexMatching: ((Int) -> UITableViewHeaderFooterView.Type?) = { _ in nil } public var headerClassForSectionIndexMatching: ((Int) -> UITableViewHeaderFooterView.Type?) = { _ in nil } public var userInfoForCellHeightMatching: ((IndexPath) -> [String: AnyObject]) = { _ in return [:] } public var userInfoForSectionHeaderHeightMatching: ((Int) -> [String: AnyObject]) = { _ in return [:] } public var userInfoForSectionFooterHeightMatching: ((Int) -> [String: AnyObject]) = { _ in return [:] } public let didSelectCell = Pipe<(UITableViewCell, IndexPath, ObjectType)>() public let willDisplayCell = Pipe<(UITableViewCell, IndexPath)>() public let didEndDisplayingCell = Pipe<(UITableViewCell, IndexPath)>() public let willSetObject = Pipe<(UITableViewCell, IndexPath)>() public let didSetObject = Pipe<(UITableViewCell, IndexPath)>() public let willDisplaySectionHeader = Pipe<(UIView, Int)>() public let didEndDisplayingSectionHeader = Pipe<(UIView, Int)>() public let willDisplaySectionFooter = Pipe<(UIView, Int)>() public let didEndDisplayingSectionFooter = Pipe<(UIView, Int)>() public let didScroll = Pipe<UIScrollView>() public let willBeginDragging = Pipe<UIScrollView>() public let didEndDragging = Pipe<(scrollView: UIScrollView, willDecelerate: Bool)>() private var behaviors = [TableViewBehavior]() public var checkedIndexPaths = [IndexPath]() { didSet { tableView.indexPathsForVisibleRows?.forEach { if var checkable = tableView.cellForRow(at: $0) as? Checkable { checkable.checked = checkedIndexPaths.contains($0) } } } } private weak var tableView: UITableView! private var nibs = [String: UINib]() private var dataSource: ObjectsDataSource<ObjectType>! private var cellInstances = [String: UITableViewCell]() private var headerFooterInstances = [String: UITableViewHeaderFooterView]() private var identifiersForIndexPaths = [IndexPath: String]() private var mappings: [String: (ObjectType, UITableViewCell, IndexPath) -> Void] = [:] public init(dataSource: ObjectsDataSource<ObjectType>, tableView: UITableView) { super.init() self.tableView = tableView tableView.dataSource = self tableView.delegate = self self.dataSource = dataSource dataSource.beginUpdatesSignal.subscribeNext { [weak self] in self?.tableView.beginUpdates() }.putInto(pool) dataSource.endUpdatesSignal.subscribeNext { [weak self] in self?.tableView.endUpdates() }.putInto(pool) dataSource.reloadDataSignal.subscribeNext { [weak self] in guard let strongSelf = self else { return } if !strongSelf.animatesReload { tableView.reloadData() return } UIView.animate(withDuration: 0.1, animations: { strongSelf.tableView.alpha = 0}, completion: { completed in strongSelf.tableView.reloadData() UIView.animate(withDuration: 0.2, animations: { strongSelf.tableView.alpha = 1 }) }) }.putInto(pool) dataSource.didChangeObjectSignal.subscribeNext { [weak self] object, changeType, fromIndexPath, toIndexPath in guard let strongSelf = self else { return } switch changeType { case .Insertion: if let toIndexPath = toIndexPath { strongSelf.tableView.insertRows(at: [toIndexPath as IndexPath], with: .fade) } case .Deletion: if let fromIndexPath = fromIndexPath { strongSelf.tableView.deleteRows(at: [fromIndexPath as IndexPath], with: .fade) } case .Update: if let indexPath = toIndexPath { strongSelf.tableView.reloadRows(at: [indexPath as IndexPath], with: .fade) } case .Move: if let fromIndexPath = fromIndexPath, let toIndexPath = toIndexPath { strongSelf.tableView.deleteRows(at: [fromIndexPath as IndexPath], with: .fade) strongSelf.tableView.insertRows(at: [toIndexPath as IndexPath], with: .fade) } } }.putInto(pool) dataSource.didChangeSectionSignal.subscribeNext { [weak self] changeType, fromIndex, toIndex in guard let strongSelf = self else { return } switch changeType { case .Insertion: if let toIndex = toIndex { strongSelf.tableView.insertSections(IndexSet(integer: toIndex), with: .fade) } case .Deletion: if let fromIndex = fromIndex { strongSelf.tableView.deleteSections(IndexSet(integer: fromIndex), with: .fade) } default: break } }.putInto(pool) } public func registerSectionHeaderFooterClass(_ headerFooterClass: UITableViewHeaderFooterView.Type) { let identifier = String(describing: headerFooterClass) headerFooterInstances[identifier] = headerFooterClass.init(reuseIdentifier: String(describing: headerFooterClass)) tableView.register(headerFooterClass, forHeaderFooterViewReuseIdentifier: identifier) } public func registerCellClass<U: ObjectConsuming>(_ cellClass: U.Type) where U.ObjectType == ObjectType { let identifier = String(describing: cellClass) let nib = UINib(nibName: identifier, bundle: nil) tableView.register(nib, forCellReuseIdentifier: identifier) cellInstances[identifier] = nib.instantiate(withOwner: self, options: nil).last as? UITableViewCell mappings[identifier] = { object, cell, _ in (cell as! U).applyObject(object) } } public func addBehavior(_ behavior: TableViewBehavior) { behavior.tableView = tableView behaviors.append(behavior) } //UITableViewDataSource @objc public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfObjectsInSection(section) } @objc public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let object = dataSource.objectAtIndexPath(indexPath)!; let identifier = nibNameForObjectMatching((object, indexPath)) var cell = tableView.dequeueReusableCell(withIdentifier: identifier) identifiersForIndexPaths[indexPath] = identifier if cell == nil { cell = (nibs[identifier]!.instantiate(withOwner: nil, options: nil).last as! UITableViewCell) } willSetObject.sendNext((cell!, indexPath)) let mapping = mappings[identifier]! mapping(object, cell!, indexPath) didSetObject.sendNext((cell!, indexPath)) return cell! } @objc public func numberOfSections(in tableView: UITableView) -> Int { return dataSource.numberOfSections() } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return canEditRowAtIndexPath?(indexPath) ?? false } public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { commitWithEditingStyle?(editingStyle, indexPath) } // UITableViewDelegate @objc public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { return editActionsForRowAtIndexPath?(indexPath) } @objc public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let identifier = nibNameForObjectMatching((dataSource.objectAtIndexPath(indexPath)!, indexPath)) if let cell = cellInstances[identifier] as? HeightCalculatingCell { var userInfo = userInfoForCellHeightMatching(indexPath as IndexPath) behaviors.forEach { userInfo.append($0.cellHeightCalculationUserInfo(forCellAtIndexPath: indexPath)) } return cell.height(forObject: dataSource.objectAtIndexPath(indexPath), width: tableView.frame.size.width, userInfo: userInfo) } return UITableViewAutomaticDimension; } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let headerClass = headerClassForSectionIndexMatching(section), let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: headerClass)) { if let titleApplicable = view as? TitleApplicable, let sectionTitle = dataSource.titleForSection(atIndex: section) { titleApplicable.applyTitle(sectionTitle) } return view } return nil } @objc public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { willDisplaySectionHeader.sendNext((view, section)) behaviors.forEach { $0.tableView?(tableView, willDisplayHeaderView: view, forSection: section) } } @objc public func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { didEndDisplayingSectionHeader.sendNext((view, section)) behaviors.forEach { $0.tableView?(tableView, didEndDisplayingHeaderView: view, forSection: section) } } @objc public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { willDisplaySectionFooter.sendNext(view, section) behaviors.forEach { $0.tableView?(tableView, willDisplayFooterView: view, forSection: section) } } @objc public func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { willDisplaySectionFooter.sendNext(view, section) behaviors.forEach { $0.tableView?(tableView, didEndDisplayingFooterView: view, forSection: section) } } @objc public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if let footerClass = footerClassForSectionIndexMatching(section), let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: footerClass)) { willDisplaySectionFooter.sendNext((view, section)) return view } return nil } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let headerClass = headerClassForSectionIndexMatching(section), let view = headerFooterInstances[String(describing: headerClass)] as? HeightCalculatingCell { var userInfo = userInfoForSectionHeaderHeightMatching(section) behaviors.forEach { userInfo.append($0.sectionHeaderHeightCalculationUserInfo(forHeaderAtIndex: section)) } return view.height(forObject: nil, width: tableView.frame.size.width, userInfo: userInfo) } return UITableViewAutomaticDimension } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let footerClass = footerClassForSectionIndexMatching(section), let view = headerFooterInstances[String(describing: footerClass)] as? HeightCalculatingCell { var userInfo = userInfoForSectionFooterHeightMatching(section) behaviors.forEach { userInfo.append($0.sectionFooterHeightCalculationUserInfo(forFooterAtIndex: section)) } return view.height(forObject: nil, width: tableView.frame.size.width, userInfo: userInfo) } return UITableViewAutomaticDimension } @objc public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { didSelectCell.sendNext(( tableView.cellForRow(at: indexPath)!, indexPath, dataSource.objectAtIndexPath(indexPath)!) ) tableView.deselectRow(at: indexPath, animated: true) behaviors.forEach { $0.tableView?(tableView, didSelectRowAt: indexPath) } } @objc public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if var checkable = cell as? Checkable { checkable.checked = checkedIndexPaths.contains(indexPath) } willDisplayCell.sendNext((cell, indexPath)) behaviors.forEach { $0.tableView?(tableView, willDisplay: cell, forRowAt: indexPath) } } @objc public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { didEndDisplayingCell.sendNext((cell, indexPath)) behaviors.forEach { $0.tableView?(tableView, didEndDisplaying: cell, forRowAt: indexPath) } } @objc public func scrollViewDidScroll(_ scrollView: UIScrollView) { didScroll.sendNext(scrollView) behaviors.forEach { $0.scrollViewDidScroll?(scrollView) } } @objc public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { willBeginDragging.sendNext(scrollView) behaviors.forEach { $0.scrollViewWillBeginDragging?(scrollView) } } @objc public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { didEndDragging.sendNext((scrollView, decelerate)) behaviors.forEach { $0.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) } } }
mit
06d41e62b26280d79350ea0a9b846a3c
39.307246
132
0.709406
5.275417
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Validation/Convenience/Email.swift
1
1389
import Foundation public class Email: ValidationSuite { public static func validate(input value: String) throws { guard let localName = value.components(separatedBy: "@").first where isValidLocalName(localName) else { throw error(with: value) } // Thanks Ben Wu :) #if os(Linux) let range = value.range(of: ".@.+\\..", options: .regularExpressionSearch) #else let range = value.range(of: ".@.+\\..", options: .regularExpression) #endif guard let _ = range else { throw error(with: value) } } private static func isValidLocalName(_ string: String) -> Bool { let original = string.characters let valid = original.filter(isValid) return valid.count == original.count } // Based on http://stackoverflow.com/a/2049510/2611971 private static func isValid(_ character: Character) -> Bool { switch character { case "a"..."z", "A"..."Z", "0"..."9": return true // valid non alphanumeric characters case "!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~", ".": return true default: return false } } }
mit
c03967e673ba61f814298de36898cae0
29.195652
112
0.483801
4.890845
false
false
false
false
TwoRingSoft/shared-utils
Sources/PippinDebugging/DebugViewController.swift
1
4884
// // DebugViewController.swift // PippinDebugging // // Created by Andrew McKnight on 7/31/17. // Copyright © 2019 Two Ring Software. All rights reserved. // import Anchorage import Pippin import UIKit protocol DebugViewControllerDelegate { func debugViewControllerDisplayedMenu(debugViewController: DebugViewController) func debugViewControllerHidMenu(debugViewController: DebugViewController) } public class DebugViewController: UIViewController { private var delegate: DebugViewControllerDelegate! private var environment: Environment private var debugMenu: UIView! private var displayButton: UIButton! private var assetBundle: Bundle? init(delegate: DebugViewControllerDelegate, environment: Environment, assetBundle: Bundle? = nil, buttonTintColor: UIColor, buttonStartLocation: CGPoint, appControlPanel: UIView? = nil) { self.delegate = delegate self.environment = environment self.assetBundle = assetBundle super.init(nibName: nil, bundle: nil) setUpUI(buttonTintColor: buttonTintColor, buttonStartLocation: buttonStartLocation, appControlPanel: appControlPanel) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @objc extension DebugViewController { func closePressed() { debugMenu.isHidden = true displayButton.isHidden = false delegate.debugViewControllerHidMenu(debugViewController: self) } func displayPressed() { debugMenu.isHidden = false displayButton.isHidden = true delegate.debugViewControllerDisplayedMenu(debugViewController: self) } func draggedDisplayButton(recognizer: UIPanGestureRecognizer) { guard let button = recognizer.view else { return } let translation = recognizer.translation(in: view) button.center = CGPoint(x: button.center.x + translation.x, y: button.center.y + translation.y) recognizer.setTranslation(.zero, in: view) } } private extension DebugViewController { func setUpUI(buttonTintColor: UIColor, buttonStartLocation: CGPoint, appControlPanel: UIView? = nil) { debugMenu = UIView(frame: .zero) debugMenu.isHidden = true debugMenu.backgroundColor = .white view.addSubview(debugMenu) debugMenu.fillSuperview() let scrollView = UIScrollView(frame: .zero) debugMenu.addSubview(scrollView) scrollView.fillSuperview() let stackWidthSizingView = UIView(frame: .zero) debugMenu.addSubview(stackWidthSizingView) stackWidthSizingView.horizontalAnchors == debugMenu.horizontalAnchors stackWidthSizingView.heightAnchor == 0 stackWidthSizingView.topAnchor == debugMenu.topAnchor var controlPanels = [UIView]() let debuggingControls: [UIView?] = [ environment.model?.debuggingControlPanel(), environment.activityIndicator?.debuggingControlPanel(), environment.alerter?.debuggingControlPanel(), environment.crashReporter?.debuggingControlPanel(), environment.locator?.debuggingControlPanel(), environment.logger?.debuggingControlPanel(), environment.touchVisualizer?.debuggingControlPanel(), environment.bugReporter?.debuggingControlPanel(), ] debuggingControls.forEach { if let view = $0 { controlPanels.append(view) } } let closeButton = UIButton(frame: .zero) closeButton.configure(title: "Close", target: self, selector: #selector(closePressed)) controlPanels.append(closeButton) if let appControlPanel = appControlPanel { controlPanels.insert(appControlPanel, at: 0) } let stack = UIStackView(arrangedSubviews: controlPanels) stack.axis = .vertical stack.distribution = .equalSpacing scrollView.addSubview(stack) stack.edgeAnchors == scrollView.edgeAnchors stack.widthAnchor == stackWidthSizingView.widthAnchor displayButton = UIButton.button(withImageSetName: "debug", emphasisSuffix: "-pressed", tintColor: buttonTintColor, target: self, selector: #selector(displayPressed), imageBundle: assetBundle) let size: CGFloat = 50 displayButton.frame = CGRect(x: buttonStartLocation.x, y: buttonStartLocation.y, width: size, height: size) displayButton.layer.cornerRadius = size / 2 displayButton.layer.borderWidth = 2 displayButton.layer.borderColor = buttonTintColor.cgColor view.addSubview(displayButton) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(draggedDisplayButton)) displayButton.addGestureRecognizer(panGestureRecognizer) } }
mit
70e8b707a41a37da49ab31e944e53b24
37.148438
199
0.700594
5.178155
false
false
false
false
coffee-cup/solis
SunriseSunset/SunViewController.swift
1
21038
// // ViewController.swift // SunriseSunset // // Created by Jake Runzer on 2016-05-14. // Copyright © 2016 Puddllee. All rights reserved. // import UIKit import EDSunriseSet import CoreLocation import UIView_Easing import SPPermission class SunViewController: UIViewController, TouchDownProtocol, UIGestureRecognizerDelegate, MenuProtocol, SunProtocol, SPPermissionDialogDelegate { @IBOutlet weak var sunView: UIView! @IBOutlet weak var hourSlider: UISlider! var gradientLayer = CAGradientLayer() var backgroundView: UIView! @IBOutlet weak var nowView: UIView! @IBOutlet weak var nowTimeLabel: UILabel! @IBOutlet weak var nowLineView: UIView! @IBOutlet weak var nowLabel: UILabel! @IBOutlet weak var nowLeftConstraint: NSLayoutConstraint! @IBOutlet weak var futureLabel: UILabel! @IBOutlet weak var pastLabel: UILabel! @IBOutlet weak var noLocationLabel1: SpringLabel! @IBOutlet weak var noLocationLabel2: SpringLabel! @IBOutlet weak var centerImageView: SpringImageView! @IBOutlet weak var centerButton: UIButton! // You guessed it: users current coordinates var myLoc: CLLocationCoordinate2D! // All of the logic to compute gradients and suntimes var sun: Sun! // Main view in display we use to capture all touch events var touchDownView: TouchDownView! // The offset in minutes that we are from now var offset: Double = 0 // The offset y transform that we are for rest position var offsetTranslation: Double = 0 var timer = Timer() // How long the sun view has been free scrolling var animationTimer = Timer() // The date the timer started running var animationFireDate: Date! // Whether or not we are scrolling free form var scrolling = false // Whether or not we are touch panning var panning = false // Whether or not a touch down event stopped the free scrolling var animationStopped = false // Whether or not the user is allowed to touch pan var allowedPan = true // Whether or not the sun view is off from rest position var offNow = false // Whether or not the menu is out of position right now var isMenuOut = false // Whether or not the now line is colliding with a sun line var colliding = false // Whether we have a location to render a gradient with var gotLocation = false // Flag indicating the location just changed var locationJustChanged = false // The duration we will free form for var scrollAnimationDuration: TimeInterval = 0 // The duration the animation went for before it was stopped var stopAnimationDuration: Double = 0 // The y transform before the free form scrolling started var transformBeforeAnimation: Double = 0 // The y transform after the free form scrolling ended var transformAfterAnimation: Double = 0 // TODO: Remove hardcoded free form scroll duration let SCROLL_DURATION: TimeInterval = 1.2 // Duration to use when animation sun view fade let MenuFadeAnimationDuration: TimeInterval = 0.25 // Background alpha of background overlay view when menu is out let MenuBackgroundAlpha: CGFloat = 0.4 // Whether or not the sun view is fading due to the menu animating let menuAnimation = false // How large the sun view is compared to the normal view let SunViewScreenMultiplier: CGFloat = 9 var smoothyOffset: Double = 0 var smoothyForward = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let screenMinutes = Float(60 * 6) // 6 hours / screen height let screenHeight = Float(view.frame.height) let sunHeight = screenHeight * Float(SunViewScreenMultiplier) sunView.translatesAutoresizingMaskIntoConstraints = true sunView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: CGFloat(sunHeight)) sunView.center = view.center touchDownView = view as? TouchDownView touchDownView.delegate = self touchDownView.backgroundColor = nauticalColour gradientLayer.backgroundColor = nauticalColour.cgColor sunView.layer.addSublayer(gradientLayer) nowLabel.textColor = nameTextColour nowLabel.font = fontTwilight nowTimeLabel.textColor = timeTextColour nowTimeLabel.font = fontDetail nowLineView.backgroundColor = nowLineColour nowLineView.isUserInteractionEnabled = false nowLabel.addSimpleShadow() nowTimeLabel.addSimpleShadow() pastLabel.addSimpleShadow() futureLabel.addSimpleShadow() centerButton.isEnabled = false centerImageView.duration = CGFloat(1) centerImageView.curve = "easeInOut" centerImageView.alpha = 0 noLocationLabel1.alpha = 0 noLocationLabel2.alpha = 0 sun = Sun(screenMinutes: screenMinutes, screenHeight: screenHeight, sunHeight: sunHeight, sunView: sunView, gradientLayer: gradientLayer, nowTimeLabel: nowTimeLabel, nowLabel: nowLabel) sun.delegate = self // Gestures // Double tap let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap)) doubleTapRecognizer.numberOfTapsRequired = 2 sunView.addGestureRecognizer(doubleTapRecognizer) // Pan (scrolling) let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture)) panRecognizer.delegate = self sunView.addGestureRecognizer(panRecognizer) // Send Menu in tap let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGesture)) sunView.addGestureRecognizer(tapRecognizer) // Long press tap (toggle sun areas) let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture)) longPressRecognizer.allowableMovement = 0.5 longPressRecognizer.minimumPressDuration = 0.5 sunView.addGestureRecognizer(longPressRecognizer) setupBackgroundView() // Notifications Bus.subscribeEvent(.locationUpdate, observer: self, selector: #selector(locationUpdate)) Bus.subscribeEvent(.locationChanged, observer: self, selector: #selector(locationChanged)) Bus.subscribeEvent(.gotTimeZone, observer: self, selector: #selector(timeZoneUpdate)) Bus.subscribeEvent(.foregrounded, observer: self, selector: #selector(scrollReset)) reset() scrollReset() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) sunView.alpha = 0 update() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupPermissions() // Update every minute timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(update), userInfo: nil, repeats: true) } deinit { NotificationCenter.default.removeObserver(self) Bus.removeSubscriptions(self) } func setupBackgroundView() { backgroundView = UIView() backgroundView.backgroundColor = UIColor.black backgroundView.translatesAutoresizingMaskIntoConstraints = false backgroundView.isUserInteractionEnabled = false backgroundView.alpha = 0 view.addSubview(backgroundView) view.bringSubviewToFront(backgroundView) let horizontalContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": backgroundView!]) let verticalContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": backgroundView!]) NSLayoutConstraint.activate(horizontalContraints + verticalContraints) } func startAnimationTimer() { animationTimer = Timer.scheduledTimer(timeInterval: 0.06, target: self, selector: #selector(animationUpdate), userInfo: nil, repeats: true) animationFireDate = Date() } func stopAnimationTimer() { animationTimer.invalidate() } func setupPermissions() { if SPPermission.isAllowed(.locationWhenInUse) { SunLocation.startLocationWatching() } else { SPPermission.Dialog.request(with: [.locationWhenInUse], on: self, delegate: self, dataSource: PermissionController()) } } @objc func didAllow(permission: SPPermissionType) { if SPPermission.isAllowed(.locationWhenInUse) { SunLocation.startLocationWatching() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dateComponentsToString(_ d: DateComponents) -> String { return "\(String(describing: d.hour)):\(String(describing: d.minute))" } @objc func timeZoneUpdate() { update() } @objc func locationUpdate() { print("location update") update() } @objc func locationChanged() { print("location changed") locationJustChanged = true // scrollReset() } // Enable=true means we are showing the no location views func noLocationViews(_ enable: Bool) { if !gotLocation { // Do not re-animate if already showing if enable && noLocationLabel1.alpha == 1 { return } else if !enable && noLocationLabel1.alpha == 0 { return } UIView.animate(withDuration: 0.5) { self.noLocationLabel1.alpha = enable ? 1 : 0 self.noLocationLabel2.alpha = enable ? 1 : 0 self.nowView.alpha = !enable ? 1 : 0 } } } // Update all the views the with the time offset value @objc func update() { if (!scrolling && !panning && !offNow) || locationJustChanged { if let location = SunLocation.getLocation() { sun.update(offset, location: location) // Fade in sun view if not already visible if self.sunView.alpha == 0 { UIView.animate(withDuration: 0.5) { self.sunView.alpha = 1 } } // If we are updating right from changing location // reset the scroll if locationJustChanged { locationJustChanged = false scrollReset() } noLocationViews(false) gotLocation = true } else { noLocationViews(true) } } offNow = Int(floor(offset)) != 0 setCenterButton() } // Update from transformation move // Do not update maths of sunlines func moveUpdate(_ offset: Double = 0) { offNow = Int(floor(abs(offset))) != 0 sun.findNow(offNow ? offset : 0) setCenterButton() } func setCenterButton() { if offNow && !centerButton.isEnabled { centerButton.isEnabled = true centerImageView.animation = "fadeIn" centerImageView.animate() } else if !offNow && centerButton.isEnabled { centerButton.isEnabled = false centerImageView.animation = "fadeOut" centerImageView.animate() } } func reset() { self.stopAnimationTimer() self.scrolling = false self.panning = false self.allowedPan = true self.offset = 0.0 self.offsetTranslation = 0.0 } // Menu func menuIn() { isMenuOut = false } func menuOut() { isMenuOut = true } func menuStartAnimatingIn() { UIView.animate(withDuration: MenuFadeAnimationDuration) { self.backgroundView.alpha = 0 self.isMenuOut = false } } func menuIsIn() { backgroundView.alpha = 0 isMenuOut = false } func menuStartAnimatingOut() { isMenuOut = true UIView.animate(withDuration: MenuFadeAnimationDuration) { self.backgroundView.alpha = self.MenuBackgroundAlpha } } func menuIsOut() { backgroundView.alpha = MenuBackgroundAlpha isMenuOut = true } func menuIsMoving(_ percent: Float) { let alpha = CGFloat(percent) * MenuBackgroundAlpha backgroundView.alpha = alpha isMenuOut = alpha != 0 } // Touch and Dragging // constrain offset minutes and offset tranform within proper view bounds func normalizeOffsets(_ transformBy: Double, offsetBy: Double) -> (Double, Double) { var newTransformBy = transformBy var newOffsetBy = offsetBy let ViewPadding: Double = 0 let halfHeight = Double(sun.screenHeight) / 2 let halfSunHeight = Double(sun.sunHeight) / 2 let neg = transformBy < 0 if abs(transformBy) > halfSunHeight - halfHeight - ViewPadding { newTransformBy = halfSunHeight - halfHeight - ViewPadding newOffsetBy = sun.pointsToMinutes(transformBy) newTransformBy = neg ? newTransformBy * -1 : newTransformBy newOffsetBy = neg ? newOffsetBy * -1 : newOffsetBy } return (newTransformBy, newOffsetBy) } // Convert tranform y translation to minute offset and normalize func setOffsetFromTranslation(_ translation: Double) { offsetTranslation = translation offset = sun.pointsToMinutes(offsetTranslation) (offsetTranslation, offset) = normalizeOffsets(offsetTranslation, offsetBy: offset) } @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { let translation = Double(recognizer.translation(in: view).y) let offsetMinutes = sun.pointsToMinutes(translation) let offsetSeconds = offsetMinutes if (recognizer.state == .began) { if recognizer.location(in: view).x < 40 || scrolling { // 40 so pan gestures don't interfer with pulling menu out allowedPan = false } else { panning = true } } else if (recognizer.state == .changed) { if allowedPan && !isMenuOut && !scrolling { let transformBy = translation + offsetTranslation let offsetBy = offsetSeconds + offset let (newTransformBy, newOffsetBy) = normalizeOffsets(transformBy, offsetBy: offsetBy) self.sunView.transform = CGAffineTransform(translationX: 0, y: CGFloat(newTransformBy)) moveUpdate(newOffsetBy) } } else if (recognizer.state == .ended) { if allowedPan && !isMenuOut { offset += offsetSeconds offsetTranslation += translation (offsetTranslation, offset) = normalizeOffsets(offsetTranslation, offsetBy: offset) let velocity = Double(recognizer.velocity(in: view).y) if abs(velocity) > 12 { // 12 so scroll doesn't animate for soft pans animateScroll(velocity * 0.55) // 0.55 to weaken momentum scoll velocity } } panning = false allowedPan = true } } func animateScroll(_ velocity: Double) { transformAfterAnimation = offsetTranslation + velocity (transformAfterAnimation, _) = normalizeOffsets(transformAfterAnimation, offsetBy: 0) startAnimationTimer() transformBeforeAnimation = Double(sunView.transform.ty) // TODO: Make scroll duration dynamic scrollAnimationDuration = SCROLL_DURATION scrolling = true UIView.animate(withDuration: scrollAnimationDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { self.sunView.setEasingFunction(Easing.easeOutQuad, forKeyPath: "transform") self.sunView.transform = CGAffineTransform(translationX: 0, y: CGFloat(self.transformAfterAnimation)) }, completion: {finished in self.setTransformWhenStopped() self.animationStopped = false }) } @objc func doubleTap(_ recognizer: UITapGestureRecognizer) { scrollReset() } func setTransformWhenStopped() { self.stopAnimationTimer() self.scrolling = false self.sunView.removeEasingFunction(forKeyPath: "transform") let transformDifference = self.transformAfterAnimation - self.transformBeforeAnimation let animationDuration = abs(self.animationFireDate.timeIntervalSinceNow) + (1 / 60) // <- this magic number makes view not jump as much when scroll stopping self.offsetTranslation = Easing.easeOutQuadFunc(animationDuration, startValue: self.transformBeforeAnimation, changeInValue: transformDifference, duration: self.scrollAnimationDuration) if (!self.animationStopped) { self.offsetTranslation = self.transformAfterAnimation } self.setOffsetFromTranslation(self.offsetTranslation) moveUpdate(self.offset) self.sunView.transform = CGAffineTransform(translationX: 0, y: CGFloat(self.offsetTranslation)) } @objc func scrollReset() { transformBeforeAnimation = Double(sunView.transform.ty) transformAfterAnimation = 0.0 scrollAnimationDuration = SCROLL_DURATION startAnimationTimer() scrolling = true UIView.animate(withDuration: scrollAnimationDuration, animations: { self.sunView.setEasingFunction(Easing.easeOutQuad, forKeyPath: "transform") self.sunView.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: { finished in self.sunView.removeEasingFunction(forKeyPath: "transform") self.reset() self.update() }) } func stopScroll() { animationStopped = true sunView.layer.removeAllAnimations() self.setTransformWhenStopped() } @objc func animationUpdate() { let transformDifference = self.transformAfterAnimation - self.transformBeforeAnimation let ease = Easing.easeOutQuadFunc(animationFireDate.timeIntervalSinceNow * -1, startValue: transformBeforeAnimation, changeInValue: transformDifference, duration:scrollAnimationDuration) // print("d: \(animationFireDate.timeIntervalSinceNow * -1) b: \(transformBeforeAnimation) a: \(transformAfterAnimation) ease: \(ease)") moveUpdate(sun.pointsToMinutes(ease)) } @objc func tapGesture(_ recognizer: UITapGestureRecognizer) { Bus.sendMessage(.sendMenuIn, data: nil) } @objc func longPressGesture(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { sun.toggleSunAreas() } } func touchDown(_ touches: Set<UITouch>, withEvent event: UIEvent?) { if scrolling { stopScroll() } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @IBAction func centerButtonDidTouch(_ sender: AnyObject) { stopAnimationTimer() scrollReset() } func collisionIsHappening() { if !colliding { // Fixes sunline overlap on iphone5 screens and smaller nowLeftConstraint.constant = sunView.frame.width < 375 ? 210 : 240 UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(), animations: { self.nowView.layoutIfNeeded() }, completion: nil) } colliding = true } func collisionNotHappening() { if colliding { nowLeftConstraint.constant = 100 UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(), animations: { self.nowView.layoutIfNeeded() }, completion: nil) } colliding = false } }
mit
fffc6cb79884a50d79e23d18379a99f2
35.084048
194
0.627941
5.261881
false
false
false
false
kfarst/alarm
alarm/AppDelegate.swift
1
7076
// // AppDelegate.swift // alarm // // Created by Kevin Farst on 3/4/15. // Copyright (c) 2015 Kevin Farst. All rights reserved. // import AVFoundation import CoreData import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Initial setup before we start the UI setupMagicalRecord() setupAVAudioSession() AlarmManager.createInitialAlarms() AlarmManager.updateAlarmHelper() LocationHelper.enableMonitoring() self.window = UIWindow(frame: UIScreen.mainScreen().bounds) if let window = self.window { var homeViewController = HomeViewController( nibName: "HomeViewController", bundle: nil ) window.rootViewController = homeViewController window.makeKeyAndVisible() // Request location and recording access // We should move this into the onboarding LocationHelper.requestLocationAccess() SoundMonitor.requestPermissionIfNeeded() } return true } private func setupMagicalRecord() { MagicalRecord.setupAutoMigratingCoreDataStack() } private func setupAVAudioSession() { let session = AVAudioSession.sharedInstance() var error: NSError? session.setCategory( AVAudioSessionCategoryPlayAndRecord, error: &error ) if let e = error { NSLog(e.description) } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. NSLog("applicationWillResignActive") } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. NSLog("applicationDidEnterBackground") } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. NSLog("applicationWillEnterForeground") } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. NSLog("applicationDidBecomeActive") } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. NSLog("applicationWillTerminate") MagicalRecord.cleanUp() self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.codepath.alarm" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("alarm", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("alarm.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject]) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
0e6aa0dea703ef543ec87a90553e9bbc
44.358974
286
0.747032
5.485271
false
false
false
false
nosrak113/SwiftValidator
Validator/FloatRule.swift
1
913
// // FloatRule.swift // Validator // // Created by Cameron McCord on 5/5/15. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation public class FloatRule:Rule { private var message : String public init(message : String = "This must be a number with or without a decimal"){ self.message = message } public func validate(value: String) -> Bool { let regex: NSRegularExpression? do { regex = try NSRegularExpression(pattern: "[-+]?(\\d*[.])?\\d+", options: []) } catch _ { regex = nil } if let regex = regex { let match = regex.numberOfMatchesInString(value, options: [], range: NSRange(location: 0, length: value.characters.count)) return match == 1 } return false } public func errorMessage() -> String { return message } }
mit
d9eee23473fd8670f30f3d28d6ad1342
24.388889
134
0.573932
4.327014
false
false
false
false
vishalSonawane/LoginForm
LoginForm/UIViewExtension.swift
2
1567
// // UIViewExtension.swift // LoginForm // // Created by vishalsonawane on 12/12/16. // Copyright © 2016 vishalsonawane. All rights reserved. // import Foundation import UIKit extension UIView { @IBInspectable var shadow: Bool { get { return layer.shadowOpacity > 0.0 } set { if newValue == true { self.addShadow() } } } @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue // Don't touch the masksToBound property if a shadow is needed in addition to the cornerRadius if shadow == false { self.layer.masksToBounds = true } } } // MARK: Add Shadow func addShadow(shadowColor: CGColor = UIColor.black.cgColor, shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0), shadowOpacity: Float = 0.4, shadowRadius: CGFloat = 3.0) { layer.shadowColor = shadowColor layer.shadowOffset = shadowOffset layer.shadowOpacity = shadowOpacity layer.shadowRadius = shadowRadius } // MARK: Gradient Color Generation func addGradientWithColor(color: UIColor) { let gradient = CAGradientLayer() gradient.frame = self.frame gradient.colors = [UIColor.clear.cgColor, color.cgColor] self.layer.insertSublayer(gradient, at: 0) } }
apache-2.0
f8c1a921d54f752e989d1ca5be8b1690
26.964286
106
0.569604
4.788991
false
false
false
false
AaronMT/firefox-ios
Sync/KeysPayload.swift
11
1540
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import Shared import SwiftyJSON open class KeysPayload: CleartextPayloadJSON { override open func isValid() -> Bool { return super.isValid() && self["default"].isArray() } fileprivate func keyBundleFromPair(_ input: JSON) -> KeyBundle? { if let pair: [JSON] = input.array { if let encKey = pair[0].string { if let hmacKey = pair[1].string { return KeyBundle(encKeyB64: encKey, hmacKeyB64: hmacKey) } } } return nil } var defaultKeys: KeyBundle? { return self.keyBundleFromPair(self["default"]) } var collectionKeys: [String: KeyBundle] { if let collections: [String: JSON] = self["collections"].dictionary { return optFilter(mapValues(collections, f: self.keyBundleFromPair)) } return [:] } override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool { if !(obj is KeysPayload) { return false } if !super.equalPayloads(obj) { return false } let p = obj as! KeysPayload if p.defaultKeys != self.defaultKeys { return false } // TODO: check collections. return true } }
mpl-2.0
a6d2c1234d6f7d8404a280b7dd7c9c4f
26.5
79
0.581169
4.680851
false
false
false
false
dmiedema/URLSessionMetrics
Example/URLSessionMetrics/RequestManager.swift
1
1997
// // RequestManager.swift // URLSessionMetrics // // Created by Daniel Miedema on 6/16/16. // Copyright © 2016 dmiedema. All rights reserved. // import Foundation import URLSessionMetrics public struct RequestBuilder { public enum Method: String { case GET = "GET" case POST = "POST" } public let method: Method public let baseURL: String public let path: String? public var url: URL? { return URL(string: baseURL + (path ?? "")) } public var request: URLRequest? { guard let url = url else { return nil } var request = URLRequest(url: url) request.httpMethod = method.rawValue return request } public static func build(method: Method, baseURL: String, path: String?) -> RequestBuilder { return RequestBuilder(method: method, baseURL: baseURL, path: path) } public static func build(method: Method, baseURL: String) -> RequestBuilder { return RequestBuilder(method: method, baseURL: baseURL, path: nil) } } public class RequestManager: NSObject { public static var session: URLSession { let session = URLSession(configuration: URLSessionConfiguration.default, delegate: RequestManager(), delegateQueue: OperationQueue.main) return session } public class func send(request: URLRequest, completion: ((Data?, URLResponse?, NSError?) -> Void)?) { let task = session.dataTask(with: request) { (data, response, error) in guard let completion = completion else { return } DispatchQueue.main.async { completion(data, response, error as NSError?) } } task.resume() } } extension RequestManager: URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { NSLog("Finished collecting metrics") DefaultMetricsManager.shared.add(entry: metrics) } }
mit
697bc49da9cb610d9fec5fdd6fcd8f19
29.707692
144
0.660321
4.718676
false
false
false
false
PartiallyFinite/SwiftDataStructures
Sources/RBTree.swift
1
22139
// // RBTree.swift // SwiftDataStructures // // The MIT License (MIT) // // Copyright (c) 2016 Greg Omelaenko // // 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. // private final class _RBTreeNode<Key, Value> : NonObjectiveCBase { var red = true var left, right: _RBTreeNode! weak var parent: _RBTreeNode! let key: Key! var value: Value! init(sentinel: ()) { red = false key = nil value = nil super.init() } init(key: Key, value: Value, sentinel: _RBTreeNode) { self.key = key self.value = value assert(sentinel.isSentinel) left = sentinel; right = sentinel; parent = sentinel } init(deepCopy node: _RBTreeNode, sentinel: _RBTreeNode, setParent: _RBTreeNode? = nil) { key = node.key value = node.value red = node.red parent = setParent ?? sentinel super.init() left = node.left.isSentinel ? sentinel : _RBTreeNode(deepCopy: node.left, sentinel: sentinel, setParent: self) right = node.right.isSentinel ? sentinel : _RBTreeNode(deepCopy: node.right, sentinel: sentinel, setParent: self) } var isSentinel: Bool { return key == nil } /// - Complexity: O(log count) func subtreeMin() -> _RBTreeNode { guard !self.isSentinel else { return self } var x = self while !x.left.isSentinel { x = x.left } assert(!x.isSentinel) return x } /// - Complexity: O(log count) func subtreeMax() -> _RBTreeNode { guard !self.isSentinel else { return self } var x = self while !x.right.isSentinel { x = x.right } assert(!x.isSentinel) return x } /// - Complexity: Amortised O(1) func successor() -> _RBTreeNode? { if isSentinel { return nil } // if the right subtree exists, the successor is the smallest item in it if !right.isSentinel { return right.subtreeMin() } // the successor is the first ancestor which has self in its left subtree var x = self, y = x.parent while !y.isSentinel && x == y.right { x = y; y = x.parent } return y.isSentinel ? nil : y } /// - Complexity: Amortised O(1) func predecessor() -> _RBTreeNode? { if isSentinel { return nil } // if the left subtree exists, the predecessor is the largest item in it if !left.isSentinel { return left.subtreeMax() } // the predecessor is the first ancestor which has self in its right subtree var x = self, y = x.parent while !y.isSentinel && x == y.left { x = y; y = x.parent } return y.isSentinel ? nil : y } } @inline(__always) private func ==<Key, Value>(lhs: _RBTreeNode<Key, Value>, rhs: _RBTreeNode<Key, Value>) -> Bool { return lhs === rhs } extension _RBTreeNode : Equatable { } private enum _RBTreeIndexKind<Key, Value> { case Node(Unowned<_RBTreeNode<Key, Value>>) case End(last: Unowned<_RBTreeNode<Key, Value>>) case Empty } /// Used to access elements of an `_RBTree<Key, Value>`. public struct _RBTreeIndex<Key, Value> : BidirectionalIndexType { private typealias Node = _RBTreeNode<Key, Value> private typealias Kind = _RBTreeIndexKind<Key, Value> private let kind: Kind private init(node u: Unowned<Node>) { kind = .Node(u) } private init(node: Node) { self.init(node: Unowned(node)) } private init(end u: Unowned<Node>) { assert(u.value.successor() == nil, "Cannot make end index for a node that is not the end.") kind = .End(last: u) } private init(end last: Node) { self.init(end: Unowned(last)) } private init(empty: ()) { kind = .Empty } /// - Complexity: Amortised O(1) public func successor() -> _RBTreeIndex { switch kind { case .Node(let u): guard let suc = u.value.successor() else { return _RBTreeIndex(end: u) } return _RBTreeIndex(node: suc) case .End(_): fallthrough case .Empty: preconditionFailure("Cannot get successor of the end index.") } } /// - Complexity: Amortised O(1) public func predecessor() -> _RBTreeIndex { switch kind { case .Node(let u): guard let pre = u.value.predecessor() else { preconditionFailure("Cannot get predecessor of the start index.") } return _RBTreeIndex(node: pre) case .End(last: let u): return _RBTreeIndex(node: u) case .Empty: preconditionFailure("Cannot get predecessor of the start index.") } } /// Return whether the index is safe to subscript. public var _safe: Bool { if case .Node(_) = kind { return true } return false } /// The node the index refers to, if any. private var node: Node? { if case .Node(let u) = kind { return u.value } return nil } } public func ==<Key, Value>(lhs: _RBTreeIndex<Key, Value>, rhs: _RBTreeIndex<Key, Value>) -> Bool { switch (lhs.kind, rhs.kind) { case (.Node(let a), .Node(let b)): return a.value === b.value case (.End(let a), .End(let b)): return a.value === b.value case (.Empty, .Empty): return true default: return false } } /* A red-black tree is a binary tree that satisfies the following red-black properties: 1. Every node is either red or black. 2. The root is black. 3. Every leaf (nil) is black. 4. If a node is red, then both its children are black. 5. For each node, all simple paths from the node to descendant leaves contain the same number of black nodes. */ /// Implements a red-black binary tree: a collection of keys with associated values, ordered by key only. /// /// Provides O(log `count`) insertion, search, and removal, as well as a `CollectionType` interface. public struct _RBTree<Key : Comparable, Value> { private typealias Node = _RBTreeNode<Key, Value> private var sentinel = Node(sentinel: ()) private var root: Node private unowned var firstNode, lastNode: Node public private(set) var count = 0 /// Copy-on-write optimisation. Return `true` if the tree was copied. /// - Complexity: Expected O(1), O(`count`) if the structure was copied and modified. private mutating func ensureUnique() -> Bool { if _slowPath(root != sentinel && !isUniquelyReferenced(&root)) { sentinel = Node(sentinel: ()) root = _RBTreeNode(deepCopy: root, sentinel: sentinel) firstNode = root.subtreeMin() lastNode = root.subtreeMax() return true } assert(root == sentinel || isUniquelyReferenced(&root)) return false } public init() { root = sentinel firstNode = sentinel lastNode = sentinel } // TODO: initialiser that takes a sorted sequence and constructs a tree in O(n) time /// - Complexity: O(n log n), where n = `seq.count`. public init<S : SequenceType where S.Generator.Element == Element>(_ seq: S) { self.init() for (k, v) in seq { insert(k, with: v) } } private func loopSentinel() { assert(sentinel.isSentinel) assert(!sentinel.red) assert(sentinel.left == nil) assert(sentinel.right == nil) assert(sentinel.parent == nil) sentinel.left = sentinel sentinel.right = sentinel sentinel.parent = sentinel } private func fixSentinel() { assert(sentinel.isSentinel) assert(!sentinel.red) sentinel.left = nil sentinel.right = nil sentinel.parent = nil } /// Insert the key `k` into the tree with associated value `value`. Returns the index at which `k` was inserted. /// /// If this is the *first* modification to the tree since creation or copying, invalidates all indices with respect to `self`. /// /// - Complexity: O(log `count`) public mutating func insert(k: Key, with value: Value) -> Index { ensureUnique() loopSentinel() let z = Node(key: k, value: value, sentinel: sentinel) do { var y = sentinel var x = root // find a leaf (nil) node x to replace with z, and its parent y while x != sentinel { y = x // move left if z sorts before x, right otherwise x = z.key < x.key ? x.left : x.right } z.parent = y // y is only nil if x is the root if y == sentinel { root = z } // attach z to left or right of y, depending on sort order else if z.key < y.key { y.left = z } else { y.right = z } } // fix violated red-black properties (rebalance the tree) do { var z = z while z.parent.red { let zp = z.parent assert(z.red) assert(zp != root) // if zp is the root, then zp is black let zpp = zp.parent // zp is red, so cannot be the root // if z's parent is a right child, swap left and right operations // further comments that mention left/right assume left let left = zp === zpp.left let y = left ? zpp.right : zpp.left if y.red { // case 1: z's uncle y is red zp.red = false y.red = false zpp.red = true z = zpp } else { // if z is a right child if z === (left ? zp.right : zp.left) { // case 2: z's uncle y is black and z is a right child z = zp left ? rotateLeft(z) : rotateRight(z) // z is now a left child } let zp = z.parent, zpp = zp.parent // case 3: z's uncle y is black and z is a left child zp.red = false zpp.red = true left ? rotateRight(zpp) : rotateLeft(zpp) } } root.red = false } fixSentinel() count += 1 if firstNode == sentinel || z.key < firstNode.key { firstNode = z } assert(firstNode.predecessor() == nil) if lastNode == sentinel || z.key >= lastNode.key { lastNode = z } assert(lastNode.successor() == nil) return Index(node: z) } /// Remove the element at `index`. /// /// If this is the *first* modification to the tree since creation or copying, invalidates all indices with respect to `self`. /// /// - Complexity: O(log `count`) public mutating func remove(index: Index) { let z: Node do { precondition(index._safe, "Cannot remove an index that is out of range.") let copied = ensureUnique() // call this before creating additional references to nodes var node = index.node! // get the node // the index was in the previous tree, find it in this one // the O(log `count`) complexity of this operation doesn't matter as it is equal to the complexity of the removal operation if copied { // make a path of left (true) / right turns from the root var path = ContiguousArray<Bool>() // the other tree has a different sentinel let old = node while !node.parent.isSentinel { path.append(node == node.parent.left) node = node.parent } node = root for left in path.reverse() { node = left ? node.left : node.right } assert(node.key == old.key) } loopSentinel() z = node } count -= 1 if z == firstNode { firstNode = firstNode.successor() ?? sentinel } if z == lastNode { lastNode = lastNode.predecessor() ?? sentinel } var ored = z.red let x: Node if z.left == sentinel { // replace z with its only right child, or the sentinel if it has no children x = z.right transplant(z, with: z.right) } else if z.right == sentinel { // replace z with its only left child x = z.left transplant(z, with: z.left) } else { // 2 children let y = z.right.subtreeMin() ored = y.red // y has no left child (successor is leftmost in subtree) x = y.right // y === r, move r's right subtree under y if y.parent == z { x.parent = y } else { // replace y with its right subtree transplant(y, with: y.right) // move z's right subtree under y y.right = z.right y.right.parent = y } // replace z with y transplant(z, with: y) // place z's left subtree on y's left y.left = z.left y.left.parent = y y.red = z.red } // fix violated red-black properties (rebalance) if !ored { var x = x while x != root && !x.red { // mirror directional operations if x is a right child let left = x == x.parent.left var w: Node = left ? x.parent.right : x.parent.left assert(w != sentinel) if w.red { // case 1 w.red = false x.parent.red = true left ? rotateLeft(x.parent) : rotateRight(x.parent) w = left ? x.parent.right : x.parent.left assert(w != sentinel) } if !w.left.red && !w.right.red { // case 2 w.red = true x = x.parent } else { if left ? !w.right.red : !w.left.red { // case 3 left ? (w.left.red = false) : (w.right.red = false) w.red = true left ? rotateRight(w) : rotateLeft(w) w = left ? x.parent.right : x.parent.left assert(w != sentinel) } // case 4: w's right child is red assert(left ? w.right.red : w.left.red) w.red = x.parent.red x.parent.red = false left ? (w.right.red = false) : (w.left.red = false) left ? rotateLeft(x.parent) : rotateRight(x.parent) x = root } } x.red = false } fixSentinel() assert((count == 0) == (root == sentinel)) assert(firstNode.predecessor() == nil) assert(lastNode.successor() == nil) } /// Update the value stored at the given index, and return the previous value. /// /// If this is the *first* modification to the tree since creation or copying, invalidates all indices with respect to `self`. /// /// - Complexity: O(1). public mutating func updateValue(value: Value, atIndex index: Index) -> Value { precondition(index._safe, "Cannot update an index that is out of range.") let v = index.node!.value index.node!.value = value return v } /// Replace subtree `u` with subtree `v`. private mutating func transplant(u: Node, with v: Node) { if u.parent == sentinel { root = v } else if u == u.parent.left { u.parent.left = v } else { u.parent.right = v } v.parent = u.parent } /** Perform the following structure conversion: | | x y / \ -> / \ a y x c / \ / \ b c a b */ private mutating func rotateLeft(x: Node) { // ensureUnique() is not called here since this function does not affect any externally visible interface (elements remain in same order, index objects stay valid, etc.) let y = x.right // move b x.right = y.left // set b's parent if y.left != sentinel { y.left.parent = x } y.parent = x.parent // update x's parent if x.parent == sentinel { root = y } // check if x was left or right child and update appropriately else if x == x.parent.left { x.parent.left = y } else { x.parent.right = y } // put x on y's left y.left = x x.parent = y } /// Perform the reverse structure conversion to `rotateLeft`. private mutating func rotateRight(y: Node) { let x = y.left // move b y.left = x.right // set b's parent if x.right != sentinel { x.right.parent = y } x.parent = y.parent // update y's parent if y.parent == sentinel { root = x } // check if y was left or right child and update appropriately else if y == y.parent.left { y.parent.left = x } else { y.parent.right = x } // put y on x's right x.right = y y.parent = x } } extension _RBTree { /// Return the index of the first element with key *not less* than `k`, or `endIndex` if not found. /// /// - Complexity: O(log `count`) @warn_unused_result public func lowerBound(k: Key) -> Index { // early return if the largest element is smaller var nl = lastNode guard k <= nl.key else { return endIndex } var x = root while x != sentinel { if k <= x.key { nl = x x = x.left } else { x = x.right } } assert(k <= nl.key) assert(nl.predecessor() == nil || nl.predecessor()!.key < k) return Index(node: nl) } /// Return the index of the first element with key *greater* than `k`, or `endIndex` if not found. /// /// - Complexity: O(log `count`) @warn_unused_result public func upperBound(k: Key) -> Index { // early return if the largest element is smaller var nl = lastNode guard k < nl.key else { return endIndex } var x = root while x != sentinel { if k < x.key { nl = x x = x.left } else { x = x.right } } assert(k < nl.key) assert(nl.predecessor() == nil || nl.predecessor()!.key <= k) return Index(node: nl) } /// Return the index of the first element with key *equal to* `key`, or `nil` if not found. /// /// - Complexity: O(log `count`) @warn_unused_result public func find(key: Key) -> Index? { let i = lowerBound(key) return i._safe && i.node!.key == key ? i : nil } /// Return whether the tree contains any elements with key `key`. /// /// - Complexity: O(log `count`) @warn_unused_result public func contains(key: Key) -> Bool { return find(key) != nil } /// - Complexity: O(1) public var minKey: Key? { return firstNode.key ?? nil } /// - Complexity: O(1) public var maxKey: Key? { return lastNode.key ?? nil } } extension _RBTree : CollectionType { public typealias Element = (Key, Value) public typealias Index = _RBTreeIndex<Key, Value> /// - Complexity: O(1) public var startIndex: Index { guard firstNode != sentinel else { assert(count == 0 && root == sentinel); return Index(empty: ()) } assert(firstNode.predecessor() == nil) return Index(node: firstNode) } /// - Complexity: O(1) public var endIndex: Index { guard lastNode != sentinel else { assert(count == 0 && root == sentinel); return Index(empty: ()) } assert(lastNode.successor() == nil) return Index(end: lastNode) } /// Access the key at `index`. /// /// - Complexity: O(1) public subscript(index: Index) -> Element { guard case .Node(let u) = index.kind else { preconditionFailure("Cannot subscript an out-of-bounds index.") } return (u.value.key, u.value.value) } } extension _RBTree { /// - Complexity: O(1) public var first: Element? { return firstNode != sentinel ? (firstNode.key, firstNode.value) : nil } /// - Complexity: O(1) public var last: Element? { return lastNode != sentinel ? (lastNode.key, lastNode.value) : nil } } extension _RBTree : ArrayLiteralConvertible { public init(arrayLiteral elements: Element...) { self.init(elements) } }
mit
b7cd294e2ba2f4ffd03ae404e813c9cd
32.903522
177
0.543656
4.180325
false
false
false
false
ikesyo/ReactiveTask
Sources/Task.swift
1
15978
// // Task.swift // ReactiveTask // // Created by Justin Spahr-Summers on 2014-10-10. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation import ReactiveSwift import Result /// Describes how to execute a shell command. public struct Task { /// The path to the executable that should be launched. public var launchPath: String /// Any arguments to provide to the executable. public var arguments: [String] /// The path to the working directory in which the process should be /// launched. /// /// If nil, the launched task will inherit the working directory of its /// parent. public var workingDirectoryPath: String? /// Environment variables to set for the launched process. /// /// If nil, the launched task will inherit the environment of its parent. public var environment: [String: String]? public init(_ launchPath: String, arguments: [String] = [], workingDirectoryPath: String? = nil, environment: [String: String]? = nil) { self.launchPath = launchPath self.arguments = arguments self.workingDirectoryPath = workingDirectoryPath self.environment = environment } /// A GCD group which to wait completion fileprivate static let group = DispatchGroup() /// wait for all task termination public static func waitForAllTaskTermination() { let _ = Task.group.wait(timeout: DispatchTime.distantFuture) } } extension String { private static let whitespaceRegularExpression = try! NSRegularExpression(pattern: "\\s") var escapingWhitespaces: String { return String.whitespaceRegularExpression.stringByReplacingMatches( in: self, range: NSRange(location: 0, length: self.utf16.count), withTemplate: "\\\\$0" ) } } extension Task: CustomStringConvertible { public var description: String { return "\(launchPath) \(arguments.map { $0.escapingWhitespaces }.joined(separator: " "))" } } extension Task: Hashable { public static func == (lhs: Task, rhs: Task) -> Bool { return lhs.launchPath == rhs.launchPath && lhs.arguments == rhs.arguments && lhs.workingDirectoryPath == rhs.workingDirectoryPath && lhs.environment == rhs.environment } public var hashValue: Int { var result = launchPath.hashValue ^ (workingDirectoryPath?.hashValue ?? 0) for argument in arguments { result ^= argument.hashValue } for (key, value) in environment ?? [:] { result ^= key.hashValue ^ value.hashValue } return result } } private func ==<Key: Equatable, Value: Equatable>(lhs: [Key: Value]?, rhs: [Key: Value]?) -> Bool { switch (lhs, rhs) { case let (lhs?, rhs?): return lhs == rhs case (.none, .none): return true default: return false } } /// A private class used to encapsulate a Unix pipe. private final class Pipe { typealias ReadProducer = SignalProducer<Data, TaskError> /// The file descriptor for reading data. let readFD: Int32 /// The file descriptor for writing data. let writeFD: Int32 /// A GCD queue upon which to deliver I/O callbacks. let queue: DispatchQueue /// A GCD group which to wait completion let group: DispatchGroup /// Creates an NSFileHandle corresponding to the `readFD`. The file handle /// will not automatically close the descriptor. var readHandle: FileHandle { return FileHandle(fileDescriptor: readFD, closeOnDealloc: false) } /// Creates an NSFileHandle corresponding to the `writeFD`. The file handle /// will not automatically close the descriptor. var writeHandle: FileHandle { return FileHandle(fileDescriptor: writeFD, closeOnDealloc: false) } /// Initializes a pipe object using existing file descriptors. init(readFD: Int32, writeFD: Int32, queue: DispatchQueue, group: DispatchGroup) { precondition(readFD >= 0) precondition(writeFD >= 0) self.readFD = readFD self.writeFD = writeFD self.queue = queue self.group = group } /// Instantiates a new descriptor pair. class func create(_ queue: DispatchQueue, _ group: DispatchGroup) -> Result<Pipe, TaskError> { var fildes: [Int32] = [ 0, 0 ] if pipe(&fildes) == 0 { return .success(self.init(readFD: fildes[0], writeFD: fildes[1], queue: queue, group: group)) } else { return .failure(.posixError(errno)) } } /// Closes both file descriptors of the receiver. func closePipe() { close(readFD) close(writeFD) } /// Creates a signal that will take ownership of the `readFD` using /// dispatch_io, then read it to completion. /// /// After starting the returned producer, `readFD` should not be used /// anywhere else, as it may close unexpectedly. func transferReadsToProducer() -> ReadProducer { return SignalProducer { observer, disposable in self.group.enter() let channel = DispatchIO(type: .stream, fileDescriptor: self.readFD, queue: self.queue) { error in if error == 0 { observer.sendCompleted() } else if error == ECANCELED { observer.sendInterrupted() } else { observer.send(error: .posixError(error)) } close(self.readFD) self.group.leave() } channel.setLimit(lowWater: 1) channel.read(offset: 0, length: Int.max, queue: self.queue) { (done, dispatchData, error) in if let dispatchData = dispatchData { let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: dispatchData.count) dispatchData.copyBytes(to: bytes, count: dispatchData.count) let data = Data(bytes: bytes, count: dispatchData.count) bytes.deinitialize(count: dispatchData.count) bytes.deallocate(capacity: dispatchData.count) observer.send(value: data) } if error == ECANCELED { observer.sendInterrupted() } else if error != 0 { observer.send(error: .posixError(error)) } if done { channel.close() } } let _ = disposable.add { channel.close(flags: .stop) } } } /// Creates a dispatch_io channel for writing all data that arrives on /// `signal` into `writeFD`, then closes `writeFD` when the input signal /// terminates. /// /// After starting the returned producer, `writeFD` should not be used /// anywhere else, as it may close unexpectedly. /// /// Returns a producer that will complete or error. func writeDataFromProducer(_ producer: SignalProducer<Data, NoError>) -> SignalProducer<(), TaskError> { return SignalProducer { observer, disposable in self.group.enter() let channel = DispatchIO(type: .stream, fileDescriptor: self.writeFD, queue: self.queue) { error in if error == 0 { observer.sendCompleted() } else if error == ECANCELED { observer.sendInterrupted() } else { observer.send(error: .posixError(error)) } close(self.writeFD) self.group.leave() } producer.startWithSignal { signal, producerDisposable in disposable.add(producerDisposable) signal.observe(Observer(value: { data in let dispatchData = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> DispatchData in let buffer = UnsafeBufferPointer(start: bytes, count: data.count) return DispatchData(bytes: buffer) } channel.write(offset: 0, data: dispatchData, queue: self.queue) { (done, data, error) in if error == ECANCELED { observer.sendInterrupted() } else if error != 0 { observer.send(error: .posixError(error)) } } }, completed: { channel.close() }, interrupted: { observer.sendInterrupted() })) } let _ = disposable.add { channel.close(flags: .stop) } } } } public protocol TaskEventType { /// The type of value embedded in a `Success` event. associatedtype T /// The resulting value, if the event is `Success`. var value: T? { get } /// Maps over the value embedded in a `Success` event. func map<U>(_ transform: (T) -> U) -> TaskEvent<U> /// Convenience operator for mapping TaskEvents to SignalProducers. func producerMap<U, Error>(_ transform: (T) -> SignalProducer<U, Error>) -> SignalProducer<TaskEvent<U>, Error> } /// Represents events that can occur during the execution of a task that is /// expected to terminate with a result of type T (upon success). public enum TaskEvent<T>: TaskEventType { /// The task is about to be launched. case launch(Task) /// Some data arrived from the task on `stdout`. case standardOutput(Data) /// Some data arrived from the task on `stderr`. case standardError(Data) /// The task exited successfully (with status 0), and value T was produced /// as a result. case success(T) /// The resulting value, if the event is `Success`. public var value: T? { if case let .success(value) = self { return value } return nil } /// Maps over the value embedded in a `Success` event. public func map<U>(_ transform: (T) -> U) -> TaskEvent<U> { switch self { case let .launch(task): return .launch(task) case let .standardOutput(data): return .standardOutput(data) case let .standardError(data): return .standardError(data) case let .success(value): return .success(transform(value)) } } /// Convenience operator for mapping TaskEvents to SignalProducers. public func producerMap<U, Error>(_ transform: (T) -> SignalProducer<U, Error>) -> SignalProducer<TaskEvent<U>, Error> { switch self { case let .launch(task): return .init(value: .launch(task)) case let .standardOutput(data): return .init(value: .standardOutput(data)) case let .standardError(data): return .init(value: .standardError(data)) case let .success(value): return transform(value).map(TaskEvent<U>.success) } } } extension TaskEvent where T: Equatable { public static func == (lhs: TaskEvent<T>, rhs: TaskEvent<T>) -> Bool { switch (lhs, rhs) { case let (.launch(left), .launch(right)): return left == right case let (.standardOutput(left), .standardOutput(right)): return left == right case let (.standardError(left), .standardError(right)): return left == right case let (.success(left), .success(right)): return left == right default: return false } } } extension TaskEvent: CustomStringConvertible { public var description: String { func dataDescription(_ data: Data) -> String { return String(data: data, encoding: .utf8) ?? data.description } switch self { case let .launch(task): return "launch: \(task)" case let .standardOutput(data): return "stdout: " + dataDescription(data) case let .standardError(data): return "stderr: " + dataDescription(data) case let .success(value): return "success(\(value))" } } } extension SignalProducer where Value: TaskEventType { /// Maps the values inside a stream of TaskEvents into new SignalProducers. public func flatMapTaskEvents<U>(_ strategy: FlattenStrategy, transform: @escaping (Value.T) -> SignalProducer<U, Error>) -> SignalProducer<TaskEvent<U>, Error> { return self.flatMap(strategy) { taskEvent in return taskEvent.producerMap(transform) } } /// Ignores incremental standard output and standard error data from the given /// task, sending only a single value with the final, aggregated result. public func ignoreTaskData() -> SignalProducer<Value.T, Error> { return lift { $0.ignoreTaskData() } } } extension Signal where Value: TaskEventType { /// Ignores incremental standard output and standard error data from the given /// task, sending only a single value with the final, aggregated result. public func ignoreTaskData() -> Signal<Value.T, Error> { return self.filterMap { $0.value } } } extension Task { /// Launches a new shell task. /// /// - Parameters: /// - standardInput: Data to stream to standard input of the launched process. If nil, stdin will /// be inherited from the parent process. /// /// - Returns: A producer that will launch the receiver when started, then send /// `TaskEvent`s as execution proceeds. public func launch(standardInput: SignalProducer<Data, NoError>? = nil) -> SignalProducer<TaskEvent<Data>, TaskError> { return SignalProducer { observer, disposable in let queue = DispatchQueue(label: self.description, attributes: []) let group = Task.group let process = Process() process.launchPath = self.launchPath process.arguments = self.arguments if let cwd = self.workingDirectoryPath { process.currentDirectoryPath = cwd } if let env = self.environment { process.environment = env } var stdinProducer: SignalProducer<(), TaskError> = .empty if let input = standardInput { switch Pipe.create(queue, group) { case let .success(pipe): process.standardInput = pipe.readHandle stdinProducer = pipe.writeDataFromProducer(input).on(started: { close(pipe.readFD) }) case let .failure(error): observer.send(error: error) return } } SignalProducer(result: Pipe.create(queue, group).fanout(Pipe.create(queue, group))) .flatMap(.merge) { stdoutPipe, stderrPipe -> SignalProducer<TaskEvent<Data>, TaskError> in let stdoutProducer = stdoutPipe.transferReadsToProducer() let stderrProducer = stderrPipe.transferReadsToProducer() enum Aggregation { case value(Data) case failed(TaskError) case interrupted var producer: Pipe.ReadProducer { switch self { case let .value(data): return .init(value: data) case let .failed(error): return .init(error: error) case .interrupted: return SignalProducer { observer, _ in observer.sendInterrupted() } } } } return SignalProducer { observer, disposable in func startAggregating(producer: Pipe.ReadProducer, chunk: @escaping (Data) -> TaskEvent<Data>) -> Pipe.ReadProducer { let aggregated = MutableProperty<Aggregation?>(nil) producer.startWithSignal { signal, signalDisposable in disposable += signalDisposable var aggregate = Data() signal.observe(Observer(value: { data in observer.send(value: chunk(data)) aggregate.append(data) }, failed: { error in observer.send(error: error) aggregated.value = .failed(error) }, completed: { aggregated.value = .value(aggregate) }, interrupted: { aggregated.value = .interrupted })) } return aggregated.producer .skipNil() .flatMap(.concat) { $0.producer } } let stdoutAggregated = startAggregating(producer: stdoutProducer, chunk: TaskEvent.standardOutput) let stderrAggregated = startAggregating(producer: stderrProducer, chunk: TaskEvent.standardError) process.standardOutput = stdoutPipe.writeHandle process.standardError = stderrPipe.writeHandle group.enter() process.terminationHandler = { nstask in let terminationStatus = nstask.terminationStatus if terminationStatus == EXIT_SUCCESS { // Wait for stderr to finish, then pass // through stdout. disposable += stderrAggregated .then(stdoutAggregated) .map(TaskEvent.success) .start(observer) } else { // Wait for stdout to finish, then pass // through stderr. disposable += stdoutAggregated .then(stderrAggregated) .flatMap(.concat) { data -> SignalProducer<TaskEvent<Data>, TaskError> in let errorString = (data.count > 0 ? String(data: data, encoding: .utf8) : nil) return SignalProducer(error: .shellTaskFailed(self, exitCode: terminationStatus, standardError: errorString)) } .start(observer) } group.leave() } observer.send(value: .launch(self)) process.launch() close(stdoutPipe.writeFD) close(stderrPipe.writeFD) disposable += stdinProducer.start() let _ = disposable.add { process.terminate() } } } .startWithSignal { signal, taskDisposable in disposable.add(taskDisposable) signal.observe(observer) } } } }
mit
e7601cec17fb5ff1c8ca18f440a0a05e
28.643785
163
0.679747
3.824318
false
false
false
false
resmio/SignificantSpices
SignificantSpicesTests/SwiftExtensions/Extensions/Sequence/Sequence (firstNfulfilling).swift
1
708
// // Sequence (firstNfulfilling).swift // SignificantSpices // // Created by Jan Nash on 8/14/17. // Copyright © 2017 resmio. All rights reserved. // import XCTest import SignificantSpices class SequenceFirstNfulfillingTests: XCTestCase { func testSequenceFirstNfulfilling0() { let s: [Int] = [] let gt4: (Int) -> Bool = { $0 > 4 } let c: [Int] = s.first(3, fulfilling: gt4) XCTAssertTrue(c.isEmpty) } func testSequenceFirstNfulfilling1() { let s: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9] let gt4: (Int) -> Bool = { $0 > 4 } let c: [Int] = s.first(3, fulfilling: gt4) XCTAssertEqual(c, [5, 6, 7]) } }
mit
5c77423d1a4649ee8cbf3e3cf055ecf7
23.37931
50
0.560113
3.15625
false
true
false
false
HaliteChallenge/Halite-II
airesources/Swift/Sources/hlt/TokenStack.swift
1
319
import Foundation class TokenStack { let tokens: [String] var idx = 0 init(_ tokens: [String]) { self.tokens = tokens } func pop() -> String { defer { idx += 1 } return tokens[idx] } func isEmpty() -> Bool { return idx == tokens.count } }
mit
636f5e16b4dc5ca38d4a8e959b064736
15.789474
34
0.492163
4.089744
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CodeBuild/CodeBuild_Paginator.swift
1
32898
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension CodeBuild { /// Retrieves one or more code coverage reports. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeCodeCoveragesPaginator<Result>( _ input: DescribeCodeCoveragesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeCodeCoveragesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeCodeCoverages, tokenKey: \DescribeCodeCoveragesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeCodeCoveragesPaginator( _ input: DescribeCodeCoveragesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeCodeCoveragesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeCodeCoverages, tokenKey: \DescribeCodeCoveragesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of details about test cases for a report. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeTestCasesPaginator<Result>( _ input: DescribeTestCasesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeTestCasesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeTestCases, tokenKey: \DescribeTestCasesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeTestCasesPaginator( _ input: DescribeTestCasesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeTestCasesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeTestCases, tokenKey: \DescribeTestCasesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Retrieves the identifiers of your build batches in the current region. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBuildBatchesPaginator<Result>( _ input: ListBuildBatchesInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBuildBatchesOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBuildBatches, tokenKey: \ListBuildBatchesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBuildBatchesPaginator( _ input: ListBuildBatchesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBuildBatchesOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBuildBatches, tokenKey: \ListBuildBatchesOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Retrieves the identifiers of the build batches for a specific project. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBuildBatchesForProjectPaginator<Result>( _ input: ListBuildBatchesForProjectInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBuildBatchesForProjectOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBuildBatchesForProject, tokenKey: \ListBuildBatchesForProjectOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBuildBatchesForProjectPaginator( _ input: ListBuildBatchesForProjectInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBuildBatchesForProjectOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBuildBatchesForProject, tokenKey: \ListBuildBatchesForProjectOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of build IDs, with each build ID representing a single build. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBuildsPaginator<Result>( _ input: ListBuildsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBuildsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBuilds, tokenKey: \ListBuildsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBuildsPaginator( _ input: ListBuildsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBuildsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBuilds, tokenKey: \ListBuildsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of build IDs for the specified build project, with each build ID representing a single build. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listBuildsForProjectPaginator<Result>( _ input: ListBuildsForProjectInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListBuildsForProjectOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listBuildsForProject, tokenKey: \ListBuildsForProjectOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listBuildsForProjectPaginator( _ input: ListBuildsForProjectInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListBuildsForProjectOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listBuildsForProject, tokenKey: \ListBuildsForProjectOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of build project names, with each build project name representing a single build project. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listProjectsPaginator<Result>( _ input: ListProjectsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListProjectsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listProjects, tokenKey: \ListProjectsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listProjectsPaginator( _ input: ListProjectsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListProjectsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listProjects, tokenKey: \ListProjectsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list ARNs for the report groups in the current AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listReportGroupsPaginator<Result>( _ input: ListReportGroupsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListReportGroupsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listReportGroups, tokenKey: \ListReportGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listReportGroupsPaginator( _ input: ListReportGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListReportGroupsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listReportGroups, tokenKey: \ListReportGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of ARNs for the reports in the current AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listReportsPaginator<Result>( _ input: ListReportsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListReportsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listReports, tokenKey: \ListReportsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listReportsPaginator( _ input: ListReportsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListReportsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listReports, tokenKey: \ListReportsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of ARNs for the reports that belong to a ReportGroup. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listReportsForReportGroupPaginator<Result>( _ input: ListReportsForReportGroupInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListReportsForReportGroupOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listReportsForReportGroup, tokenKey: \ListReportsForReportGroupOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listReportsForReportGroupPaginator( _ input: ListReportsForReportGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListReportsForReportGroupOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listReportsForReportGroup, tokenKey: \ListReportsForReportGroupOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of projects that are shared with other AWS accounts or users. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSharedProjectsPaginator<Result>( _ input: ListSharedProjectsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSharedProjectsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSharedProjects, tokenKey: \ListSharedProjectsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSharedProjectsPaginator( _ input: ListSharedProjectsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSharedProjectsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSharedProjects, tokenKey: \ListSharedProjectsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Gets a list of report groups that are shared with other AWS accounts or users. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSharedReportGroupsPaginator<Result>( _ input: ListSharedReportGroupsInput, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSharedReportGroupsOutput, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSharedReportGroups, tokenKey: \ListSharedReportGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSharedReportGroupsPaginator( _ input: ListSharedReportGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSharedReportGroupsOutput, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSharedReportGroups, tokenKey: \ListSharedReportGroupsOutput.nextToken, on: eventLoop, onPage: onPage ) } } extension CodeBuild.DescribeCodeCoveragesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.DescribeCodeCoveragesInput { return .init( maxLineCoveragePercentage: self.maxLineCoveragePercentage, maxResults: self.maxResults, minLineCoveragePercentage: self.minLineCoveragePercentage, nextToken: token, reportArn: self.reportArn, sortBy: self.sortBy, sortOrder: self.sortOrder ) } } extension CodeBuild.DescribeTestCasesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.DescribeTestCasesInput { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token, reportArn: self.reportArn ) } } extension CodeBuild.ListBuildBatchesInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListBuildBatchesInput { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token, sortOrder: self.sortOrder ) } } extension CodeBuild.ListBuildBatchesForProjectInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListBuildBatchesForProjectInput { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token, projectName: self.projectName, sortOrder: self.sortOrder ) } } extension CodeBuild.ListBuildsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListBuildsInput { return .init( nextToken: token, sortOrder: self.sortOrder ) } } extension CodeBuild.ListBuildsForProjectInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListBuildsForProjectInput { return .init( nextToken: token, projectName: self.projectName, sortOrder: self.sortOrder ) } } extension CodeBuild.ListProjectsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListProjectsInput { return .init( nextToken: token, sortBy: self.sortBy, sortOrder: self.sortOrder ) } } extension CodeBuild.ListReportGroupsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListReportGroupsInput { return .init( maxResults: self.maxResults, nextToken: token, sortBy: self.sortBy, sortOrder: self.sortOrder ) } } extension CodeBuild.ListReportsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListReportsInput { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token, sortOrder: self.sortOrder ) } } extension CodeBuild.ListReportsForReportGroupInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListReportsForReportGroupInput { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token, reportGroupArn: self.reportGroupArn, sortOrder: self.sortOrder ) } } extension CodeBuild.ListSharedProjectsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListSharedProjectsInput { return .init( maxResults: self.maxResults, nextToken: token, sortBy: self.sortBy, sortOrder: self.sortOrder ) } } extension CodeBuild.ListSharedReportGroupsInput: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CodeBuild.ListSharedReportGroupsInput { return .init( maxResults: self.maxResults, nextToken: token, sortBy: self.sortBy, sortOrder: self.sortOrder ) } }
apache-2.0
aad3ca173bc60c958570fcd4825901dd
41.947781
168
0.642015
5.023362
false
false
false
false
SeptAi/Cooperate
Cooperate/Cooperate/Class/View/Main/visitor/VisitorView.swift
1
10052
// // VisitorView.swift // Cooperation // // Created by J on 2016/12/26. // Copyright © 2016年 J. All rights reserved. // import UIKit class VisitorView: UIView { // MARK: - 属性 /// 注册按钮 lazy var registerButton: UIButton = UIButton.cz_textButton( "注册", fontSize: 16, normalColor: UIColor.orange, highlightedColor: UIColor.black, backgroundImageName: "common_button_white_disable") /// 登录按钮 lazy var loginButton: UIButton = UIButton.cz_textButton( "登录", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.black, backgroundImageName: "common_button_white_disable") /// 访客视图的信息字典 [imageName / message] /// 如果是首页 imageName == "" var visitorInfo: [String: String]?{ didSet{ // 1.取字典信息 guard let imageName = visitorInfo?["imageName"], let message = visitorInfo?["message"] else { return } // 2.设置消息 tipLabel.text = message // 3.设置图像,首页特殊处理 if imageName == ""{ startAnimation() return } iconView.image = UIImage(named: imageName) // 其他控制器无需设置小房子/遮罩视图 houseIconView.isHidden = true maskIconView.isHidden = true } } // MARK: - 私有控件 /// 懒加载属性只有调用 UIKit 控件的指定构造函数,其他都需要使用类型 /// 图像视图 lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) /// 遮罩图像 - 不要使用 maskView lazy var maskIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) /// 小房子 lazy var houseIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) /// 提示标签 lazy var tipLabel: UILabel = UILabel.cz_label( withText: "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜", fontSize: 14, color: UIColor.darkGray) // MARK: - 方法 /// 旋转图标动画(首页) private func startAnimation() { let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2 * M_PI anim.repeatCount = MAXFLOAT anim.duration = 15 // 动画完成不删除,如果 iconView 被释放,动画会一起销毁! // 在设置连续播放的动画非常有用! anim.isRemovedOnCompletion = false // 将动画添加到图层 iconView.layer.add(anim, forKey: nil) } // MARK: - 系统 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 布局 extension VisitorView{ /// 设置界面 func setupUI(){ // 0. 在开发的时候,如果能够使用颜色,就不要使用图像,效率会更高! backgroundColor = UIColor.cz_color(withHex: 0xEDEDED) // 1. 添加控件 addSubview(iconView) addSubview(maskIconView) addSubview(houseIconView) addSubview(tipLabel) addSubview(registerButton) addSubview(loginButton) // 2.文本居中 tipLabel.textAlignment = .center // 3.自动布局 // 3.1取消autoresizing for v in subviews{ v.translatesAutoresizingMaskIntoConstraints = false } // 3.2AutoLayout let margin: CGFloat = 20.0 // 图像视图 addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: -60)) // 小房子 addConstraint(NSLayoutConstraint(item: houseIconView, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: houseIconView, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1.0, constant: 0)) // 提示标签 addConstraint(NSLayoutConstraint(item: tipLabel, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: tipLabel, attribute: .top, relatedBy: .equal, toItem: iconView, attribute: .bottom, multiplier: 1.0, constant: margin)) addConstraint(NSLayoutConstraint(item: tipLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 236)) // 注册按钮 addConstraint(NSLayoutConstraint(item: registerButton, attribute: .left, relatedBy: .equal, toItem: tipLabel, attribute: .left, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: registerButton, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1.0, constant: margin)) addConstraint(NSLayoutConstraint(item: registerButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)) // 登录按钮 addConstraint(NSLayoutConstraint(item: loginButton, attribute: .right, relatedBy: .equal, toItem: tipLabel, attribute: .right, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: tipLabel, attribute: .bottom, multiplier: 1.0, constant: margin)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: .width, relatedBy: .equal, toItem: registerButton, attribute: .width, multiplier: 1.0, constant: 0)) // 遮罩图像 let viewDict = ["maskIconView":maskIconView,"registerButton":registerButton] as [String:Any] let metrics = ["spacing":20] addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[maskIconView]-0-|", options: [], metrics: nil, views: viewDict)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[maskIconView]-(spacing)-[registerButton]", options: [], metrics: metrics, views: viewDict)) } }
mit
eea1ce557eeab2c0fdcfc3112e63033c
39.733906
114
0.414814
6.491792
false
false
false
false
calleerlandsson/Tofu
Tofu/AccountCreationViewController.swift
1
4261
import UIKit private let formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .none return formatter }() class AccountCreationViewController: UITableViewController, AlgorithmSelectionDelegate { @IBOutlet weak var doneItem: UIBarButtonItem! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var issuerField: UITextField! @IBOutlet weak var secretField: UITextField! @IBOutlet weak var algorithmLabel: UILabel! @IBOutlet weak var eightDigitsSwitch: UISwitch! @IBOutlet weak var timeBasedSwitch: UISwitch! @IBOutlet weak var periodCounterCell: UITableViewCell! @IBOutlet weak var periodCounterLabel: UILabel! @IBOutlet weak var periodCounterField: UITextField! var delegate: AccountCreationDelegate? private var algorithm = Algorithm.sha1 private var periodString: String? private var counterString: String? private var period: Int? { guard periodCounterField.text?.count ?? 0 > 0 else { return 30 } return formatter.number(from: periodCounterField.text!)?.intValue } private var counter: Int? { guard periodCounterField.text?.count ?? 0 > 0 else { return 0 } return formatter.number(from: periodCounterField.text!)?.intValue } @IBAction func didPressCancel(_ sender: UIBarButtonItem) { presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func didPressDone(_ sender: UIBarButtonItem) { let password = Password() password.timeBased = timeBasedSwitch.isOn password.algorithm = algorithm password.digits = eightDigitsSwitch.isOn ? 8 : 6 password.secret = Data(base32Encoded: secretField.text!)! if timeBasedSwitch.isOn { password.period = period! } else { password.counter = counter! } let account = Account() account.name = nameField.text account.issuer = issuerField.text account.password = password presentingViewController?.dismiss(animated: true) { self.delegate?.createAccount(account) } } @IBAction func editingChangedForTextField(_ textField: UITextField) { validate() } @IBAction func valueChangedForTimeBasedSwitch() { if self.timeBasedSwitch.isOn { counterString = periodCounterField.text } else { periodString = periodCounterField.text } UIView.transition(with: periodCounterCell, duration: 0.2, options: .transitionCrossDissolve, animations: { if self.timeBasedSwitch.isOn { self.periodCounterLabel.text = "Period" self.periodCounterField.placeholder = String(30) self.periodCounterField.text = self.periodString } else { self.periodCounterLabel.text = "Counter" self.periodCounterField.placeholder = String(0) self.periodCounterField.text = self.counterString } }, completion: { _ in self.validate() }) } override func viewDidLoad() { super.viewDidLoad() nameField.becomeFirstResponder() algorithmLabel.text = algorithm.name } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let algorithmsController = segue.destination as? AlgorithmsViewController { algorithmsController.algorithms = [.sha1, .sha256, .sha512] algorithmsController.selected = algorithm algorithmsController.delegate = self } } private func validate() { doneItem.isEnabled = secretField.text?.count ?? 0 > 0 && Data(base32Encoded: secretField.text!) != nil && (timeBasedSwitch.isOn ? period != nil : counter != nil) } // MARK: AlgorithmSelectionDelegate func selectAlgorithm(_ algorithm: Algorithm) { self.algorithm = algorithm algorithmLabel.text = algorithm.name } }
isc
cccae442116e2f04890e15449535605e
36.377193
88
0.623093
5.247537
false
false
false
false
NijiDigital/NetworkStack
Example/MoyaComparison/MoyaComparison/Utils/MCLogger+LogModule.swift
1
2064
// // Copyright 2017 niji // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import SwiftyBeaver public enum LogModule: String { case appCoordinator case githubProvider case webServiceClient case parsing case encoding } extension LogModule { public func verbose(_ message: @autoclosure @escaping () -> Any, _ path: String = #file, _ function: String = #function, line: Int = #line) { SwiftyBeaver.verbose({ return "[\(self.rawValue)] - \(message())" as Any}(), path, function, line: line) } public func debug(_ message: @autoclosure @escaping () -> Any, _ path: String = #file, _ function: String = #function, line: Int = #line) { SwiftyBeaver.debug({ return "[\(self.rawValue)] - \(message())" as Any}(), path, function, line: line) } public func info(_ message: @autoclosure @escaping () -> Any, _ path: String = #file, _ function: String = #function, line: Int = #line) { SwiftyBeaver.info({ return "[\(self.rawValue)] - \(message())" as Any}(), path, function, line: line) } public func warning(_ message: @autoclosure @escaping () -> Any, _ path: String = #file, _ function: String = #function, line: Int = #line) { SwiftyBeaver.warning({ return "[\(self.rawValue)] - \(message())" as Any}(), path, function, line: line) } public func error(_ message: @autoclosure @escaping () -> Any, _ path: String = #file, _ function: String = #function, line: Int = #line) { SwiftyBeaver.error({ return "[\(self.rawValue)] - \(message())" as Any}(), path, function, line: line) } }
apache-2.0
7c66333ac336d882cb28c9904a56736d
42
143
0.671027
3.946463
false
false
false
false
mrudulp/iOSSrc
swiftNotify/swiftNotify/AppDelegate.swift
2
3420
// // AppDelegate.swift // swiftNotify // // Created by Mrudul P on 12/02/15. // Copyright (c) 2015 Mrudul P. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //Registering For Notification let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound let acceptAction = UIMutableUserNotificationAction() acceptAction.identifier = "Accept" acceptAction.title = "Accept" acceptAction.activationMode = UIUserNotificationActivationMode.Background acceptAction.destructive = false acceptAction.authenticationRequired = false let declineAction = UIMutableUserNotificationAction() declineAction.identifier = "Decline" declineAction.title = "Decline" declineAction.activationMode = UIUserNotificationActivationMode.Background declineAction.destructive = false declineAction.authenticationRequired = false let category = UIMutableUserNotificationCategory() category.identifier = "invite" category.setActions([acceptAction,declineAction], forContext: UIUserNotificationActionContext.Default) let catergories = NSSet(array: [category]) let settings = UIUserNotificationSettings(forTypes: notificationType, categories: catergories) application.registerUserNotificationSettings(settings) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
4c001869a55a9d5bdbe549297dd26dfd
46.5
285
0.741228
5.79661
false
false
false
false
AboutCXJ/30DaysOfSwift
Project 12 - LoginAnimation/Project 12 - LoginAnimation/ViewController.swift
1
2511
// // ViewController.swift // Project 12 - LoginAnimation // // Created by sfzx on 2017/10/19. // Copyright © 2017年 陈鑫杰. All rights reserved. // import UIKit let screenWidth = UIScreen.main.bounds.size.width let screenHeight = UIScreen.main.bounds.size.height class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setupUI() } func setupUI() { self.navigationController?.navigationBar.barStyle = .black self.navigationController?.navigationBar.isHidden = true self.view.backgroundColor = UIColor(red: 28/255.0, green: 155/255.0, blue: 5/255.0, alpha: 1.0) self.view.addSubview(loginBtn) self.view.addSubview(signUPBtn) self.view.addSubview(logoView) } override var preferredStatusBarStyle: UIStatusBarStyle{ get{ return UIStatusBarStyle.lightContent } } @objc func goLoginVC() { self.navigationController?.pushViewController(LoginViewController(), animated: true) } // MARK: - 懒加载 //登录按钮 lazy var loginBtn: UIButton = { let loginBtn = UIButton(frame: CGRect(x: 30, y: screenHeight - 130, width: screenWidth - 60, height: 45)) loginBtn.backgroundColor = UIColor(red: 23/255.0, green: 139/255.0, blue: 3/255.0, alpha: 1.0) loginBtn.layer.cornerRadius = 4 loginBtn.layer.masksToBounds = true loginBtn.setTitleColor(.white, for: .normal) loginBtn.setTitle("Login", for: .normal) loginBtn.addTarget(self, action: #selector(goLoginVC), for: .touchUpInside) return loginBtn }() //注册按钮 lazy var signUPBtn: UIButton = { let signUPBtn = UIButton(frame: CGRect(x: 30, y: screenHeight - 65, width: screenWidth - 60, height: 45)) signUPBtn.backgroundColor = .white signUPBtn.layer.cornerRadius = 4 signUPBtn.layer.masksToBounds = true signUPBtn.setTitleColor(UIColor(red: 23/255.0, green: 164/255.0, blue: 5/255.0, alpha: 1.0), for: .normal) signUPBtn.setTitle("Sign Up", for: .normal) return signUPBtn }() //logo lazy var logoView: UIImageView = { let logoView = UIImageView(frame: CGRect(x: 20, y: 60, width: screenWidth - 40, height: 80)) logoView.contentMode = .scaleAspectFit logoView.image = UIImage(named: "logo") return logoView }() }
mit
9591b2756467bdb9a5cdd6e6f80bb83c
28.879518
114
0.631452
4.112769
false
false
false
false
samodom/TestableUIKit
TestableUIKit/UIResponder/UIViewController/UITabBarController/UITabBarControllerSetViewControllersSpy.swift
1
4121
// // UITabBarControllerSetViewControllersSpy.swift // TestableUIKit // // Created by Sam Odom on 2/25/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import TestSwagger import FoundationSwagger public extension UITabBarController { private static let setViewControllersCalledString = UUIDKeyString() private static let setViewControllersCalledKey = ObjectAssociationKey(setViewControllersCalledString) private static let setViewControllersCalledReference = SpyEvidenceReference(key: setViewControllersCalledKey) private static let setViewControllersControllersString = UUIDKeyString() private static let setViewControllersControllersKey = ObjectAssociationKey(setViewControllersControllersString) private static let setViewControllersControllersReference = SpyEvidenceReference(key: setViewControllersControllersKey) private static let setViewControllersAnimatedString = UUIDKeyString() private static let setViewControllersAnimatedKey = ObjectAssociationKey(setViewControllersAnimatedString) private static let setViewControllersAnimatedReference = SpyEvidenceReference(key: setViewControllersAnimatedKey) /// Spy controller for ensuring a tab bar controller has had its implementation of /// `setViewControllers(_:animated:)` invoked. public enum SetViewControllersSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITabBarController.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(UITabBarController.setViewControllers(_:animated:)), spy: #selector(UITabBarController.spy_setViewControllers(_:animated:)) ) ] as Set public static let evidence = [ setViewControllersCalledReference, setViewControllersControllersReference, setViewControllersAnimatedReference ] as Set public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of /// `setViewControllers(_:direction:animated:completion:)` public func spy_setViewControllers(_ controllers: [UIViewController]?, animated: Bool) { setViewControllersCalled = true setViewControllersControllers = controllers setViewControllersAnimated = animated spy_setViewControllers(controllers, animated: animated) } /// Indicates whether the `setViewControllers(_:animated:)` method has been called /// on this object. public final var setViewControllersCalled: Bool { get { return loadEvidence(with: UITabBarController.setViewControllersCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UITabBarController.setViewControllersCalledReference) } } /// Provides the view controllers passed to /// `setViewControllers(_:animated:)` if called. public final var setViewControllersControllers: [UIViewController]? { get { return loadEvidence(with: UITabBarController.setViewControllersControllersReference) as? [UIViewController] } set { let reference = UITabBarController.setViewControllersControllersReference guard let controllers = newValue else { return removeEvidence(with: reference) } saveEvidence(controllers, with: reference) } } /// Provides the animation flag passed to `setViewControllers(_:animated:)` /// if called. public final var setViewControllersAnimated: Bool? { get { return loadEvidence(with: UITabBarController.setViewControllersAnimatedReference) as? Bool } set { let reference = UITabBarController.setViewControllersAnimatedReference guard let animated = newValue else { return removeEvidence(with: reference) } saveEvidence(animated, with: reference) } } }
mit
837ae9408a58a0b57e97d21670d8b079
38.615385
123
0.711165
6.529319
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/Utility/Media/MediaVideoExporter.swift
2
8342
import Foundation import MobileCoreServices /// Media export handling of Videos from PHAssets or AVAssets. /// class MediaVideoExporter: MediaExporter { var mediaDirectoryType: MediaDirectory = .uploads /// Export options. /// var options = Options() /// Available options for a video export. /// struct Options: MediaExportingOptions { /// The export preset to use when exporting a video, see AVAssetExportSession documentation. /// var exportPreset = AVAssetExportPresetHighestQuality /// The preferred UTType of the output video file. /// /// - Note: the exporter will try to honor the type, /// if both the exporter and AVAsset support the type for exporting. /// var preferredExportVideoType: String? // MARK: - MediaExporting var stripsGeoLocationIfNeeded = false } /// Completion block with a MediaVideoExport. /// typealias OnVideoExport = (MediaVideoExport) -> Void public enum VideoExportError: MediaExportError { case videoAssetWasDetectedAsNotExportable case videoExportSessionDoesNotSupportVideoOutputType case failedToInitializeVideoExportSession case failedExportingVideoDuringExportSession case failedGeneratingVideoPreviewImage var description: String { switch self { case .failedGeneratingVideoPreviewImage: return NSLocalizedString("Video Preview Unavailable", comment: "Message shown if a video preview image is unavailable while the video is being uploaded.") default: return NSLocalizedString("The video could not be added to the Media Library.", comment: "Message shown when a video failed to load while trying to add it to the Media library.") } } } /// Exports a known video at a URL asynchronously. /// func exportVideo(atURL url: URL, onCompletion: @escaping OnVideoExport, onError: @escaping OnExportError) { do { let asset = AVURLAsset(url: url) guard asset.isExportable else { throw VideoExportError.videoAssetWasDetectedAsNotExportable } guard let session = AVAssetExportSession(asset: asset, presetName: options.exportPreset) else { throw VideoExportError.failedToInitializeVideoExportSession } exportVideo(with: session, filename: url.lastPathComponent, onCompletion: onCompletion, onError: onError) } catch { onError(exporterErrorWith(error: error)) } } /// Configures an AVAssetExportSession and exports the video asynchronously. /// func exportVideo(with session: AVAssetExportSession, filename: String?, onCompletion: @escaping OnVideoExport, onError: @escaping OnExportError) { do { var outputType = options.preferredExportVideoType ?? supportedExportFileTypes.first! // Check if the exportFileType is one of the supported types for the exportSession. if session.supportedFileTypes.contains(outputType) == false { /* If it is not supported by the session, try and find one of the exporter's own supported types within the session's. Ideally we return the first type, as an order of preference from supportedExportFileTypes. */ guard let supportedType = supportedExportFileTypes.first(where: { session.supportedFileTypes.contains($0) }) else { // No supported types available, throw an error. throw VideoExportError.videoExportSessionDoesNotSupportVideoOutputType } outputType = supportedType } // Generate a URL for exported video. let mediaURL = try mediaFileManager.makeLocalMediaURL(withFilename: filename ?? "video", fileExtension: URL.fileExtensionForUTType(outputType)) session.outputURL = mediaURL session.outputFileType = outputType session.shouldOptimizeForNetworkUse = true // Configure metadata filter for sharing, if we need to remove location data. if options.stripsGeoLocationIfNeeded { session.metadataItemFilter = AVMetadataItemFilter.forSharing() } session.exportAsynchronously { guard session.status == .completed else { if let error = session.error { onError(self.exporterErrorWith(error: error)) } else { onError(VideoExportError.failedExportingVideoDuringExportSession) } return } onCompletion(MediaVideoExport(url: mediaURL, fileSize: mediaURL.resourceFileSize, duration: session.asset.duration.seconds)) } } catch { onError(exporterErrorWith(error: error)) } } /// Generate and export a preview image for a known video at the URL, local file or remote resource. /// /// - Note: Generates the image asynchronously and could potentially take a bit. /// /// - imageOptions: ImageExporter options for the generated thumbnail image. /// func exportPreviewImageForVideo(atURL url: URL, imageOptions: MediaImageExporter.Options?, onCompletion: @escaping MediaImageExporter.OnImageExport, onError: @escaping OnExportError) { do { let asset = AVURLAsset(url: url) guard asset.isExportable else { throw VideoExportError.videoAssetWasDetectedAsNotExportable } let generator = AVAssetImageGenerator(asset: asset) if let imageOptions = imageOptions, let maxSize = imageOptions.maximumImageSize { generator.maximumSize = CGSize(width: maxSize, height: maxSize) } generator.appliesPreferredTrackTransform = true generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: CMTimeMake(0, 1))], completionHandler: { (time, cgImage, actualTime, result, error) in guard let cgImage = cgImage else { onError(VideoExportError.failedGeneratingVideoPreviewImage) return } let image = UIImage(cgImage: cgImage) let exporter = MediaImageExporter() if let imageOptions = imageOptions { exporter.options = imageOptions } exporter.mediaDirectoryType = self.mediaDirectoryType exporter.exportImage(image, fileName: UUID().uuidString, onCompletion: onCompletion, onError: onError) }) } catch { onError(exporterErrorWith(error: error)) } } /// Returns the supported UTType identifiers for the video exporter. /// /// - Note: This particular list is for the intention of uploading /// exported videos to WordPress, and what WordPress itself supports. /// fileprivate var supportedExportFileTypes: [String] { let types = [ kUTTypeMPEG4, kUTTypeQuickTimeMovie, kUTTypeMPEG, kUTTypeAVIMovie ] return types as [String] } }
gpl-2.0
e6c6573e796dac5d8fc30c2bc269085e
46.397727
193
0.564253
6.387443
false
false
false
false
Syerram/asphalos
asphalos/FormValueCell.swift
1
2637
// // FormValueCell.swift // SwiftForms // // Created by Miguel Ángel Ortuño Ortuño on 13/11/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit class FormValueCell: FormBaseCell { /// MARK: Cell views let titleLabel = UILabel() let valueLabel = UILabel() /// MARK: Properties private var customConstraints: [AnyObject]! /// MARK: FormBaseCell override func configure() { super.configure() accessoryType = .DisclosureIndicator titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) valueLabel.setTranslatesAutoresizingMaskIntoConstraints(false) titleLabel.font = UIFont(name: Globals.Theme.RegularFont, size: 16) valueLabel.font = UIFont(name: Globals.Theme.RegularFont, size: 16) valueLabel.textColor = UIColor.lightGrayColor() valueLabel.textAlignment = .Right contentView.addSubview(titleLabel) contentView.addSubview(valueLabel) titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) titleLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) // apply constant constraints contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) } override func constraintsViews() -> [String : UIView] { return ["titleLabel" : titleLabel, "valueLabel" : valueLabel] } override func defaultVisualConstraints() -> [String] { // apply default constraints var rightPadding = 0 if accessoryType == .None { rightPadding = 16 } if titleLabel.text != nil && count(titleLabel.text!) > 0 { return ["H:|-16-[titleLabel]-[valueLabel]-\(rightPadding)-|"] } else { return ["H:|-16-[valueLabel]-\(rightPadding)-|"] } } }
mit
9b1bbdb923bdeb789ce11367db5e64a1
36.614286
185
0.653627
5.092843
false
false
false
false
groue/GRDB.swift
GRDB/Record/Record.swift
1
14518
// MARK: - Record /// A base class for types that can be fetched and persisted in the database. /// /// ## Topics /// /// ### Creating Record Instances /// /// - ``init()`` /// - ``init(row:)`` /// /// ### Encoding a Database Row /// /// - ``encode(to:)`` /// /// ### Changes Tracking /// /// - ``databaseChanges`` /// - ``hasDatabaseChanges`` /// - ``updateChanges(_:)`` /// /// ### Persistence Callbacks /// /// - ``willSave(_:)`` /// - ``willInsert(_:)`` /// - ``willUpdate(_:columns:)`` /// - ``willDelete(_:)`` /// - ``didSave(_:)`` /// - ``didInsert(_:)`` /// - ``didUpdate(_:)`` /// - ``didDelete(deleted:)`` /// - ``aroundSave(_:save:)`` /// - ``aroundInsert(_:insert:)`` /// - ``aroundUpdate(_:columns:update:)`` /// - ``aroundDelete(_:delete:)`` open class Record { // MARK: - Initializers /// Creates a Record. public init() { } /// Creates a Record from a row. public required init(row: Row) throws { if row.isFetched { // Take care of the hasDatabaseChanges flag. // // Row may be a reused row which will turn invalid as soon as the // SQLite statement is iterated. We need to store an // immutable copy. referenceRow = row.copy() } } // MARK: - Core methods /// The name of the database table used to build SQL queries. /// /// Subclasses must override this method. For example: /// /// ```swift /// class Player: Record { /// override class var databaseTableName: String { /// return "player" /// } /// } /// ``` /// /// - returns: The name of a database table. open class var databaseTableName: String { // Programmer error fatalError("subclass must override") } open class var persistenceConflictPolicy: PersistenceConflictPolicy { PersistenceConflictPolicy(insert: .abort, update: .abort) } /// The columns selected by the record. /// /// By default, all columns are selected: /// /// ```swift /// class Player: Record { } /// /// // SELECT * FROM player /// try Player.fetchAll(db) /// ``` /// /// You can override this property and provide an explicit selection. /// For example: /// /// ```swift /// class PartialPlayer: Record { /// override static var databaseSelection: [any SQLSelectable] { /// [Column("id"), Column("name")] /// } /// } /// /// // SELECT id, name FROM player /// try PartialPlayer.fetchAll(db) /// ``` open class var databaseSelection: [any SQLSelectable] { [AllColumns()] } /// Encodes the record into the provided persistence container. /// /// In your implementation of this method, store in the `container` argument /// all values that should be stored in database columns. /// /// Primary key columns, if any, must be included. /// /// For example: /// /// ```swift /// class Player: Record { /// var id: Int64? /// var name: String? /// /// override func encode(to container: inout PersistenceContainer) { /// container["id"] = id /// container["name"] = name /// } /// } /// ``` /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. /// /// - throws: An error is thrown if the record can't be encoded to its /// database representation. open func encode(to container: inout PersistenceContainer) throws { } // MARK: - Compare with Previous Versions /// A boolean value indicating whether the record has changes that have not /// been saved. /// /// This flag is purely informative, and does not prevent insertions and /// updates from performing their database queries. /// /// A record is *edited* if has been changed since last database /// synchronization (fetch, update, or insert). Comparison /// is performed between *values* (values stored in the ``encode(to:)`` /// method, and values decoded from ``init(row:)``). Property setters do not /// trigger this flag. /// /// You can rely on the ``Record`` base class to compute this flag for you, /// or you may set it to true or false when you know better. Setting it to /// false does not prevent it from turning true on subsequent modifications /// of the record. public var hasDatabaseChanges: Bool { do { return try databaseChangesIterator().next() != nil } catch { // Can't encode the record: surely it can't be saved. return true } } /// A dictionary of changes that have not been saved. /// /// The keys of the dictionary are column names, and values are the old /// values that have been changed since last fetching or saving of /// the record. /// /// Unless the record has actually been fetched or saved, the old values /// are nil. /// /// See ``hasDatabaseChanges`` for more information. /// /// - throws: An error is thrown if the record can't be encoded to its /// database representation. public var databaseChanges: [String: DatabaseValue?] { get throws { try Dictionary(uniqueKeysWithValues: databaseChangesIterator()) } } /// Sets hasDatabaseChanges to true private func setHasDatabaseChanges() { referenceRow = nil } /// Sets hasDatabaseChanges to false private func resetDatabaseChanges() throws { referenceRow = try Row(self) } /// Sets hasDatabaseChanges to false private func resetDatabaseChanges(with persistenceContainer: PersistenceContainer) { referenceRow = Row(persistenceContainer) } // A change iterator that is used by both hasDatabaseChanges and // persistentChangedValues properties. private func databaseChangesIterator() throws -> AnyIterator<(String, DatabaseValue?)> { let oldRow = referenceRow var newValueIterator = try PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueIterator.next() { let newDbValue = newValue?.databaseValue ?? .null guard let oldRow = oldRow, let oldDbValue: DatabaseValue = oldRow[column] else { return (column, nil) } if newDbValue != oldDbValue { return (column, oldDbValue) } } return nil } } /// Reference row for the *hasDatabaseChanges* property. var referenceRow: Row? // MARK: Persistence Callbacks /// Called before the record is inserted. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter db: A database connection. open func willInsert(_ db: Database) throws { } /// Called around the record insertion. /// /// If you override this method, you must call `super` at some point in /// your implementation (this calls the `insert` parameter). /// /// For example: /// /// ```swift /// class Player: Record { /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { /// print("Player will insert") /// try super.aroundInsert(db, insert: insert) /// print("Player did insert") /// } /// } /// ``` /// /// - parameter db: A database connection. /// - parameter insert: A function that inserts the record, and returns /// information about the inserted row. open func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { let inserted = try insert() resetDatabaseChanges(with: inserted.persistenceContainer) } /// Called upon successful insertion. /// /// You can override this method in order to grab the auto-incremented id: /// /// ```swift /// class Player: Record { /// var id: Int64? /// var name: String /// /// override func didInsert(_ inserted: InsertionSuccess) { /// super.didInsert(inserted) /// id = inserted.rowID /// } /// } /// ``` /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter inserted: Information about the inserted row. open func didInsert(_ inserted: InsertionSuccess) { } /// Called before the record is updated. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter db: A database connection. open func willUpdate(_ db: Database, columns: Set<String>) throws { } /// Called around the record update. /// /// If you override this method, you must call `super` at some point in /// your implementation (this calls the `update` parameter). /// /// For example: /// /// ```swift /// class Player: Record { /// override func aroundUpdate( /// _ db: Database, /// columns: Set<String>, /// update: () throws -> PersistenceSuccess) /// throws /// { /// print("Player will update") /// try super.aroundUpdate(db, columns: columns, update: update) /// print("Player did update") /// } /// } /// ``` /// /// - parameter db: A database connection. /// - parameter columns: The updated columns. /// - parameter update: A function that updates the record. Its result is /// reserved for GRDB usage. open func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws { let updated = try update() resetDatabaseChanges(with: updated.persistenceContainer) } /// Called upon successful update. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter updated: Reserved for GRDB usage. open func didUpdate(_ updated: PersistenceSuccess) { } /// Called before the record is updated or inserted. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter db: A database connection. open func willSave(_ db: Database) throws { } /// Called around the record update or insertion. /// /// If you override this method, you must call `super` at some point in /// your implementation (this calls the `update` parameter). /// /// For example: /// /// ```swift /// class Player: Record { /// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { /// print("Player will save") /// try super.aroundSave(db, save: save) /// print("Player did save") /// } /// } /// ``` /// /// - parameter db: A database connection. /// - parameter update: A function that updates the record. Its result is /// reserved for GRDB usage. open func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { _ = try save() } /// Called upon successful update or insertion. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter saved: Reserved for GRDB usage. open func didSave(_ saved: PersistenceSuccess) { } /// Called before the record is deleted. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter db: A database connection. open func willDelete(_ db: Database) throws { } /// Called around the destruction of the record. /// /// If you override this method, you must call `super` at some point in /// your implementation (this calls the `delete` parameter). /// /// For example: /// /// ```swift /// class Player: Record { /// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { /// print("Player will delete") /// try super.aroundDelete(db, delete: delete) /// print("Player did delete") /// } /// } /// ``` /// /// - parameter db: A database connection. /// - parameter delete: A function that deletes the record and returns /// whether a row was deleted in the database. open func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { _ = try delete() setHasDatabaseChanges() } /// Called upon successful deletion. /// /// If you override this method, you must call `super` at some point in /// your implementation. /// /// - parameter deleted: Whether a row was deleted in the database. open func didDelete(deleted: Bool) { } // MARK: - CRUD /// If the record has been changed, executes an `UPDATE` statement so that /// those changes and only those changes are saved in the database. /// /// On success, this method sets the `hasDatabaseChanges` flag to false. /// /// - parameter db: A database connection. /// - returns: Whether the record had changes. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// ``PersistenceError/recordNotFound(databaseTableName:key:)`` is thrown /// if the primary key does not match any row in the database and record /// could not be updated. @discardableResult public final func updateChanges(_ db: Database) throws -> Bool { let changedColumns = try Set(databaseChanges.keys) if changedColumns.isEmpty { return false } else { try update(db, columns: changedColumns) return true } } } extension Record: TableRecord { } extension Record: PersistableRecord { } extension Record: FetchableRecord { }
mit
ab874f1e8096c01671ca062a0a52a401
32.528868
114
0.583
4.683226
false
false
false
false
tad-iizuka/swift-sdk
Source/DiscoveryV1/Models/Aggregation.swift
2
3420
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** An aggregation produced by the Discovery service to analyze the input provided. */ public struct Aggregation: JSONDecodable { /// Type of aggregation command used. e.g. term, filter, max, min, etc. public let type: String? /// The field where the aggregation is located in the document. public let field: String? /// Results of the aggregation. public let results: [AggregationResult]? /// The match the aggregated results queried for. public let match: String? /// Number of matching results. public let matchingResults: Int? /// Aggregations returned by the Discovery service. public let aggregations: [Aggregation]? /// Interval specified by using aggregation type 'timeslice'. public let interval: String? /// Value of the aggregation. (For 'max' and 'min' type). public let value: Double? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize an `Aggregation` model from JSON. public init(json: JSON) throws { type = try? json.getString(at: "type") field = try? json.getString(at: "field") results = try? json.decodedArray(at: "results", type: AggregationResult.self) match = try? json.getString(at: "match") matchingResults = try? json.getInt(at: "matching_results") aggregations = try? json.decodedArray(at: "aggregations", type: Aggregation.self) interval = try? json.getString(at: "interval") value = try? json.getDouble(at: "value") self.json = try json.getDictionaryObject() } /// Used internally to serialize an 'Aggregation' model to JSON. public func toJSONObject() -> Any { return json } } /** Results of the aggregation. */ public struct AggregationResult: JSONDecodable { /// Key that matched the aggregation type. public let key: String? /// Number of matching results. public let matchingResults: Int? /// Aggregations returned in the case of chained aggregations. public let aggregations: [Aggregation]? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialze an 'AggregationResult' model from JSON. public init(json: JSON) throws { key = try? json.getString(at: "key") matchingResults = try? json.getInt(at: "matching_results") aggregations = try? json.decodedArray(at: "aggregations", type: Aggregation.self) self.json = try json.getDictionaryObject() } /// Used internally to serialize an 'AggregationResult' model to JSON. public func toJSONObject() -> Any { return json } }
apache-2.0
908f27ed60cf9ce6d114f6885d6d38b8
34.625
89
0.670468
4.5
false
false
false
false
joe22499/JKCalendar
Example/JKCalendar-Example/TableViewController.swift
1
5334
// // TableViewController.swift // // Copyright © 2017 Joe Ciou. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import JKCalendar class TableViewCell: UITableViewCell{ @IBOutlet weak var timeLabel: UILabel! } class TableViewController: UIViewController { let markColor = UIColor(red: 40/255, green: 178/255, blue: 253/255, alpha: 1) var selectDay: JKDay = JKDay(date: Date()) @IBOutlet weak var calendarTableView: JKCalendarTableView! override func viewDidLoad() { super.viewDidLoad() calendarTableView.nativeDelegate = self calendarTableView.calendar.delegate = self calendarTableView.calendar.dataSource = self calendarTableView.calendar.focusWeek = selectDay.weekOfMonth - 1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func handleBackButtonClick(_ sender: Any) { let _ = navigationController?.popViewController(animated: true) } } extension TableViewController: JKCalendarDelegate{ func calendar(_ calendar: JKCalendar, didTouch day: JKDay){ selectDay = day calendar.focusWeek = day < calendar.month ? 0: day > calendar.month ? calendar.month.weeksCount - 1: day.weekOfMonth - 1 calendar.reloadData() } func heightOfFooterView(in claendar: JKCalendar) -> CGFloat{ return 10 } func viewOfFooter(in calendar: JKCalendar) -> UIView?{ let view = UIView() let line = UIView(frame: CGRect(x: 8, y: 9, width: calendar.frame.width - 16, height: 1)) line.backgroundColor = UIColor.lightGray view.addSubview(line) return view } } extension TableViewController: JKCalendarDataSource{ func calendar(_ calendar: JKCalendar, marksWith month: JKMonth) -> [JKCalendarMark]? { let firstMarkDay: JKDay = JKDay(year: 2018, month: 1, day: 9)! let secondMarkDay: JKDay = JKDay(year: 2018, month: 1, day: 20)! var marks: [JKCalendarMark] = [] if selectDay == month{ marks.append(JKCalendarMark(type: .circle, day: selectDay, color: markColor)) } if firstMarkDay == month{ marks.append(JKCalendarMark(type: .underline, day: firstMarkDay, color: markColor)) } if secondMarkDay == month{ marks.append(JKCalendarMark(type: .hollowCircle, day: secondMarkDay, color: markColor)) } return marks } func calendar(_ calendar: JKCalendar, continuousMarksWith month: JKMonth) -> [JKCalendarContinuousMark]?{ let startDay: JKDay = JKDay(year: 2018, month: 1, day: 17)! let endDay: JKDay = JKDay(year: 2018, month: 1, day: 18)! return [JKCalendarContinuousMark(type: .dot, start: startDay, end: endDay, color: markColor)] } } extension TableViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 48 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell if indexPath.row % 2 == 0 && indexPath.row != 0 && indexPath.row != 47{ let hour = indexPath.row / 2 cell.timeLabel.text = (hour < 10 ? "0": "") + String(hour) + ":00" }else{ cell.timeLabel.text = "" } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(indexPath.row) } }
mit
93ab0c74a23f7c7b6c5e4ab08388f9f1
35.033784
128
0.618414
4.753119
false
false
false
false
cweatureapps/SwiftScraper
Pods/Observable-Swift/Observable-Swift/Protocols.swift
2
4109
// // Protocols.swift // Observable-Swift // // Created by Leszek Ślażyński on 21/06/14. // Copyright (c) 2014 Leszek Ślażyński. All rights reserved. // /// Arbitrary Event. public protocol AnyEvent { associatedtype ValueType /// Notify all valid subscriptions of the change. Remove invalid ones. mutating func notify(_ value: ValueType) /// Add an existing subscription. @discardableResult mutating func add(_ subscription: EventSubscription<ValueType>) -> EventSubscription<ValueType> /// Create, add and return a subscription for given handler. @discardableResult mutating func add(_ handler : @escaping (ValueType) -> ()) -> EventSubscription<ValueType> /// Remove given subscription, if present. mutating func remove(_ subscription : EventSubscription<ValueType>) /// Remove all subscriptions. mutating func removeAll() /// Create, add and return a subscription with given handler and owner. @discardableResult mutating func add(owner : AnyObject, _ handler : @escaping (ValueType) -> ()) -> EventSubscription<ValueType> } /// Event which is a value type. public protocol UnownableEvent: AnyEvent { } /// Event which is a reference type public protocol OwnableEvent: AnyEvent { } /// Arbitrary observable. public protocol AnyObservable { associatedtype ValueType /// Value of the observable. var value: ValueType { get } /// Event fired before value is changed var beforeChange: EventReference<ValueChange<ValueType>> { get } /// Event fired after value is changed var afterChange: EventReference<ValueChange<ValueType>> { get } } /// Observable which can be written to public protocol WritableObservable: AnyObservable { var value: ValueType { get set } } /// Observable which is a value type. Elementary observables are value types. public protocol UnownableObservable: WritableObservable { /// Unshares events mutating func unshare(removeSubscriptions: Bool) } /// Observable which is a reference type. Compound observables are reference types. public protocol OwnableObservable: AnyObservable { } // observable <- value infix operator <- // value = observable^ postfix operator ^ // observable ^= value public func ^= <T : WritableObservable> (x: inout T, y: T.ValueType) { x.value = y } // observable += { valuechange in ... } @discardableResult public func += <T : AnyObservable> (x: inout T, y: @escaping (ValueChange<T.ValueType>) -> ()) -> EventSubscription<ValueChange<T.ValueType>> { return x.afterChange += y } // observable += { (old, new) in ... } @discardableResult public func += <T : AnyObservable> (x: inout T, y: @escaping (T.ValueType, T.ValueType) -> ()) -> EventSubscription<ValueChange<T.ValueType>> { return x.afterChange += y } // observable += { new in ... } @discardableResult public func += <T : AnyObservable> (x: inout T, y: @escaping (T.ValueType) -> ()) -> EventSubscription<ValueChange<T.ValueType>> { return x.afterChange += y } // observable -= subscription public func -= <T : AnyObservable> (x: inout T, s: EventSubscription<ValueChange<T.ValueType>>) { x.afterChange.remove(s) } // event += { (old, new) in ... } @discardableResult public func += <T> (event: EventReference<ValueChange<T>>, handler: @escaping (T, T) -> ()) -> EventSubscription<ValueChange<T>> { return event.add({ handler($0.oldValue, $0.newValue) }) } // event += { new in ... } @discardableResult public func += <T> (event: EventReference<ValueChange<T>>, handler: @escaping (T) -> ()) -> EventSubscription<ValueChange<T>> { return event.add({ handler($0.newValue) }) } // for observable values on variables public func <- <T : WritableObservable & UnownableObservable> (x: inout T, y: T.ValueType) { x.value = y } // for observable references on variables or constants public func <- <T : WritableObservable & OwnableObservable> (x: T, y: T.ValueType) { var z = x z.value = y } public postfix func ^ <T : AnyObservable> (x: T) -> T.ValueType { return x.value }
mit
6fbe52a44bc5fd3499595d5b332839f7
29.849624
143
0.685108
4.199591
false
false
false
false
matthewcheok/JSONCodable
JSONCodable.playground/Contents.swift
1
3223
/*: # JSONCodable Hassle-free JSON encoding and decoding in Swift `JSONCodable` is made of two seperate protocols `JSONEncodable` and `JSONDecodable`. `JSONEncodable` generates `Dictionary`s (compatible with `NSJSONSerialization`) and `String`s from your types while `JSONDecodable` creates structs (or classes) from compatible `Dictionary`s (from an incoming network request for instance) */ import JSONCodable /*: Here's some data models we'll use as an example: */ struct User { let id: Int let name: String var email: String? var company: Company? var friends: [User] = [] } struct Company { let name: String var address: String? } /*: ## JSONEncodable We'll add conformance to `JSONEncodable`. You may also add conformance to `JSONCodable`. */ extension User: JSONEncodable { func toJSON() throws -> Any { return try JSONEncoder.create({ (encoder) -> Void in try encoder.encode(id, key: "id") try encoder.encode(name, key: "full_name") try encoder.encode(email, key: "email") try encoder.encode(company, key: "company") try encoder.encode(friends, key: "friends") }) } } extension Company: JSONEncodable {} /*: The default implementation of `func toJSON()` inspects the properties of your type using reflection. (Like in `Company`.) If you need a different mapping, you can provide your own implementation (like in `User`.) */ /*: ## JSONDecodable We'll add conformance to `JSONDecodable`. You may also add conformance to `JSONCodable`. */ extension User: JSONDecodable { init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) id = try decoder.decode("id") name = try decoder.decode("full_name") email = try decoder.decode("email") company = try decoder.decode("company") friends = try decoder.decode("friends") } } extension Company: JSONDecodable { init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) name = try decoder.decode("name") address = try decoder.decode("address") } } /*: Simply provide the implementations for `init?(JSONDictionary: JSONObject)`. As before, you can use this to configure the mapping between keys in the `Dictionary` to properties in your structs and classes. */ /*: ## Test Drive You can open the console and see the output using `CMD + SHIFT + Y` or ⇧⌘Y. Let's work with an incoming JSON Dictionary: */ let JSON: [String: Any] = [ "id": 24, "full_name": "John Appleseed", "email": "[email protected]", "company": [ "name": "Apple", "address": "1 Infinite Loop, Cupertino, CA" ], "friends": [ ["id": 27, "full_name": "Bob Jefferson"], ["id": 29, "full_name": "Jen Jackson"] ] ] print("Initial JSON:\n\(JSON)\n\n") /*: We can instantiate `User` using one of provided initializers: - `init(JSONDictionary: JSONObject)` - `init?(JSONString: String)` */ let user = try! User(object: JSON) print("Decoded: \n\(user)\n\n") /*: And encode it to JSON using one of the provided methods: - `func JSONEncode() throws -> AnyObject` - `func JSONString() throws -> String` */ try! 1.toJSON() let dict = try! user.toJSON() print("Encoded: \n\(dict as! JSONObject)\n\n")
mit
c03a37b439774d1a73954d086c7332fb
25.825
238
0.679714
3.734339
false
false
false
false
KiiCorp/HelloKii-iOS
HelloKii-iOS-Swift/HelloKii-iOS-Swift/MainViewController.swift
2
6673
// // // Copyright 2017 Kii Corporation // http://kii.com // // 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 UIKit import KiiSDK class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // Define the object array of KiiObjects. fileprivate var objectList: [KiiObject] = [] // Define the object count to easily see // object names incrementing. fileprivate var objectCount = 0 fileprivate let bucketName = "myBucket" fileprivate let objectKey = "myObjectValue" override func viewDidLoad() { super.viewDidLoad() // Initialize the view. tableView.delegate = self tableView.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Add the "+" button to the navigation bar. let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MainViewController.addItem)) navigationItem.rightBarButtonItem = addButton // Initialize the activity indicator to appear on the top of the screen. self.activityIndicator.layer.zPosition = 1 } override func viewDidAppear(_ animated: Bool) { // Show an activity indicator. activityIndicator.startAnimating() // Clear all items. self.objectList.removeAll() // Create an empty KiiQuery. This query will retrieve all results sorted by the creation date. let allQuery = KiiQuery(clause: nil) allQuery.sort(byDesc: "_created") // Define the bucket to query. let bucket = KiiUser.current()!.bucket(withName: bucketName) // Perform the query. bucket.execute(allQuery) { (query, bucket, result, nextQuery, error) -> Void in // Hide the activity indicator by setting "Hides When Stopped" in the storyboard. self.activityIndicator.stopAnimating() // Check for an error. The request was successfully processed if error==nil. if error != nil { self.showMessage("Query failed", error: error as NSError?) return } // Add the objects to the object array and refresh the list. self.objectList.append(contentsOf: result as! [KiiObject]) self.tableView.reloadData() } } func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return objectList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Initialize a cell. var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath) if cell == nil { cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier:"Cell") } // Fill the cell with data from the object array. let obj = objectList[indexPath.row] cell!.textLabel!.text! = obj.getForKey(objectKey) as! String cell!.detailTextLabel!.text! = obj.objectURI! return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath:IndexPath) { // Show an alert dialog. let alert = UIAlertController(title: nil, message: "Would you like to remove this item?", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { (action) -> Void in // Perform the delete action to the tapped object. self.performDelete(indexPath.row) })) alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil)) present(alert, animated: true, completion: nil) } func addItem() { // Show an activity indicator. activityIndicator.startAnimating() // Create an incremented title for the object. objectCount += 1 let value = String(format: "MyObject %d", objectCount) // Get a reference to the KiiBucket. let bucket = KiiUser.current()!.bucket(withName: bucketName) // Create a new KiiObject instance and set the key-value pair. let object = bucket.createObject() object.setObject(value, forKey: objectKey) // Save the object asynchronously. object.save { (object, error) -> Void in // Hide the activity indicator by setting "Hides When Stopped" in the storyboard. self.activityIndicator.stopAnimating() // Check for an error. The request was successfully processed if error==nil. if error != nil { self.showMessage("Save failed", error: error as NSError?) return } // Insert the object at the beginning of the object array and refresh the list. self.objectList.insert(object, at: 0) self.tableView.reloadData() } } func performDelete(_ position: Int) { // Show an activity indicator. activityIndicator.startAnimating() // Get the object to delete with the index number of the tapped row. let obj = objectList[position] // Delete the object asynchronously. obj.delete { (object, error) -> Void in // Hide the activity indicator by setting "Hides When Stopped" in the storyboard. self.activityIndicator.stopAnimating() // Check for an error. The request was successfully processed if error==nil. if error != nil { self.showMessage("Delete failed", error: error as NSError?) return } // Remove the object from the object array and refresh the list. self.objectList.remove(at: position) self.tableView.reloadData() } } }
apache-2.0
0d04f66dafead991d60253ed6b2f6031
36.488764
143
0.648284
4.98357
false
false
false
false
seem-sky/ios-charts
Charts/Classes/Charts/PieRadarChartViewBase.swift
1
17006
// // PieRadarChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation /// Base class of PieChartView and RadarChartView. public class PieRadarChartViewBase: ChartViewBase { /// holds the current rotation angle of the chart internal var _rotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not public var rotationEnabled = true private var _tapGestureRecognizer: UITapGestureRecognizer! public override init(frame: CGRect) { super.init(frame: frame); } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } internal override func initialize() { super.initialize(); _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")); self.addGestureRecognizer(_tapGestureRecognizer); } internal override func calcMinMax() { _deltaX = CGFloat(_data.xVals.count - 1); } public override func notifyDataSetChanged() { if (_dataNotSet) { return; } calcMinMax(); _legendRenderer.computeLegend(_data); calculateOffsets(); setNeedsDisplay(); } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0); var legendRight = CGFloat(0.0); var legendBottom = CGFloat(0.0); var legendTop = CGFloat(0.0); if (_legend != nil && _legend.enabled) { if (_legend.position == .RightOfChartCenter) { // this is the space between the legend and the chart var spacing = CGFloat(13.0); legendRight = self.fullLegendWidth + spacing; } else if (_legend.position == .RightOfChart) { // this is the space between the legend and the chart var spacing = CGFloat(8.0); var legendWidth = self.fullLegendWidth + spacing; var legendHeight = _legend.neededHeight + _legend.textHeightMax; var c = self.center; var bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15); var distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y); var reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomRight.x, y: bottomRight.y)); var distReference = distanceToCenter(x: reference.x, y: reference.y); var min = CGFloat(5.0); if (distLegend < distReference) { var diff = distReference - distLegend; legendRight = min + diff; } if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendRight = legendWidth; } } else if (_legend.position == .LeftOfChartCenter) { // this is the space between the legend and the chart var spacing = CGFloat(13.0); legendLeft = self.fullLegendWidth + spacing; } else if (_legend.position == .LeftOfChart) { // this is the space between the legend and the chart var spacing = CGFloat(8.0); var legendWidth = self.fullLegendWidth + spacing; var legendHeight = _legend.neededHeight + _legend.textHeightMax; var c = self.center; var bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15); var distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y); var reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y)); var distReference = distanceToCenter(x: reference.x, y: reference.y); var min = CGFloat(5.0); if (distLegend < distReference) { var diff = distReference - distLegend; legendLeft = min + diff; } if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendLeft = legendWidth; } } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { legendBottom = self.requiredBottomOffset; } legendLeft += self.requiredBaseOffset; legendRight += self.requiredBaseOffset; legendTop += self.requiredBaseOffset; } var min = CGFloat(10.0); var offsetLeft = max(min, legendLeft); var offsetTop = max(min, legendTop); var offsetRight = max(min, legendRight); var offsetBottom = max(min, max(self.requiredBaseOffset, legendBottom)); _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom); } /// returns the angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... public func angleForPoint(#x: CGFloat, y: CGFloat) -> CGFloat { var c = centerOffsets; var tx = Double(x - c.x); var ty = Double(y - c.y); var length = sqrt(tx * tx + ty * ty); var r = acos(ty / length); var angle = r * ChartUtils.Math.RAD2DEG; if (x > c.x) { angle = 360.0 - angle; } // add 90° because chart starts EAST angle = angle + 90.0; // neutralize overflow if (angle > 360.0) { angle = angle - 360.0; } return CGFloat(angle); } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. internal func getPosition(#center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { var a = cos(angle * ChartUtils.Math.FDEG2RAD); return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD), y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD)); } /// Returns the distance of a certain point on the chart to the center of the chart. public func distanceToCenter(#x: CGFloat, y: CGFloat) -> CGFloat { var c = self.centerOffsets; var dist = CGFloat(0.0); var xDist = CGFloat(0.0); var yDist = CGFloat(0.0); if (x > c.x) { xDist = x - c.x; } else { xDist = c.x - x; } if (y > c.y) { yDist = y - c.y; } else { yDist = c.y - y; } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)); return dist; } /// Returns the xIndex for the given angle around the center of the chart. /// Returns -1 if not found / outofbounds. public func indexForAngle(angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase"); } /// current rotation angle of the pie chart /// :default: 270f --> top (NORTH) public var rotationAngle: CGFloat { get { return _rotationAngle; } set { while (_rotationAngle < 0.0) { _rotationAngle += 360.0; } _rotationAngle = newValue % 360.0; setNeedsDisplay(); } } /// returns the diameter of the pie- or radar-chart public var diameter: CGFloat { var content = _viewPortHandler.contentRect; return min(content.width, content.height); } /// Returns the radius of the chart in pixels. public var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase"); } /// Returns the required bottom offset for the chart. internal var requiredBottomOffset: CGFloat { fatalError("requiredBottomOffset cannot be called on PieRadarChartViewBase"); } /// Returns the base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase"); } /// Returns the required right offset for the chart. private var fullLegendWidth: CGFloat { return _legend.textWidthMax + _legend.formSize + _legend.formToTextSpace; } public override var chartXMax: Float { return 0.0; } public override var chartXMin: Float { return 0.0; } /// Returns an array of SelInfo objects for the given x-index. /// The SelInfo objects give information about the value at the selected index and the DataSet it belongs to. public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo] { var vals = [ChartSelInfo](); for (var i = 0; i < _data.dataSetCount; i++) { var dataSet = _data.getDataSetByIndex(i); // extract all y-values from all DataSets at the given x-index var yVal = dataSet!.yValForXIndex(xIndex); if (!isnan(yVal)) { vals.append(ChartSelInfo(value: yVal, dataSetIndex: i, dataSet: dataSet!)); } } return vals; } public var isRotationEnabled: Bool { return rotationEnabled; } // MARK: - Animation private var _spinAnimator: ChartAnimator!; private var _spinFromAngle: CGFloat = 0.0; private var _spinToAngle: CGFloat = 0.0; /// Applys a spin animation to the Chart. public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if (_spinAnimator != nil) { _spinAnimator.stop(); } _spinFromAngle = fromAngle; _spinToAngle = toAngle; _spinAnimator = ChartAnimator(); _spinAnimator.updateBlock = { self.rotationAngle = (self._spinToAngle - self._spinFromAngle) * self._spinAnimator.phaseX + self._spinFromAngle; }; _spinAnimator.stopBlock = { self._spinAnimator = nil; }; _spinAnimator.animate(xAxisDuration: duration, easing: easing); } public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)); } public func spin(#duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil); } public func stopSpinAnimation() { if (_spinAnimator != nil) { _spinAnimator.stop(); } } // MARK: - Gestures private var _touchStartPoint: CGPoint!; private var _isRotating = false; private var _startAngle = CGFloat(0.0) public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event); // if rotation by touch is enabled if (rotationEnabled) { var touch = touches.first as! UITouch!; var touchLocation = touch.locationInView(self); _touchStartPoint = touchLocation; self.setStartAngle(x: touchLocation.x, y: touchLocation.y); } } public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesMoved(touches, withEvent: event); if (rotationEnabled) { var touch = touches.first as! UITouch!; var touchLocation = touch.locationInView(self); if (!_isRotating && distance(eventX: touchLocation.x, startX: _touchStartPoint.x, eventY: touchLocation.y, startY: _touchStartPoint.y) > CGFloat(8.0)) { _isRotating = true; self.disableScroll(); } else { self.updateRotation(x: touchLocation.x, y: touchLocation.y); } } } public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event); if (rotationEnabled) { var touch = touches.first as! UITouch!; var touchLocation = touch.locationInView(self); _touchStartPoint = touchLocation; self.enableScroll(); _isRotating = false; } } /// returns the distance between two points private func distance(#eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { var dx = eventX - startX; var dy = eventY - startY; return sqrt(dx * dx + dy * dy); } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setStartAngle(#x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y); // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle; setNeedsDisplay(); } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateRotation(#x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle; } /// reference to the last highlighted object private var _lastHighlight: ChartHighlight!; @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Ended) { var location = recognizer.locationInView(self); var distance = distanceToCenter(x: location.x, y: location.y); // check if a slice was touched if (distance > self.radius) { // if no slice was touched, highlight nothing self.highlightValues(nil); _lastHighlight = nil; _lastHighlight = nil; } else { var angle = angleForPoint(x: location.x, y: location.y); if (self.isKindOfClass(PieChartView)) { angle /= _animator.phaseY; } var index = indexForAngle(angle); // check if the index could be found if (index < 0) { self.highlightValues(nil); _lastHighlight = nil; } else { var valsAtIndex = getYValsAtIndex(index); var dataSetIndex = 0; // get the dataset that is closest to the selection (PieChart only has one DataSet) if (self.isKindOfClass(RadarChartView)) { dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(distance / (self as! RadarChartView).factor), axis: nil); } var h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex); if (_lastHighlight !== nil && h == _lastHighlight) { self.highlightValue(highlight: nil, callDelegate: true); _lastHighlight = nil; } else { self.highlightValue(highlight: h, callDelegate: true); _lastHighlight = h; } } } } } }
apache-2.0
cdc492708298f1d3c5d24c5459a10cf9
31.202652
162
0.546818
5.128808
false
false
false
false
AmitaiB/MyPhotoViewer
Pods/Cache/Source/Shared/Library/ImageWrapper.swift
3
793
import Foundation public struct ImageWrapper: Codable { public let image: Image public enum CodingKeys: String, CodingKey { case image } public init(image: Image) { self.image = image } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let data = try container.decode(Data.self, forKey: CodingKeys.image) guard let image = Image(data: data) else { throw StorageError.decodingFailed } self.image = image } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) guard let data = image.cache_toData() else { throw StorageError.encodingFailed } try container.encode(data, forKey: CodingKeys.image) } }
mit
5e4e725be5d3133604719842d2c15325
23.78125
72
0.696091
4.218085
false
false
false
false
swiftcode/swapscroll
swapscroll/swapscroll/ViewController.swift
1
1401
// // ViewController.swift // swapscroll // // Created by mpc on 4/12/15. // Copyright (c) 2015 mpc. All rights reserved. // import Foundation import Cocoa import IOKit class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() //TODO: look into creating status items. swapScrollDirection() exit(0) //TODO: This will not happen. Run continuously. } func mouseDetected() -> Bool { let task = Process() let pipe = Pipe() var detected = false task.launchPath = "/usr/sbin/ioreg" task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String detected = Regex("mouse").test(output) return detected } func swapScrollDirection() { let task = Process() var command = [String]() if mouseDetected() { command = ["-c", "defaults write com.apple.swipescrolldirection -bool false"] } else { command = ["-c", "defaults write com.apple.swipescrolldirection -bool true"] } task.launchPath = "/bin/bash" task.arguments = command task.launch() } }
mit
894fdba8ae418b1c77a36cf4c6d15646
24.944444
101
0.576731
4.533981
false
false
false
false
huonw/swift
test/TBD/class.swift
1
8450
// RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s // RUN: %target-swift-frontend -enable-resilience -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing // RUN: %target-swift-frontend -enable-resilience -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing open class OpenNothing {} open class OpenInit { public init() {} public init(public_: Int) {} internal init(internal_: Int) {} deinit {} } open class OpenMethods { public init() {} public func publicMethod() {} internal func internalMethod() {} private func privateMethod() {} } open class OpenProperties { public let publicLet: Int = 0 internal let internalLet: Int = 0 private let privateLet: Int = 0 public var publicVar: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 public var publicVarGet: Int { return 0 } internal var internalVarGet: Int { return 0 } private var privateVarGet: Int { return 0 } public var publicVarGetSet: Int { get { return 0 } set {} } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} } } open class OpenStatics { public static func publicStaticFunc() {} internal static func internalStaticFunc() {} private static func privateStaticFunc() {} public static let publicLet: Int = 0 internal static let internalLet: Int = 0 private static let privateLet: Int = 0 public static var publicVar: Int = 0 internal static var internalVar: Int = 0 private static var privateVar: Int = 0 public static var publicVarGet: Int { return 0 } internal static var internalVarGet: Int { return 0 } private static var privateVarGet: Int { return 0 } public static var publicVarGetSet: Int { get { return 0 } set {} } internal static var internalVarGetSet: Int { get { return 0 } set {} } private static var privateVarGetSet: Int { get { return 0 } set {} } } open class OpenGeneric<T, U, V> { public var publicVar: T internal var internalVar: U private var privateVar: V public var publicVarConcrete: Int = 0 internal var internalVarConcrete: Int = 0 private var privateVarConcrete: Int = 0 public init<S>(t: T, u: U, v: V, _: S) { publicVar = t internalVar = u privateVar = v } public func publicGeneric<A>(_: A) {} internal func internalGeneric<A>(_: A) {} private func privateGeneric<A>(_: A) {} public static func publicStaticGeneric<A>(_: A) {} internal static func internalStaticGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} } public class PublicNothing {} public class PublicInit { public init() {} public init(public_: Int) {} internal init(internal_: Int) {} deinit {} } public class PublicMethods { public init() {} public func publicMethod() {} internal func internalMethod() {} private func privateMethod() {} } public class PublicProperties { public let publicLet: Int = 0 internal let internalLet: Int = 0 private let privateLet: Int = 0 public var publicVar: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 public var publicVarGet: Int { return 0 } internal var internalVarGet: Int { return 0 } private var privateVarGet: Int { return 0 } public var publicVarGetSet: Int { get { return 0 } set {} } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} } } public class PublicStatics { public static func publicStaticFunc() {} internal static func internalStaticFunc() {} private static func privateStaticFunc() {} public static let publicLet: Int = 0 internal static let internalLet: Int = 0 private static let privateLet: Int = 0 public static var publicVar: Int = 0 internal static var internalVar: Int = 0 private static var privateVar: Int = 0 public static var publicVarGet: Int { return 0 } internal static var internalVarGet: Int { return 0 } private static var privateVarGet: Int { return 0 } public static var publicVarGetSet: Int { get { return 0 } set {} } internal static var internalVarGetSet: Int { get { return 0 } set {} } private static var privateVarGetSet: Int { get { return 0 } set {} } } public class PublicGeneric<T, U, V> { public var publicVar: T internal var internalVar: U private var privateVar: V public var publicVarConcrete: Int = 0 internal var internalVarConcrete: Int = 0 private var privateVarConcrete: Int = 0 public init<S>(t: T, u: U, v: V, _: S) { publicVar = t internalVar = u privateVar = v } public func publicGeneric<A>(_: A) {} internal func internalGeneric<A>(_: A) {} private func privateGeneric<A>(_: A) {} public static func publicStaticGeneric<A>(_: A) {} internal static func internalStaticGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} } internal class InternalNothing {} internal class InternalInit { internal init() {} internal init(internal_: Int) {} private init(private_: Int) {} } internal class InternalMethods { internal init() {} internal func internalMethod() {} private func privateMethod() {} } internal class InternalProperties { internal let internalLet: Int = 0 private let privateLet: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 internal var internalVarGet: Int { return 0 } private var privateVarGet: Int { return 0 } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} } } internal class InternalStatics { internal static func internalStaticFunc() {} private static func privateStaticFunc() {} internal static let internalLet: Int = 0 private static let privateLet: Int = 0 internal static var internalVar: Int = 0 private static var privateVar: Int = 0 internal static var internalVarGet: Int { return 0 } private static var privateVarGet: Int { return 0 } internal static var internalVarGetSet: Int { get { return 0 } set {} } private static var privateVarGetSet: Int { get { return 0 } set {} } } internal class InternalGeneric<T, U, V> { internal var internalVar: U private var privateVar: V internal var internalVarConcrete: Int = 0 private var privateVarConcrete: Int = 0 internal init<S>(t: T, u: U, v: V, _: S) { internalVar = u privateVar = v } internal func internalGeneric<A>(_: A) {} private func privateGeneric<A>(_: A) {} internal static func internalStaticGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} } private class PrivateNothing {} private class PrivateInit { private init() {} private init(private_: Int) {} } private class PrivateMethods { private init() {} private func privateMethod() {} } private class PrivateProperties { private let privateLet: Int = 0 private var privateVar: Int = 0 private var privateVarGet: Int { return 0 } private var privateVarGetSet: Int { get { return 0 } set {} } } private class PrivateStatics { private static func privateStaticFunc() {} private static let privateLet: Int = 0 private static var privateVar: Int = 0 private static var privateVarGet: Int { return 0 } private static var privateVarGetSet: Int { get { return 0 } set {} } } private class PrivateGeneric<T, U, V> { private var privateVar: V private var privateVarConcrete: Int = 0 private init<S>(t: T, u: U, v: V, _: S) { privateVar = v } private func privateGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} }
apache-2.0
579502d9817f391f3bab18644a31dc57
24.14881
150
0.647456
4.34001
false
false
false
false
huonw/swift
test/DebugInfo/inlinedAt.swift
5
2053
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -emit-verbose-sil -o - \ // RUN: | %FileCheck %s --check-prefix=CHECK-SIL // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | %FileCheck %s public var glob : Int = 0 @inline(never) public func hold(_ n : Int) { glob = n } #sourceLocation(file: "abc.swift", line: 100) @inline(__always) func h(_ k : Int) -> Int { // 101 hold(k) // 102 return k // 103 } #sourceLocation(file: "abc.swift", line: 200) @inline(__always) func g(_ j : Int) -> Int { // 201 hold(j) // 202 return h(j) // 203 } #sourceLocation(file: "abc.swift", line: 301) public func f(_ i : Int) -> Int { // 301 return g(i) // 302 } // CHECK-SIL: sil {{.*}}@$S9inlinedAt1fyS2iF : // CHECK-SIL-NOT: return // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1 // CHECK-SIL-SAME: line:101:10:in_prologue // CHECK-SIL-SAME: perf_inlined_at line:203:10 // CHECK-SIL-SAME: perf_inlined_at line:302:10 // CHECK: define {{.*}}@"$S9inlinedAt1fyS2iF"({{.*}}) // CHECK-NOT: ret // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value({{.*}}), !dbg ![[L1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK: ![[L3:.*]] = !DILocation(line: 302, column: 10, // CHECK-SAME: scope: ![[F_SCOPE:.*]]) // CHECK: ![[F_SCOPE]] = distinct !DILexicalBlock(scope: ![[F]], // CHECK-SAME: line: 301, column: 33) // CHECK: ![[G_SCOPE:.*]] = distinct !DILexicalBlock(scope: ![[G]], // CHECK-SAME: line: 201, column: 26) // CHECK: ![[H:.*]] = distinct !DISubprogram(name: "h", // CHECK: ![[L1]] = !DILocation(line: 101, column: 8, scope: ![[H]], // CHECK-SAME: inlinedAt: ![[L2:.*]]) // CHECK: ![[L2]] = !DILocation(line: 203, column: 10, scope: ![[G_SCOPE]], // CHECK-SAME: inlinedAt: ![[L3]])
apache-2.0
5db0f463c0fd033092327765e3ca0bb3
37.018519
77
0.518753
3.087218
false
false
false
false
Groupr-Purdue/Groupr-Backend
Sources/Library/Controllers/AuthController.swift
1
1687
import Vapor import HTTP import Auth public final class AuthController { var droplet: Droplet public init(droplet: Droplet) { self.droplet = droplet } /// GET /: Returns your own user when authenticated. public func me(request: Request) throws -> ResponseRepresentable { guard let user = try User.authenticateWithToken(fromRequest: request) else { return try JSON(node: ["error": "Not Authorized"]) } return try user.userJson() } /// POST: Authenticates user with password and returns the respective user public func login(request: Request) throws -> ResponseRepresentable { guard let careerAccount = request.json?["career_account"]?.string, let user = try User.query().filter("career_account", careerAccount).first() else { return try JSON(node: ["error": "Incorrect career account or password"]) } guard let rawPassword = request.json?["password"]?.string, try user.passwordValid(rawPassword: rawPassword) else { return try JSON(node: ["error": "Incorrect career account or password"]) } return try user.userJson() } /// DELETE: Deauthenticate user by expiring the current user token and generating a new one public func logout(request: Request) throws -> ResponseRepresentable { guard let token = request.auth.header?.header, var user = try User.query().filter("token", token).first() else { return try JSON(node: ["error": "Not Authorized"]) } user.token = User.generateToken() try user.save() return try JSON(node: ["success": "User logged out"]) } }
mit
1058462e90cedd4d2b611aa5bb8c44dd
39.166667
157
0.648488
4.660221
false
false
false
false
che1404/RGViperChat
vipergenTemplate/che1404/swift/Interactor/VIPERInteractorSpec.swift
1
1140
// // Created by AUTHOR // Copyright (c) YEAR AUTHOR. All rights reserved. // import Quick import Nimble import Cuckoo @testable import ProjectName class VIPERInteractorSpec: QuickSpec { var interactor: VIPERInteractor! var mockPresenter: MockVIPERInteractorOutputProtocol! var mockAPIDataManager: MockVIPERAPIDataManagerInputProtocol! var mockLocalDataManager: MockVIPERLocalDataManagerInputProtocol! override func spec() { beforeEach { self.mockPresenter = MockVIPERInteractorOutputProtocol() self.mockAPIDataManager = MockVIPERAPIDataManagerInputProtocol() self.mockLocalDataManager = MockVIPERLocalDataManagerInputProtocol() self.interactor = VIPERInteractor() self.interactor.presenter = self.mockPresenter self.interactor.APIDataManager = self.mockAPIDataManager self.interactor.localDataManager = self.mockLocalDataManager } it("Todo") { } afterEach { self.interactor = nil self.mockPresenter = nil self.mockAPIDataManager = nil } } }
mit
9a905f9ceb571299b3c97ba34f389a48
29
80
0.689474
5.643564
false
false
false
false
ozgur/AutoLayoutAnimation
UserViewController.swift
1
1768
// // UserViewController.swift // AutoLayoutAnimation // // Created by Ozgur Vatansever on 10/27/15. // Copyright © 2015 Techshed. All rights reserved. // import UIKit class UserViewController: UITableViewController { var user: User! fileprivate static let CellIdentifier = "UserCell" var info = [String]() { didSet { tableView.reloadData() } } convenience init() { self.init(nibName: "UserViewController", bundle: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white edgesForExtendedLayout = UIRectEdge() tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.register(UITableViewCell.self, forCellReuseIdentifier: UserViewController.CellIdentifier) title = user.firstName } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) execute(delay: 2.0, repeating: false) { self.info = [self.user.fullName, String(self.user.userId), self.user.city] } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return info.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UserViewController.CellIdentifier)! cell.textLabel?.text = info[indexPath.row] cell.selectionStyle = .gray return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
5b29219187ad4c6e4d962634c856ad97
24.608696
107
0.697793
4.762803
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/ColumnarCollectionViewController.swift
1
18187
import UIKit import WMF class ColumnarCollectionViewController: ViewController, ColumnarCollectionViewLayoutDelegate, UICollectionViewDataSourcePrefetching, CollectionViewFooterDelegate, HintPresenting { enum HeaderStyle { case sections case exploreFeedDetail } open var headerStyle: HeaderStyle { return .exploreFeedDetail } lazy var layout: ColumnarCollectionViewLayout = { return ColumnarCollectionViewLayout() }() lazy var layoutCache: ColumnarCollectionViewControllerLayoutCache = { return ColumnarCollectionViewControllerLayoutCache() }() @objc lazy var collectionView: UICollectionView = { let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.isPrefetchingEnabled = true cv.prefetchDataSource = self cv.preservesSuperviewLayoutMargins = true scrollView = cv return cv }() lazy var layoutManager: ColumnarCollectionViewLayoutManager = { return ColumnarCollectionViewLayoutManager(view: view, collectionView: collectionView) }() deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.wmf_addSubviewWithConstraintsToEdges(collectionView) layoutManager.register(CollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewHeader.identifier, addPlaceholder: true) layoutManager.register(CollectionViewFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: CollectionViewFooter.identifier, addPlaceholder: true) collectionView.alwaysBounceVertical = true extendedLayoutIncludesOpaqueBars = true } @objc open func contentSizeCategoryDidChange(_ notification: Notification?) { collectionView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isFirstAppearance { isFirstAppearance = false viewWillHaveFirstAppearance(animated) updateEmptyState() isEmptyDidChange() // perform initial update even though the value might not have changed } else { updateEmptyState() } if let selectedIndexPaths = collectionView.indexPathsForSelectedItems { for selectedIndexPath in selectedIndexPaths { collectionView.deselectItem(at: selectedIndexPath, animated: animated) } } for cell in collectionView.visibleCells { guard let cellWithSubItems = cell as? SubCellProtocol else { continue } cellWithSubItems.deselectSelectedSubItems(animated: animated) } } open func viewWillHaveFirstAppearance(_ animated: Bool) { // subclassers can override } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { contentSizeCategoryDidChange(nil) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (context) in let boundsChange = self.collectionView.bounds guard self.layout.shouldInvalidateLayout(forBoundsChange: boundsChange) else { return } let invalidationContext = self.layout.invalidationContext(forBoundsChange: boundsChange) self.layout.invalidateLayout(with: invalidationContext) }) } // MARK: HintPresenting var hintController: HintController? // MARK: - UIScrollViewDelegate override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { super.scrollViewWillBeginDragging(scrollView) hintController?.dismissHintDueToUserInteraction() } // MARK: - Refresh Control final var isRefreshControlEnabled: Bool = false { didSet { if isRefreshControlEnabled { let refreshControl = UIRefreshControl() refreshControl.tintColor = theme.colors.refreshControlTint refreshControl.layer.zPosition = -100 refreshControl.addTarget(self, action: #selector(refreshControlActivated), for: .valueChanged) collectionView.refreshControl = refreshControl } else { collectionView.refreshControl = nil } } } var refreshStart: Date = Date() @objc func refreshControlActivated() { refreshStart = Date() self.refresh() } open func refresh() { assert(false, "default implementation shouldn't be called") self.endRefreshing() } open func endRefreshing() { let now = Date() let timeInterval = 0.5 - now.timeIntervalSince(refreshStart) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeInterval, execute: { self.collectionView.refreshControl?.endRefreshing() }) } // MARK: - Empty State var emptyViewType: WMFEmptyViewType = .none final var isEmpty = true final var showingEmptyViewType: WMFEmptyViewType? final func updateEmptyState() { let sectionCount = numberOfSections(in: collectionView) var isCurrentlyEmpty = true for sectionIndex in 0..<sectionCount { if self.collectionView(collectionView, numberOfItemsInSection: sectionIndex) > 0 { isCurrentlyEmpty = false break } } guard isCurrentlyEmpty != isEmpty || showingEmptyViewType != emptyViewType else { return } isEmpty = isCurrentlyEmpty isEmptyDidChange() } private var emptyViewFrame: CGRect { let insets = scrollView?.contentInset ?? UIEdgeInsets.zero let frame = view.bounds.inset(by: insets) return frame } open var emptyViewAction: Selector? open func isEmptyDidChange() { if isEmpty { wmf_showEmptyView(of: emptyViewType, action: emptyViewAction, theme: theme, frame: emptyViewFrame) showingEmptyViewType = emptyViewType } else { wmf_hideEmptyView() showingEmptyViewType = nil } } override func scrollViewInsetsDidChange() { super.scrollViewInsetsDidChange() wmf_setEmptyViewFrame(emptyViewFrame) } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.baseBackground collectionView.backgroundColor = theme.colors.paperBackground collectionView.indicatorStyle = theme.scrollIndicatorStyle collectionView.reloadData() wmf_applyTheme(toEmptyView: theme) } // MARK - UICollectionViewDataSourcePrefetching private lazy var imageURLsCurrentlyBeingPrefetched: Set<URL> = { return [] }() open func imageURLsForItemAt(_ indexPath: IndexPath) -> Set<URL>? { return nil } func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { for indexPath in indexPaths { guard let imageURLs = imageURLsForItemAt(indexPath) else { continue } let imageURLsToPrefetch = imageURLs.subtracting(imageURLsCurrentlyBeingPrefetched) let imageController = ImageController.shared imageURLsCurrentlyBeingPrefetched.formUnion(imageURLsToPrefetch) for imageURL in imageURLsToPrefetch { imageController.prefetch(withURL: imageURL) { self.imageURLsCurrentlyBeingPrefetched.remove(imageURL) } } } } // MARK: - Header var headerTitle: String? var headerSubtitle: String? open func configure(header: CollectionViewHeader, forSectionAt sectionIndex: Int, layoutOnly: Bool) { header.title = headerTitle header.subtitle = headerSubtitle header.style = .detail header.apply(theme: theme) } // MARK: - Footer var footerButtonTitle: String? open func configure(footer: CollectionViewFooter, forSectionAt sectionIndex: Int, layoutOnly: Bool) { footer.buttonTitle = footerButtonTitle footer.delegate = self footer.apply(theme: theme) } // MARK - ColumnarCollectionViewLayoutDelegate func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0) switch headerStyle { case .exploreFeedDetail: guard section == 0, headerTitle != nil else { return estimate } case .sections: guard self.collectionView(collectionView, numberOfItemsInSection: section) > 0 else { return estimate } } guard let placeholder = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewHeader.identifier) as? CollectionViewHeader else { return estimate } configure(header: placeholder, forSectionAt: section, layoutOnly: true) estimate.height = placeholder.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true return estimate } open func collectionView(_ collectionView: UICollectionView, estimatedHeightForFooterInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0) guard footerButtonTitle != nil else { return estimate } guard let placeholder = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: CollectionViewFooter.identifier) as? CollectionViewFooter else { return estimate } configure(footer: placeholder, forSectionAt: section, layoutOnly: true) estimate.height = placeholder.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true return estimate } func collectionView(_ collectionView: UICollectionView, shouldShowFooterForSection section: Int) -> Bool { return section == collectionView.numberOfSections - 1 } open func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { return ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 0) } func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics { return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins) } // MARK - Previewing final func collectionViewIndexPathForPreviewingContext(_ previewingContext: UIViewControllerPreviewing, location: CGPoint) -> IndexPath? { let translatedLocation = view.convert(location, to: collectionView) guard let indexPath = collectionView.indexPathForItem(at: translatedLocation), let cell = collectionView.cellForItem(at: indexPath) else { return nil } previewingContext.sourceRect = view.convert(cell.bounds, from: cell) return indexPath } // MARK: - Event logging utiities var percentViewed: Double { guard collectionView.contentSize.height > 0 else { return 0 } return Double(((collectionView.contentOffset.y + collectionView.bounds.height) / collectionView.contentSize.height) * 100) } var _maxViewed: Double = 0 var maxViewed: Double { return min(max(_maxViewed, percentViewed), 100) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) _maxViewed = max(_maxViewed, percentViewed) } // MARK: - CollectionViewFooterDelegate func collectionViewFooterButtonWasPressed(_ collectionViewFooter: CollectionViewFooter) { } } extension ColumnarCollectionViewController: UICollectionViewDataSource { open func numberOfSections(in collectionView: UICollectionView) -> Int { return 0 } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPath) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionHeader { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewHeader.identifier, for: indexPath) guard let header = view as? CollectionViewHeader else { return view } configure(header: header, forSectionAt: indexPath.section, layoutOnly: false) return header } else if kind == UICollectionView.elementKindSectionFooter { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewFooter.identifier, for: indexPath) guard let footer = view as? CollectionViewFooter else { return view } configure(footer: footer, forSectionAt: indexPath.section, layoutOnly: false) return footer } return UICollectionReusableView() } } extension ColumnarCollectionViewController: UICollectionViewDelegate { } // MARK: - WMFArticlePreviewingActionsDelegate extension ColumnarCollectionViewController: WMFArticlePreviewingActionsDelegate { func saveArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, didSave: Bool, articleURL: URL) { if let eventLoggingEventValuesProviding = self as? EventLoggingEventValuesProviding { if didSave { ReadingListsFunnel.shared.logSave(category: eventLoggingEventValuesProviding.eventLoggingCategory, label: eventLoggingEventValuesProviding.eventLoggingLabel, articleURL: articleURL) } else { ReadingListsFunnel.shared.logUnsave(category: eventLoggingEventValuesProviding.eventLoggingCategory, label: eventLoggingEventValuesProviding.eventLoggingLabel, articleURL: articleURL) } } } func readMoreArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) { articleController.wmf_removePeekableChildViewControllers() wmf_push(articleController, animated: true) } func shareArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, shareActivityController: UIActivityViewController) { articleController.wmf_removePeekableChildViewControllers() present(shareActivityController, animated: true, completion: nil) } func viewOnMapArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) { articleController.wmf_removePeekableChildViewControllers() let placesURL = NSUserActivity.wmf_URLForActivity(of: .places, withArticleURL: articleController.articleURL) UIApplication.shared.open(placesURL, options: [:], completionHandler: nil) } } extension ColumnarCollectionViewController { func wmf_push(_ viewController: UIViewController, context: FeedFunnelContext?, index: Int?, animated: Bool) { logFeedEventIfNeeded(for: context, index: index, pushedViewController: viewController) wmf_push(viewController, animated: animated) } func logFeedEventIfNeeded(for context: FeedFunnelContext?, index: Int?, pushedViewController: UIViewController) { guard navigationController != nil, let viewControllers = navigationController?.viewControllers else { return } let isFirstViewControllerExplore = viewControllers.first is ExploreViewController let isPushedFromExplore = viewControllers.count == 1 && isFirstViewControllerExplore let isPushedFromExploreDetail = viewControllers.count == 2 && isFirstViewControllerExplore if isPushedFromExplore { let isArticle = pushedViewController is WMFArticleViewController if isArticle { FeedFunnel.shared.logFeedCardReadingStarted(for: context, index: index) } else { FeedFunnel.shared.logFeedCardOpened(for: context) } } else if isPushedFromExploreDetail { FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: context, index: index, maxViewed: maxViewed) } } }
mit
1a7ee9042898c216b448c03c594cf902
40.428246
214
0.692583
6.162996
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/DescriptionWelcomePanelViewController.swift
1
4670
class DescriptionWelcomePanelViewController: UIViewController, Themeable { private var theme = Theme.standard func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } scrollViewGradientView.apply(theme: theme) titleLabel.textColor = theme.colors.primaryText bottomLabel.textColor = theme.colors.primaryText nextButton.backgroundColor = theme.colors.link } @IBOutlet private var containerView:UIView! @IBOutlet private var titleLabel:UILabel! @IBOutlet private var bottomLabel:UILabel! @IBOutlet private var nextButton:AutoLayoutSafeMultiLineButton! @IBOutlet private var scrollView:UIScrollView! @IBOutlet private var scrollViewGradientView:WelcomePanelScrollViewGradient! @IBOutlet private var nextButtonContainerView:UIView! private var viewControllerForContainerView:UIViewController? = nil var pageType:DescriptionWelcomePageType = .intro override func viewDidLoad() { super.viewDidLoad() apply(theme: theme) embedContainerControllerView() updateUIStrings() // If the button itself was directly an arranged stackview subview we couldn't // set padding contraints and also get clean collapsing when enabling isHidden. nextButtonContainerView.isHidden = pageType != .exploration view.wmf_configureSubviewsForDynamicType() } private func embedContainerControllerView() { let containerController = DescriptionWelcomeContentsViewController.wmf_viewControllerFromDescriptionWelcomeStoryboard() containerController.pageType = pageType addChild(containerController) containerView.wmf_addSubviewWithConstraintsToEdges(containerController.view) containerController.apply(theme: theme) containerController.didMove(toParent: self) } private func updateUIStrings(){ switch pageType { case .intro: titleLabel.text = WMFLocalizedString("description-welcome-descriptions-title", value:"Title descriptions", comment:"Title text explaining title descriptions") case .exploration: titleLabel.text = WMFLocalizedString("description-welcome-concise-title", value:"Keep it short", comment:"Title text explaining descriptions should be concise") } bottomLabel.text = CommonStrings.welcomePromiseTitle nextButton.setTitle(WMFLocalizedString("description-welcome-start-editing-button", value:"Start editing", comment:"Text for button for dismissing description editing welcome screens"), for: .normal) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if scrollView.wmf_contentSizeHeightExceedsBoundsHeight() { scrollView.wmf_flashVerticalScrollIndicatorAfterDelay(1.5) } } } private extension UIScrollView { func wmf_contentSizeHeightExceedsBoundsHeight() -> Bool { return contentSize.height - bounds.size.height > 0 } func wmf_flashVerticalScrollIndicatorAfterDelay(_ delay: TimeInterval) { dispatchOnMainQueueAfterDelayInSeconds(delay) { self.flashScrollIndicators() } } } class WelcomePanelScrollViewGradient : UIView, Themeable { private var theme = Theme.standard func apply(theme: Theme) { self.theme = theme layer.backgroundColor = theme.colors.midBackground.cgColor } private let fadeHeight = 6.0 private var normalizedFadeHeight: Double { return bounds.size.height > 0 ? fadeHeight / Double(bounds.size.height) : 0 } private lazy var gradientMask: CAGradientLayer = { let mask = CAGradientLayer() mask.startPoint = .zero mask.endPoint = CGPoint(x: 0, y: 1) mask.colors = [ UIColor.black.cgColor, UIColor.clear.cgColor, UIColor.clear.cgColor, UIColor.black.cgColor ] layer.mask = mask return mask }() override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) guard layer == gradientMask.superlayer else { assertionFailure("Unexpected superlayer") return } gradientMask.locations = [ // Keep fade heights fixed to `fadeHeight` regardless of text view height 0.0, NSNumber(value: normalizedFadeHeight), // upper stop NSNumber(value: 1.0 - normalizedFadeHeight), // lower stop 1.0 ] gradientMask.frame = bounds } }
mit
7a5dfd83652ab22a205d5174e41878f6
37.916667
206
0.682013
5.411356
false
false
false
false
luzefeng/iOS8-day-by-day
39-watchkit/NightWatch/NightWatchData/NightWatchQuotes.swift
22
1534
// // Copyright 2014 Scott Logic // // 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 typealias Quote = String public class NightWatchQuotes { private var quotes = [Quote]() public init(array: [String]) { quotes = array } public convenience init(plistName: String) { let bundle = NSBundle(identifier: "com.shinobicontrols.NightWatchData") let path = bundle!.pathForResource("NightWatchQuotes", ofType: "plist") if let array = NSArray(contentsOfFile: path!) as? [String] { self.init(array: array) } else { self.init(array: [Quote]()) } } public convenience init() { self.init(plistName: "NightWatchQuotes") } public func randomQuote() -> Quote { let rnd = Int(arc4random_uniform(UInt32(quotes.count))) return quotes[rnd] } public func randomQuotes(number: Int) -> [Quote] { var quoteList = [Quote]() while quoteList.count < number { quoteList += [randomQuote()] } return quoteList } }
apache-2.0
8efe55abf852150a16f2118e2616ed65
25.912281
75
0.681226
4.015707
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/EntryHTMLEditorViewController.swift
1
7637
// // EntryHTMLEditorViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/05. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import ZSSRichTextEditor class EntryHTMLEditorViewController: BaseViewController, UITextViewDelegate, AddAssetDelegate { var sourceView: ZSSTextView! var object: EntryTextAreaItem! var blog: Blog! var entry: BaseEntry! override func viewDidLoad() { super.viewDidLoad() self.title = object.label // Do any additional setup after loading the view. self.sourceView = ZSSTextView(frame: self.view.bounds) self.sourceView.autocapitalizationType = UITextAutocapitalizationType.None self.sourceView.autocorrectionType = UITextAutocorrectionType.No //self.sourceView.font = UIFont.systemFontOfSize(16.0) self.sourceView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] self.sourceView.autoresizesSubviews = true self.sourceView.delegate = self self.view.addSubview(self.sourceView) self.sourceView.text = object.text self.sourceView.selectedRange = NSRange() let toolBar = UIToolbar(frame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0)) let modeImage = UIImageView(image: UIImage(named: "ico_html")) let modeButton = UIBarButtonItem(customView: modeImage) let cameraButton = UIBarButtonItem(image: UIImage(named: "btn_camera"), left: true, target: self, action: "cameraButtonPushed:") let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let previewButton = UIBarButtonItem(image: UIImage(named: "btn_preview"), style: UIBarButtonItemStyle.Plain, target: self, action: "previewButtonPushed:") let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:") if object is BlockTextItem || object.isCustomField { toolBar.items = [modeButton, flexibleButton, previewButton, doneButton] } else { toolBar.items = [cameraButton, modeButton, flexibleButton, previewButton, doneButton] } self.sourceView.inputAccessoryView = toolBar self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:") self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:") self.sourceView.becomeFirstResponder() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillChangeFrameNotification, object: nil) } override func viewDidDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } 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. } */ func keyboardWillShow(notification: NSNotification) { var info = notification.userInfo! let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 var insets = self.sourceView.contentInset insets.bottom = keyboardFrame.size.height UIView.animateWithDuration(duration, animations: {_ in self.sourceView.contentInset = insets; } ) } func keyboardWillHide(notification: NSNotification) { var info = notification.userInfo! // var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 var insets = self.sourceView.contentInset insets.bottom = 0 UIView.animateWithDuration(duration, animations: {_ in self.sourceView.contentInset = insets; } ) } @IBAction func saveButtonPushed(sender: UIBarButtonItem) { object.text = sourceView.text object.isDirty = true self.navigationController?.popViewControllerAnimated(true) } @IBAction func doneButtonPushed(sender: UIBarButtonItem) { self.sourceView.resignFirstResponder() } private func showAssetSelector() { let storyboard: UIStoryboard = UIStoryboard(name: "ImageSelector", bundle: nil) let nav = storyboard.instantiateInitialViewController() as! UINavigationController let vc = nav.topViewController as! ImageSelectorTableViewController vc.blog = blog vc.delegate = self vc.showAlign = true vc.object = EntryImageItem() vc.entry = entry self.presentViewController(nav, animated: true, completion: nil) } @IBAction func cameraButtonPushed(sender: UIBarButtonItem) { self.showAssetSelector() } func AddAssetDone(controller: AddAssetTableViewController, asset: Asset) { self.dismissViewControllerAnimated(false, completion: { let vc = controller as! ImageSelectorTableViewController let item = vc.object item.asset = asset let align = controller.imageAlign self.object.assets.append(asset) self.sourceView.replaceRange(self.sourceView.selectedTextRange!, withText: asset.imageHTML(align)) }) } func AddAssetsDone(controller: AddAssetTableViewController) { } func AddOfflineImageDone(controller: AddAssetTableViewController, item: EntryImageItem) { } func AddOfflineImageStorageError(controller: AddAssetTableViewController, item: EntryImageItem) { } @IBAction func backButtonPushed(sender: UIBarButtonItem) { if self.sourceView.text == object.text { self.navigationController?.popViewControllerAnimated(true) return } Utils.confrimSave(self) } @IBAction func previewButtonPushed(sender: UIBarButtonItem) { let vc = PreviewViewController() let nav = UINavigationController(rootViewController: vc) var html = "<!DOCTYPE html><html><head><title>Preview</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head><body>" html += self.sourceView.text html += "</body></html>" vc.html = html self.presentViewController(nav, animated: true, completion: nil) } }
mit
526d7d2bfaae32eb06019d13c37b7f60
40.494565
162
0.685789
5.313152
false
false
false
false
SwiftAndroid/swift
test/Interpreter/SDK/CGImportAsMember.swift
2
1592
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: OS=macosx import Foundation import CoreGraphics class Colors { // TODO: when issue is fixed, migrate these to CGColor class properties static var black = CGColor.constantColorForName(CGColor.black)! static var white = CGColor.constantColorForName(CGColor.white)! // FIXME: this triggers an assert in SILVerifier static var clear = CGColor.constantColorForName(CGColor.clear)! class func printColors() { print("Colors") // CHECK: Colors print(black) // CHECK: Generic Gray Profile print(white) // CHECK: Generic Gray Profile print(clear) // CHECK: Generic Gray Profile } } // TODO: ColorSpaces with their empty-argument-label pattern, when issue is // fixed. class Events { static var mouseDefault = CGEventMouseSubtype.defaultType static var mouseTabletPoint = CGEventMouseSubtype.tabletPoint static var tapDefault = CGEventTapOptions.defaultTap static var tapListenOnly = CGEventTapOptions.listenOnly static var privateID = CGEventSourceStateID.privateState static var combinedSessionID = CGEventSourceStateID.combinedSessionState class func printEvents() { print("Events") // CHECK-LABEL: Events print(mouseDefault.rawValue) // CHECK: 0 print(mouseTabletPoint.rawValue) // CHECK: 1 print(tapDefault.rawValue) // CHECK: 0 print(tapListenOnly.rawValue) // CHECK: 1 print(privateID.rawValue) // CHECK: -1 print(combinedSessionID.rawValue) // CHECK: 0 } } Colors.printColors() Events.printEvents()
apache-2.0
947ea14ce451ebe2ef81aae6365ecb1f
31.489796
76
0.738065
3.911548
false
false
false
false
leo150/Pelican
Sources/Pelican/Session/Modules/API Request/Admin.swift
1
3146
// // Admin.swift // Pelican // // Created by Takanu Kyriako on 20/08/2017. // import Foundation import Vapor /** A delegate for a session, to send requests to Telegram that correspond with administrating a group. One of a collection of delegates used to let Sessions make requests to Telegram in a language and format thats concise, descriptive and direct. */ public class TGAdmin { var chatID: Int var tag: SessionTag init(chatID: Int, tag: SessionTag) { self.chatID = chatID self.tag = tag } /** Kicks a user from the chat. */ public func kick(_ userID: Int) { let request = TelegramRequest.kickChatMember(chatID: chatID, userID: userID) _ = tag.sendRequest(request) } /** Unbans a user from the chat. */ public func unban(_ userID: Int) { let request = TelegramRequest.unbanChatMember(chatID: chatID, userID: userID) _ = tag.sendRequest(request) } /** Applies chat restrictions to a user. */ public func restrict(_ userID: Int, restrictUntil: Int?, restrictions: (msg: Bool, media: Bool, stickers: Bool, webPreview: Bool)?) { let request = TelegramRequest.restrictChatMember(chatID: chatID, userID: userID, restrictUntil: restrictUntil, restrictions: restrictions) _ = tag.sendRequest(request) } /** Promotes a user to an admin, while being able to define the privileges they have. */ public func promote(_ userID: Int, rights: (info: Bool, msg: Bool, edit: Bool, delete: Bool, invite: Bool, restrict: Bool, pin: Bool, promote: Bool)?) { let request = TelegramRequest.promoteChatMember(chatID: chatID, userID: userID, rights: rights) _ = tag.sendRequest(request) } /** Returns an already existing invite link, or generates one if none currently exist. */ public func getInviteLink() { let request = TelegramRequest.exportChatInviteLink(chatID: chatID) _ = tag.sendRequest(request) } /** Sets the profile photo for the chat, using a `FileLink`. */ public func setChatPhoto(file: MessageFile) { let request = TelegramRequest.setChatPhoto(chatID: chatID, file: file) _ = tag.sendRequest(request) } /** Deletes the currently set chat photo. */ public func deleteChatPhoto() { let request = TelegramRequest.deleteChatPhoto(chatID: chatID) _ = tag.sendRequest(request) } /** Sets the chat name/title. */ public func setChatTitle(_ title: String) { let request = TelegramRequest.setChatTitle(chatID: chatID, title: title) _ = tag.sendRequest(request) } /** Sets the chat description. */ public func setChatDescription(_ description: String) { let request = TelegramRequest.setChatDescription(chatID: chatID, description: description) _ = tag.sendRequest(request) } /** Pins a message using the given message ID. */ public func pin(messageID: Int, disableNtf: Bool = false) { let request = TelegramRequest.pinChatMessage(chatID: chatID, messageID: messageID, disableNtf: disableNtf) _ = tag.sendRequest(request) } /** Unpins the currently pinned message. */ public func unpin() { let request = TelegramRequest.unpinChatMessage(chatID: chatID) _ = tag.sendRequest(request) } }
mit
d19f544ed91adb0ee0741389f4bfa4b7
23.968254
153
0.708519
3.546787
false
false
false
false
ello/ello-ios
Specs/Controllers/Login/LoginViewControllerSpec.swift
1
3680
//// /// LoginViewControllerSpec.swift // @testable import Ello import Quick import Nimble class LoginViewControllerSpec: QuickSpec { class MockScreen: LoginScreenProtocol { var blackBarIsVisible: Bool = false var username: String = "" var isUsernameValid: Bool? var password: String = "" var isPasswordValid: Bool? var isOnePasswordAvailable: Bool = false var inputsEnabled = true var error: String? var resignedFirstResponder = false func loadingHUD(visible: Bool) { inputsEnabled = !visible } func showError(_ text: String) { error = text } func hideError() { error = nil } func resignFirstResponder() -> Bool { resignedFirstResponder = true return true } } override func spec() { describe("LoginViewController") { var subject: LoginViewController! var mockScreen: MockScreen! beforeEach { subject = LoginViewController() mockScreen = MockScreen() subject.screen = mockScreen showController(subject) } describe("submitting successful credentials") { let email = "[email protected]" let password = "password" beforeEach { var token = AuthToken() token.username = "" token.password = "" subject.submit(username: email, password: password) } it("stores the email and password") { let token = AuthToken() expect(token.username) == email expect(token.password) == password } } describe("submitting") { context("input is valid email") { let username = "[email protected]" let password = "12345678" beforeEach { subject.submit(username: username, password: password) } it("resigns first responder") { expect(mockScreen.resignedFirstResponder) == true } it("disables input") { expect(mockScreen.inputsEnabled) == false } } context("input is valid username") { let username = "name" let password = "12345678" beforeEach { subject.submit(username: username, password: password) } it("resigns first responder") { expect(mockScreen.resignedFirstResponder) == true } it("disables input") { expect(mockScreen.inputsEnabled) == false } } context("input is invalid") { let username = "invalid email" let password = "abc" beforeEach { subject.submit(username: username, password: password) } it("resigns first responder") { expect(mockScreen.resignedFirstResponder) == true } it("does not disable input") { expect(mockScreen.inputsEnabled) == true } } } } } }
mit
5c3bc3f87997f4a7df4710acf8d36a2f
29.666667
78
0.458696
6.174497
false
false
false
false
meetkei/KeiSwiftFramework
KeiSwiftFramework/View/Label/KUnderlineLabel.swift
1
4544
// // KUnderlineLabel.swift // // Copyright (c) 2016 Keun young Kim <[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 UIKit @IBDesignable open class KUnderlineLabel: UIView { fileprivate let label = UILabel() fileprivate let underlineView = UIView() fileprivate var userConstraint = [NSLayoutConstraint]() @IBInspectable open var text: String? { didSet { label.text = text } } @IBInspectable open var topMargin: Double = 10 { didSet { setupView() } } @IBInspectable open var bottomMargin: Double = 10 { didSet { setupView() } } @IBInspectable open var underlineHidden: Bool = false { didSet { setupView() } } @IBInspectable open var fontSize: CGFloat = 13 { didSet { label.font = UIFont.systemFont(ofSize: fontSize) } } @IBInspectable open var textColor: UIColor = UIColor(red: 35.0/255.0, green: 39.0/255.0, blue: 57.0/255.0, alpha: 1.0) { didSet { label.textColor = textColor } } @IBInspectable open var underlineColor: UIColor = UIColor(red: 149.0/255.0, green: 150.0/255.0, blue: 156.0/255.0, alpha: 1.0) { didSet { underlineView.backgroundColor = underlineColor } } public override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } func setupView() { for subView in subviews { subView.removeFromSuperview() } if userConstraint.count > 0 { removeConstraints(userConstraint) userConstraint.removeAll(keepingCapacity: false) } label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.systemFont(ofSize: fontSize) label.textColor = textColor label.text = text addSubview(label) if underlineHidden == false { underlineView.translatesAutoresizingMaskIntoConstraints = false underlineView.isUserInteractionEnabled = false underlineView.backgroundColor = underlineColor addSubview(underlineView) } let metrics = ["top": NSNumber(value: topMargin as Double), "bottom": NSNumber(value: bottomMargin as Double)] let views = ["label": label, "underline": underlineView] var horz = NSLayoutConstraint.constraints(withVisualFormat: "|[label]|", options: [], metrics: nil, views: views) addConstraints(horz) if underlineHidden { let vert = NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[label]-bottom-|", options: [], metrics: metrics, views: views) addConstraints(vert) } else { horz = NSLayoutConstraint.constraints(withVisualFormat: "|[underline]|", options: [], metrics: nil, views: views) addConstraints(horz) let vert = NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[label]-bottom-[underline(1)]|", options: [], metrics: metrics, views: views) addConstraints(vert) } } }
mit
caf94141095a8b95d04418437115b166
29.911565
158
0.614217
5.020994
false
false
false
false
googlearchive/office-mover-5000
ios/OfficeMover5000/OfficeMover5000/PopoverMenuController.swift
4
2026
// // PopoverMenuController.swift // OfficeMover500 // // Created by Katherine Fang on 10/30/14. // Copyright (c) 2014 Firebase. All rights reserved. // import UIKit @objc protocol PopoverMenuDelegate { func dismissPopover(animated: Bool) optional func addNewItem(type: String) func setBackgroundLocally(type: String) optional func setBackground(type: String) } class PopoverMenuController : UITableViewController { var delegate: PopoverMenuDelegate? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.backgroundColor = UIColor.clearColor() // iOS 8 } override func viewDidLoad() { super.viewDidLoad() preferredContentSize.height = 70 * CGFloat(numItems) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numItems } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: PopoverMenuItemCell! = tableView.dequeueReusableCellWithIdentifier("menuItemCell") as? PopoverMenuItemCell if cell == nil { cell = PopoverMenuItemCell(style: .Default, reuseIdentifier: "menuItemCell") } // Definitely exists now populateCell(cell, row: indexPath.row) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70 } // Dismiss the popover func dismissPopover(animated: Bool) { delegate?.dismissPopover(animated) // iOS 7 dismissViewControllerAnimated(animated, nil) // iOS 8 } // Override this in subclass var numItems: Int { return 0 } // Override this in subclass func populateCell(cell: PopoverMenuItemCell, row: Int) {} }
mit
8121140d3b979b89644f06b2b02cfdee
29.253731
124
0.674729
5.248705
false
false
false
false
christophhagen/Signal-iOS
Signal/src/call/CallAudioService.swift
1
20830
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import AVFoundation import SignalServiceKit import SignalMessaging public let CallAudioServiceSessionChanged = Notification.Name("CallAudioServiceSessionChanged") struct AudioSource: Hashable { let image: UIImage let localizedName: String let portDescription: AVAudioSessionPortDescription? // The built-in loud speaker / aka speakerphone let isBuiltInSpeaker: Bool // The built-in quiet speaker, aka the normal phone handset receiver earpiece let isBuiltInEarPiece: Bool init(localizedName: String, image: UIImage, isBuiltInSpeaker: Bool, isBuiltInEarPiece: Bool, portDescription: AVAudioSessionPortDescription? = nil) { self.localizedName = localizedName self.image = image self.isBuiltInSpeaker = isBuiltInSpeaker self.isBuiltInEarPiece = isBuiltInEarPiece self.portDescription = portDescription } init(portDescription: AVAudioSessionPortDescription) { let isBuiltInEarPiece = portDescription.portType == AVAudioSessionPortBuiltInMic // portDescription.portName works well for BT linked devices, but if we are using // the built in mic, we have "iPhone Microphone" which is a little awkward. // In that case, instead we prefer just the model name e.g. "iPhone" or "iPad" let localizedName = isBuiltInEarPiece ? UIDevice.current.localizedModel : portDescription.portName self.init(localizedName: localizedName, image:#imageLiteral(resourceName: "button_phone_white"), // TODO isBuiltInSpeaker: false, isBuiltInEarPiece: isBuiltInEarPiece, portDescription: portDescription) } // Speakerphone is handled separately from the other audio routes as it doesn't appear as an "input" static var builtInSpeaker: AudioSource { return self.init(localizedName: NSLocalizedString("AUDIO_ROUTE_BUILT_IN_SPEAKER", comment: "action sheet button title to enable built in speaker during a call"), image: #imageLiteral(resourceName: "button_phone_white"), //TODO isBuiltInSpeaker: true, isBuiltInEarPiece: false) } // MARK: Hashable static func ==(lhs: AudioSource, rhs: AudioSource) -> Bool { // Simply comparing the `portDescription` vs the `portDescription.uid` // caused multiple instances of the built in mic to turn up in a set. if lhs.isBuiltInSpeaker && rhs.isBuiltInSpeaker { return true } if lhs.isBuiltInSpeaker || rhs.isBuiltInSpeaker { return false } guard let lhsPortDescription = lhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } guard let rhsPortDescription = rhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } return lhsPortDescription.uid == rhsPortDescription.uid } var hashValue: Int { guard let portDescription = self.portDescription else { assert(self.isBuiltInSpeaker) return "Built In Speaker".hashValue } return portDescription.uid.hash } } @objc class CallAudioService: NSObject, CallObserver { private var vibrateTimer: Timer? private let audioPlayer = AVAudioPlayer() private let handleRinging: Bool class Sound: NSObject { static let incomingRing = Sound(filePath: "r", fileExtension: "caf", loop: true) static let outgoingRing = Sound(filePath: "outring", fileExtension: "mp3", loop: true) static let dialing = Sound(filePath: "sonarping", fileExtension: "mp3", loop: true) static let busy = Sound(filePath: "busy", fileExtension: "mp3", loop: false) static let failure = Sound(filePath: "failure", fileExtension: "mp3", loop: false) let filePath: String let fileExtension: String let url: URL let loop: Bool init(filePath: String, fileExtension: String, loop: Bool) { self.filePath = filePath self.fileExtension = fileExtension self.url = Bundle.main.url(forResource: self.filePath, withExtension: self.fileExtension)! self.loop = loop } lazy var player: AVAudioPlayer? = { let newPlayer: AVAudioPlayer? do { try newPlayer = AVAudioPlayer(contentsOf: self.url, fileTypeHint: nil) if self.loop { newPlayer?.numberOfLoops = -1 } } catch { owsFail("\(self.logTag) failed to build audio player with error: \(error)") newPlayer = nil } return newPlayer }() } // MARK: Vibration config private let vibrateRepeatDuration = 1.6 // Our ring buzz is a pair of vibrations. // `pulseDuration` is the small pause between the two vibrations in the pair. private let pulseDuration = 0.2 var audioSession: CallAudioSession { return CallAudioSession.shared } // MARK: - Initializers init(handleRinging: Bool) { self.handleRinging = handleRinging super.init() SwiftSingletons.register(self) // Configure audio session so we don't prompt user with Record permission until call is connected. audioSession.configure() } // MARK: - CallObserver internal func stateDidChange(call: SignalCall, state: CallState) { AssertIsOnMainThread() self.handleState(call:call) } internal func muteDidChange(call: SignalCall, isMuted: Bool) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } internal func holdDidChange(call: SignalCall, isOnHold: Bool) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } internal func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } private func ensureProperAudioSession(call: SignalCall?) { AssertIsOnMainThread() guard let call = call else { setAudioSession(category: AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault) return } // Disallow bluetooth while (and only while) the user has explicitly chosen the built in receiver. // // NOTE: I'm actually not sure why this is required - it seems like we should just be able // to setPreferredInput to call.audioSource.portDescription in this case, // but in practice I'm seeing the call revert to the bluetooth headset. // Presumably something else (in WebRTC?) is touching our shared AudioSession. - mjk let options: AVAudioSessionCategoryOptions = call.audioSource?.isBuiltInEarPiece == true ? [] : [.allowBluetooth] if call.state == .localRinging { // SoloAmbient plays through speaker, but respects silent switch setAudioSession(category: AVAudioSessionCategorySoloAmbient, mode: AVAudioSessionModeDefault) } else if call.state == .connected, call.hasLocalVideo { // Because ModeVideoChat affects gain, we don't want to apply it until the call is connected. // otherwise sounds like ringing will be extra loud for video vs. speakerphone // Apple Docs say that setting mode to AVAudioSessionModeVideoChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVideoChat, options: options) } else { // Apple Docs say that setting mode to AVAudioSessionModeVoiceChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVoiceChat, options: options) } let session = AVAudioSession.sharedInstance() do { // It's important to set preferred input *after* ensuring properAudioSession // because some sources are only valid for certain category/option combinations. let existingPreferredInput = session.preferredInput if existingPreferredInput != call.audioSource?.portDescription { Logger.info("\(self.logTag) changing preferred input: \(String(describing: existingPreferredInput)) -> \(String(describing: call.audioSource?.portDescription))") try session.setPreferredInput(call.audioSource?.portDescription) } if call.isSpeakerphoneEnabled || (call.hasLocalVideo && call.state != .connected) { // We want consistent ringer-volume between speaker-phone and video chat. // But because using VideoChat mode has noticeably higher output gain, we treat // video chat like speakerphone mode until the call is connected. Logger.verbose("\(self.logTag) enabling speakerphone overrideOutputAudioPort(.speaker)") try session.overrideOutputAudioPort(.speaker) } else { Logger.verbose("\(self.logTag) disabling spearkerphone overrideOutputAudioPort(.none) ") try session.overrideOutputAudioPort(.none) } } catch { owsFail("\(self.logTag) failed setting audio source with error: \(error) isSpeakerPhoneEnabled: \(call.isSpeakerphoneEnabled)") } } // MARK: - Service action handlers public func didUpdateVideoTracks(call: SignalCall?) { Logger.verbose("\(self.logTag) in \(#function)") self.ensureProperAudioSession(call: call) } public func handleState(call: SignalCall) { assert(Thread.isMainThread) Logger.verbose("\(self.logTag) in \(#function) new state: \(call.state)") // Stop playing sounds while switching audio session so we don't // get any blips across a temporary unintended route. stopPlayingAnySounds() self.ensureProperAudioSession(call: call) switch call.state { case .idle: handleIdle(call: call) case .dialing: handleDialing(call: call) case .answering: handleAnswering(call: call) case .remoteRinging: handleRemoteRinging(call: call) case .localRinging: handleLocalRinging(call: call) case .connected: handleConnected(call: call) case .localFailure: handleLocalFailure(call: call) case .localHangup: handleLocalHangup(call: call) case .remoteHangup: handleRemoteHangup(call: call) case .remoteBusy: handleBusy(call: call) } } private func handleIdle(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") } private func handleDialing(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() // HACK: Without this async, dialing sound only plays once. I don't really understand why. Does the audioSession // need some time to settle? Is somethign else interrupting our session? DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { self.play(sound: Sound.dialing) } } private func handleAnswering(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() } private func handleRemoteRinging(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() self.play(sound: Sound.outgoingRing) } private func handleLocalRinging(call: SignalCall) { Logger.debug("\(self.logTag) in \(#function)") AssertIsOnMainThread() startRinging(call: call) } private func handleConnected(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() } private func handleLocalFailure(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() play(sound: Sound.failure) } private func handleLocalHangup(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() handleCallEnded(call: call) } private func handleRemoteHangup(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() vibrate() handleCallEnded(call:call) } private func handleBusy(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() play(sound: Sound.busy) // Let the busy sound play for 4 seconds. The full file is longer than necessary DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4.0) { self.handleCallEnded(call: call) } } private func handleCallEnded(call: SignalCall) { Logger.debug("\(self.logTag) \(#function)") AssertIsOnMainThread() // Stop solo audio, revert to default. setAudioSession(category: AVAudioSessionCategoryAmbient) } // MARK: Playing Sounds var currentPlayer: AVAudioPlayer? private func stopPlayingAnySounds() { currentPlayer?.stop() stopAnyRingingVibration() } private func play(sound: Sound) { guard let newPlayer = sound.player else { owsFail("\(self.logTag) unable to build player") return } Logger.info("\(self.logTag) playing sound: \(sound.filePath)") // It's important to stop the current player **before** starting the new player. In the case that // we're playing the same sound, since the player is memoized on the sound instance, we'd otherwise // stop the sound we just started. self.currentPlayer?.stop() newPlayer.play() self.currentPlayer = newPlayer } // MARK: - Ringing private func startRinging(call: SignalCall) { guard handleRinging else { Logger.debug("\(self.logTag) ignoring \(#function) since CallKit handles it's own ringing state") return } vibrateTimer = WeakTimer.scheduledTimer(timeInterval: vibrateRepeatDuration, target: self, userInfo: nil, repeats: true) {[weak self] _ in self?.ringVibration() } vibrateTimer?.fire() play(sound: Sound.incomingRing) } private func stopAnyRingingVibration() { guard handleRinging else { Logger.debug("\(self.logTag) ignoring \(#function) since CallKit handles it's own ringing state") return } Logger.debug("\(self.logTag) in \(#function)") // Stop vibrating vibrateTimer?.invalidate() vibrateTimer = nil } // public so it can be called by timer via selector public func ringVibration() { // Since a call notification is more urgent than a message notifaction, we // vibrate twice, like a pulse, to differentiate from a normal notification vibration. vibrate() DispatchQueue.default.asyncAfter(deadline: DispatchTime.now() + pulseDuration) { self.vibrate() } } func vibrate() { // TODO implement HapticAdapter for iPhone7 and up AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } // MARK - AudioSession MGMT // TODO move this to CallAudioSession? // Note this method is sensitive to the current audio session configuration. // Specifically if you call it while speakerphone is enabled you won't see // any connected bluetooth routes. var availableInputs: [AudioSource] { let session = AVAudioSession.sharedInstance() guard let availableInputs = session.availableInputs else { // I'm not sure why this would happen, but it may indicate an error. // In practice, I haven't seen it on iOS9+. // // I *have* seen it on iOS8, but it doesn't seem to cause any problems, // so we do *not* trigger the assert on that platform. if #available(iOS 9.0, *) { owsFail("No available inputs or inputs not ready") } return [AudioSource.builtInSpeaker] } Logger.info("\(self.logTag) in \(#function) availableInputs: \(availableInputs)") return [AudioSource.builtInSpeaker] + availableInputs.map { portDescription in return AudioSource(portDescription: portDescription) } } func currentAudioSource(call: SignalCall) -> AudioSource? { if let audioSource = call.audioSource { return audioSource } // Before the user has specified an audio source on the call, we rely on the existing // system state to determine the current audio source. // If a bluetooth is connected, this will be bluetooth, otherwise // this will be the receiver. let session = AVAudioSession.sharedInstance() guard let portDescription = session.currentRoute.inputs.first else { return nil } return AudioSource(portDescription: portDescription) } private func setAudioSession(category: String, mode: String? = nil, options: AVAudioSessionCategoryOptions = AVAudioSessionCategoryOptions(rawValue: 0)) { AssertIsOnMainThread() let session = AVAudioSession.sharedInstance() var audioSessionChanged = false do { if #available(iOS 10.0, *), let mode = mode { let oldCategory = session.category let oldMode = session.mode let oldOptions = session.categoryOptions guard oldCategory != category || oldMode != mode || oldOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.logTag) audio session changed category: \(oldCategory) -> \(category) ") } if oldMode != mode { Logger.debug("\(self.logTag) audio session changed mode: \(oldMode) -> \(mode) ") } if oldOptions != options { Logger.debug("\(self.logTag) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, mode: mode, options: options) } else { let oldCategory = session.category let oldOptions = session.categoryOptions guard session.category != category || session.categoryOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.logTag) audio session changed category: \(oldCategory) -> \(category) ") } if oldOptions != options { Logger.debug("\(self.logTag) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, with: options) } } catch { let message = "\(self.logTag) in \(#function) failed to set category: \(category) mode: \(String(describing: mode)), options: \(options) with error: \(error)" owsFail(message) } if audioSessionChanged { Logger.info("\(self.logTag) in \(#function)") // Update call view synchronously; already on main thread. NotificationCenter.default.post(name:CallAudioServiceSessionChanged, object: nil) } } }
gpl-3.0
36d28313947bce7e4992d7d021c59ebc
37.574074
177
0.631157
5.114166
false
false
false
false
xu6148152/binea_project_for_ios
Psychologist/Psychologist/DiagnosedHistoryViewController.swift
1
850
// // DiagnosedHistoryViewController.swift // Psychologist // // Created by Binea Xu on 6/14/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import UIKit class DiagnosedHistoryViewController: UIViewController { var text : String = ""{ didSet{ textView?.text = text } } @IBOutlet weak var textView: UITextView!{ didSet{ textView.text = text } } override var preferredContentSize: CGSize{ set{ super.preferredContentSize = newValue } get{ if textView != nil && presentingViewController != nil{ return textView.sizeThatFits(presentingViewController!.view.bounds.size) }else{ return super.preferredContentSize } } } }
mit
df761d2e2a397241bcfa9f48d654d495
20.25
88
0.558824
5.151515
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/User/DrawCashDetailViewController.swift
2
3033
// // DrawCashDetailViewController.swift // viossvc // // Created by 木柳 on 2016/11/27. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD class DrawCashDetailViewController: BaseTableViewController { @IBOutlet weak var bankCardLabel: UILabel! @IBOutlet weak var drawCashCount: UILabel! @IBOutlet weak var drawCashTime: UILabel! @IBOutlet weak var stepIcon1: UIButton! @IBOutlet weak var stepIcon2: UIButton! @IBOutlet weak var stepIcon3: UIButton! var stats: Int?{ didSet{ stepIcon1.selected = stats == 0 stepIcon2.selected = stats == 1 stepIcon3.selected = stats == 2 } } var model: DrawCashRecordModel? //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() initData() initUI() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if model == nil { return } updateUI(model!) navigationItem.hidesBackButton = false navigationItem.rightBarButtonItem = nil } //MARK: --DATA func initData() { if model != nil { return } let object: DrawCashModel = DrawCashModel() object.uid = CurrentUserHelper.shared.userInfo.uid object.account = CurrentUserHelper.shared.userInfo.currentBankCardNumber object.num = 1 object.size = 1 AppAPIHelper.userAPI().drawCashDetail(object, complete: { [weak self](result) in if result == nil{ SVProgressHUD.showErrorMessage(ErrorMessage: "获取提现详情内容失败,请前往提现记录中查看", ForDuration: 1, completion: { self?.navigationController?.pushViewControllerWithIdentifier(DrawCashRecordViewController.className(), animated: true) }) return } let resultModel = result as! DrawCashModel if resultModel.withdraw_record.count >= 0{ let model:DrawCashRecordModel = resultModel.withdraw_record[0] self?.updateUI(model) } }, error: errorBlockFunc()) } //MARK: --UI func initUI() { navigationItem.backBarButtonItem = nil navigationItem.hidesBackButton = true } func updateUI(model: DrawCashRecordModel) { let bankNum = ((model.account)! as NSString).substringWithRange(NSRange.init(location: model.account!.length()-4, length: 4)) let bankName = model.bank_name bankCardLabel.text = "\(bankName!)(\(bankNum))" drawCashCount.text = "¥\(model.cash/100)" drawCashTime.text = model.request_time stats = model.status } @IBAction func finishBtnTapped(sender: AnyObject) { navigationController?.popToRootViewControllerAnimated(true) } }
apache-2.0
ce49ac9d24fe1462d7918bd6b483456b
31.064516
138
0.603286
4.809677
false
false
false
false
iCrany/iOSExample
iOSExample/Module/UIKitExample/UIKitExampleTableViewVC.swift
1
4542
//___FILEHEADER___ import Foundation class UIKitExampleTableViewVC: UIViewController { struct Constant { static let kDemo1: String = "UIScrollView contain UIScrollView" static let kDemo2: String = "AnchorPoint Test Example" static let kDemo3: String = "UIViewController Life Cycle Example" static let kDemo4: String = "Learn Xib Example" static let kDemo5: String = "UITableViewCell Separate line" static let kDemo6: String = "Custom font issue" static let kDemo7: String = "reloadRows: vs reloadData" static let kDemo8: String = "Special font UI" static let kDemo9: String = "UIKit Dynamics" } fileprivate lazy var tableView: UITableView = { let tableView: UITableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 60 return tableView }() fileprivate var dataSource: [String] = [] init () { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.prepareDataSource() self.setupUI() } private func prepareDataSource() { self.dataSource.append(Constant.kDemo1) self.dataSource.append(Constant.kDemo2) self.dataSource.append(Constant.kDemo3) self.dataSource.append(Constant.kDemo4) self.dataSource.append(Constant.kDemo5) self.dataSource.append(Constant.kDemo6) self.dataSource.append(Constant.kDemo7) self.dataSource.append(Constant.kDemo8) self.dataSource.append(Constant.kDemo9) } private func setupUI() { self.title = "UIKit Example" self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } tableView.register(UITableViewCell.self, forCellReuseIdentifier: "default") } } extension UIKitExampleTableViewVC: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedDataSourceStr = self.dataSource[indexPath.row] switch selectedDataSourceStr { case Constant.kDemo1: let vc = UIScrollViewVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo2: let vc = ICAnchorPointVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo3: let vc = ViewControllerLifeCycleVC() print("[xxx] after vc init") self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo4: let vc = LearnXIBVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo5: let vc = UITableViewCellSeparateVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo6: let vc = ICCustomFontVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo7: let vc = LearnTableViewReloadRowVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo8: let vc = SpecialFontUIVC() self.navigationController?.pushViewController(vc, animated: true) case Constant.kDemo9: let vc = UIKitDynamicsExampleVC() self.navigationController?.pushViewController(vc, animated: true) default: break } } } extension UIKitExampleTableViewVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let dataSourceStr: String = self.dataSource[indexPath.row] let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "default") if let cell = tableViewCell { cell.textLabel?.text = dataSourceStr cell.textLabel?.textColor = UIColor.black return cell } else { return UITableViewCell.init(style: .default, reuseIdentifier: "error") } } }
mit
719b2e8a6e6b6655bac470342e228905
33.671756
102
0.654998
4.904968
false
false
false
false
brentdax/swift
test/IRGen/witness_table_indirect_conformances.swift
1
2050
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -swift-version 4 | %FileCheck %s -DINT=i%target-ptrsize protocol P1 { associatedtype AssocP1 } protocol P2 { associatedtype AssocP2: P1 func getAssocP2() -> AssocP2 } protocol P3 { associatedtype AssocP3: P2 where AssocP3.AssocP2: Q func getAssocP3() -> AssocP3 } protocol Q { } struct X { } struct Y: P1, Q { typealias AssocP1 = X } struct Z: P2 { typealias AssocP2 = Y func getAssocP2() -> Y { return Y() } } // CHECK: @"$s35witness_table_indirect_conformances1WVAA2P3AAWP" = hidden global [5 x i8*] [ // CHECK-SAME: @"$s35witness_table_indirect_conformances1WVAA2P3AAMc" // CHECK-SAME: i8* bitcast (i8** ()* @"$s35witness_table_indirect_conformances1YVAA1QAAWa" to i8*), // CHECK-SAME: @"symbolic 35witness_table_indirect_conformances1ZV" // CHECK-SAME: i8* bitcast (void (%T35witness_table_indirect_conformances1ZV*, %T35witness_table_indirect_conformances1WV*, %swift.type*, i8**)* @"$s35witness_table_indirect_conformances1WVAA2P3A2aDP08getAssocE00gE0QzyFTW" to i8*)] struct W: P3 { typealias AssocP3 = Z func getAssocP3() -> Z { return Z() } } // CHECK-LABEL: define hidden i8** @"$s35witness_table_indirect_conformances1YVAA1QAAWa"() // CHECK-NEXT: entry: // CHECK-NEXT: ret i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s35witness_table_indirect_conformances1YVAA1QAAWP", i32 0, i32 0) // CHECK-LABEL: define hidden i8** @"$s35witness_table_indirect_conformances1ZVAA2P2AAWa"() // CHECK-NEXT: entry: // CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @"$s35witness_table_indirect_conformances1ZVAA2P2AAWP", i32 0, i32 0) // CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s35witness_table_indirect_conformances1ZVMa" // CHECK-SAME: ([[INT]]) // CHECK-NEXT: entry: // CHECK-NEXT: ret %swift.metadata_response { %swift.type* bitcast {{.*}} @"$s35witness_table_indirect_conformances1ZVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 }
apache-2.0
0eecc4f8a1d47faacaa1173d63d1a36f
36.272727
231
0.718537
2.966715
false
false
false
false
JeffESchmitz/VirtualTourist
VirtualTourist/Constants.swift
1
3842
// // Constants.swift // VirtualTourist // // Created by Jeff Schmitz on 7/8/16. // Copyright © 2016 Jeff Schmitz. All rights reserved. // import UIKit // MARK: Constants accross application struct Constants { static let MapLatitude = "MapLatitude" static let MapLongitude = "MapLongitude" static let MapLatitudeDelta = "MapLatitudeDelta" static let MapLongitudeDelta = "MapLongitudeDelta" static let DataModelName = "VirtualTourist" static let Latitude = "latitude" static let Longitude = "longitude" static let MapReuseId = "Pin" static let OpenPhotoAlbum = "OpenPhotoAlbum" static let OpenPhotoDetail = "OpenPhotoDetail" static let AllFilesDownloaded = "AllFilesDownloaded" struct ColorPalette { static let UdacityBlue = UIColor(red:0.01, green:0.70, blue:0.89, alpha:1.0) } struct Entity { static let Pin = "Pin" static let Photo = "Photo" static let Title = "title" } } extension Client { struct HttpRequest { static let MethodPOST = "POST" static let AcceptHeaderField = "Accept" static let ContentTypeHeaderField = "Content-Type" static let ContentJSON = "application/json" static let MethodGET = "GET" static let MethodDELETE = "DELETE" static let CookieName = "XSRF-TOKEN" static let XSRFHeaderField = "X-XSRF-TOKEN" } struct Components { static let scheme = "https" static let host = "api.flickr.com" static let path = "/services/rest" } struct Errors { static let domain = "APISession" static let unsuccessfulResponse = "Unsuccessful response." static let noData = "No Data Returned from Request." static let noDataCode = 1000 static let unableToConverData = "Could not parse the data as JSON" static let unableToConverDataCode = 1001 } struct FlickrParameterKeys { static let Method = "method" static let APIKey = "api_key" static let Format = "format" static let NoJsonCallback = "nojsoncallback" static let SafeSearch = "safe_search" static let Extras = "extras" static let Page = "page" static let PerPage = "per_page" static let Latitude = "lat" static let Longitude = "lon" } struct FlickrParameterValues { static let Method = "flickr.photos.search" static let APIKey_Somewhere_Else = "4120b4b57e0c20e206965d809d8d59e4" static let APIKey = "f1aeaeb551dde21a0cecb995ea5ac07f" static let Format = "json" static let NoJsonCallback = "1" static let SafeSearch = "1" static let ExtrasMediumURL = "url_m" static let PerPage = "21" } struct FlickrResponseKeys { static let Status = "stat" static let Code = "code" static let Message = "message" static let PhotosDictionary = "photos" static let PhotoArray = "photo" static let Pages = "pages" static let MediumURL = "url_m" } struct FlickrResponseValues { static let Ok = "ok" static let Fail = "fail" } }
gpl-3.0
56fecfba575d06f9fd8a2eb545383fd2
33.927273
84
0.529289
4.661408
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift
20
3496
// // SwitchIfEmpty.swift // RxSwift // // Created by sergdort on 23/12/2016. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Observable<Element>) -> Observable<Element> { return SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) } } final private class SwitchIfEmpty<Element>: Producer<Element> { private let _source: Observable<Element> private let _ifEmpty: Observable<Element> init(source: Observable<Element>, ifEmpty: Observable<Element>) { self._source = source self._ifEmpty = ifEmpty } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SwitchIfEmptySink(ifEmpty: self._ifEmpty, observer: observer, cancel: cancel) let subscription = sink.run(self._source.asObservable()) return (sink: sink, subscription: subscription) } } final private class SwitchIfEmptySink<Observer: ObserverType>: Sink<Observer> , ObserverType { typealias Element = Observer.Element private let _ifEmpty: Observable<Element> private var _isEmpty = true private let _ifEmptySubscription = SingleAssignmentDisposable() init(ifEmpty: Observable<Element>, observer: Observer, cancel: Cancelable) { self._ifEmpty = ifEmpty super.init(observer: observer, cancel: cancel) } func run(_ source: Observable<Observer.Element>) -> Disposable { let subscription = source.subscribe(self) return Disposables.create(subscription, _ifEmptySubscription) } func on(_ event: Event<Element>) { switch event { case .next: self._isEmpty = false self.forwardOn(event) case .error: self.forwardOn(event) self.dispose() case .completed: guard self._isEmpty else { self.forwardOn(.completed) self.dispose() return } let ifEmptySink = SwitchIfEmptySinkIter(parent: self) self._ifEmptySubscription.setDisposable(self._ifEmpty.subscribe(ifEmptySink)) } } } final private class SwitchIfEmptySinkIter<Observer: ObserverType> : ObserverType { typealias Element = Observer.Element typealias Parent = SwitchIfEmptySink<Observer> private let _parent: Parent init(parent: Parent) { self._parent = parent } func on(_ event: Event<Element>) { switch event { case .next: self._parent.forwardOn(event) case .error: self._parent.forwardOn(event) self._parent.dispose() case .completed: self._parent.forwardOn(event) self._parent.dispose() } } }
mit
fd5247200f567762d5a786e059933eac
32.605769
171
0.635479
4.807428
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/SDE.swift
2
6314
// // SDE.swift // Neocom // // Created by Artem Shimanski on 09.08.2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import CoreData import Futures import Expressible class SDE: PersistentContainer<SDEContext> { override init(persistentContainer: NSPersistentContainer? = nil) { ValueTransformer.setValueTransformer(ImageValueTransformer(), forName: NSValueTransformerName("ImageValueTransformer")) let persistentContainer = persistentContainer ?? { let container = NSPersistentContainer(name: "SDE", managedObjectModel: NSManagedObjectModel(contentsOf: Bundle.main.url(forResource: "SDE", withExtension: "momd")!)!) let description = NSPersistentStoreDescription() description.url = Bundle.main.url(forResource: "SDE", withExtension: "sqlite") description.isReadOnly = true container.persistentStoreDescriptions = [description] container.loadPersistentStores { (_, _) in } return container }() super.init(persistentContainer: persistentContainer) } } struct SDEContext: PersistentContext { var managedObjectContext: NSManagedObjectContext func invType(_ typeID: Int) -> SDEInvType? { return (try? managedObjectContext.from(SDEInvType.self).filter(\SDEInvType.typeID == Int32(typeID)).first()) ?? nil } func invType(_ typeName: String) -> SDEInvType? { return (try? managedObjectContext.from(SDEInvType.self).filter(\SDEInvType.typeName == typeName.caseInsensitive).first()) ?? nil } func invGroup(_ groupID: Int) -> SDEInvGroup? { return (try? managedObjectContext.from(SDEInvGroup.self).filter(\SDEInvGroup.groupID == Int32(groupID)).first()) ?? nil } func invCategory(_ categoryID: Int) -> SDEInvCategory? { return (try? managedObjectContext.from(SDEInvCategory.self).filter(\SDEInvCategory.categoryID == Int32(categoryID)).first()) ?? nil } func invMetaGroup(_ metaGroupID: Int) -> SDEInvMetaGroup? { return (try? managedObjectContext.from(SDEInvMetaGroup.self).filter(\SDEInvMetaGroup.metaGroupID == Int32(metaGroupID)).first()) ?? nil } func chrRace(_ raceID: Int) -> SDEChrRace? { return (try? managedObjectContext.from(SDEChrRace.self).filter(\SDEChrRace.raceID == Int32(raceID)).first()) ?? nil } func chrBloodline(_ bloodlineID: Int) -> SDEChrBloodline? { return (try? managedObjectContext.from(SDEChrBloodline.self).filter(\SDEChrBloodline.bloodlineID == Int32(bloodlineID)).first()) ?? nil } func chrAncestry(_ ancestryID: Int) -> SDEChrAncestry? { return (try? managedObjectContext.from(SDEChrAncestry.self).filter(\SDEChrAncestry.ancestryID == Int32(ancestryID)).first()) ?? nil } func chrFaction(_ factionID: Int) -> SDEChrFaction? { return (try? managedObjectContext.from(SDEChrFaction.self).filter(\SDEChrFaction.factionID == Int32(factionID)).first()) ?? nil } func ramActivity(_ activityID: Int) -> SDERamActivity? { return (try? managedObjectContext.from(SDERamActivity.self).filter(\SDERamActivity.activityID == Int32(activityID)).first()) ?? nil } func eveIcon(_ file: String) -> SDEEveIcon? { return (try? managedObjectContext.from(SDEEveIcon.self).filter(\SDEEveIcon.iconFile == file).first()) ?? nil } func eveIcon(_ name: SDEEveIcon.Name) -> SDEEveIcon? { return (try? managedObjectContext.from(SDEEveIcon.self).filter(\SDEEveIcon.iconFile == name.name).first()) ?? nil } func dgmAttributeType(_ attributeID: Int) -> SDEDgmAttributeType? { return (try? managedObjectContext.from(SDEDgmAttributeType.self).filter(\SDEDgmAttributeType.attributeID == Int32(attributeID)).first()) ?? nil } func mapSolarSystem(_ solarSystemID: Int) -> SDEMapSolarSystem? { return (try? managedObjectContext.from(SDEMapSolarSystem.self).filter(\SDEMapSolarSystem.solarSystemID == Int32(solarSystemID)).first()) ?? nil } func mapConstellation(_ constellationID: Int) -> SDEMapConstellation? { return (try? managedObjectContext.from(SDEMapConstellation.self).filter(\SDEMapConstellation.constellationID == Int32(constellationID)).first()) ?? nil } func mapRegion(_ regionID: Int) -> SDEMapRegion? { return (try? managedObjectContext.from(SDEMapRegion.self).filter(\SDEMapRegion.regionID == Int32(regionID)).first()) ?? nil } func mapPlanet(_ planetID: Int) -> SDEMapPlanet? { return (try? managedObjectContext.from(SDEMapPlanet.self).filter(\SDEMapPlanet.planetID == Int32(planetID)).first()) ?? nil } func staStation(_ stationID: Int) -> SDEStaStation? { return (try? managedObjectContext.from(SDEStaStation.self).filter(\SDEStaStation.stationID == Int32(stationID)).first()) ?? nil } func dgmppItemCategory(categoryID: SDEDgmppItemCategoryID, subcategory: Int? = nil, race: SDEChrRace? = nil) -> SDEDgmppItemCategory? { var request = managedObjectContext.from(SDEDgmppItemCategory.self).filter(\SDEDgmppItemCategory.category == categoryID.rawValue) if let subcategory = subcategory { request = request.filter(\SDEDgmppItemCategory.subcategory == subcategory) } if let race = race { request = request.filter(\SDEDgmppItemCategory.race == race) } return (try? request.first()) ?? nil } } extension SDEInvType { subscript(key: SDEAttributeID) -> SDEDgmTypeAttribute? { return (try? managedObjectContext?.from(SDEDgmTypeAttribute.self).filter(\SDEDgmTypeAttribute.type == self && \SDEDgmTypeAttribute.attributeType?.attributeID == key.rawValue).first()) ?? nil } var dgmppItemCategoryID: SDEDgmppItemCategoryID? { guard let category = (dgmppItem?.groups?.anyObject() as? SDEDgmppItemGroup)?.category?.category else {return nil} return SDEDgmppItemCategoryID(rawValue: category) } } extension SDEWhType { @objc var targetSystemClassDisplayName: String? { switch targetSystemClass { case 0: return NSLocalizedString("Exit WH", comment: "") case 1...6: return String(format: NSLocalizedString("W-Space Class %d", comment: ""), targetSystemClass) case 7: return NSLocalizedString("High-Sec", comment: "") case 8: return NSLocalizedString("Low-Sec", comment: "") case 9: return NSLocalizedString("0.0 System", comment: "") case 12: return NSLocalizedString("Thera", comment: "") case 13: return NSLocalizedString("W-Frig", comment: "") default: return String(format: NSLocalizedString("Unknown Class %d", comment: ""), targetSystemClass) } } }
lgpl-2.1
381a729de2fe0a9c4bf41204993f89d8
39.729032
192
0.740852
3.726682
false
false
false
false
nguyenantinhbk77/practice-swift
Address Book/Inserting a Person Entry into the Address Book/Inserting a Person Entry into the Address Book/AppDelegate.swift
2
4057
// // AppDelegate.swift // Inserting a Person Entry into the Address Book // // Created by Domenico on 26/05/15. // License MIT // import UIKit import AddressBook @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var addressBook: ABAddressBookRef? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { switch ABAddressBookGetAuthorizationStatus(){ case .Authorized: println("Already authorized") createAddressBook() /* Now you can use the address book */ self.newPersonWithFirstName("Domenico", lastName: "Solazzo", inAddressBook: addressBook!) case .Denied: println("You are denied access to address book") case .NotDetermined: createAddressBook() if let theBook: ABAddressBookRef = addressBook{ ABAddressBookRequestAccessWithCompletion(theBook, {(granted: Bool, error: CFError!) in if granted{ println("Access is granted") } else { println("Access is not granted") } }) } case .Restricted: println("Access is restricted") default: println("Unhandled") } return true } func createAddressBook(){ var error: Unmanaged<CFError>? addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue() /* You can use the address book here */ func createAddressBook(){ var error: Unmanaged<CFError>? addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue() /* You can use the address book here */ self.newPersonWithFirstName("Domenico", lastName: "Solazzo", inAddressBook: addressBook!) } } func newPersonWithFirstName(firstName: String, lastName: String, inAddressBook: ABAddressBookRef) -> ABRecordRef?{ let person: ABRecordRef = ABPersonCreate().takeRetainedValue() let couldSetFirstName = ABRecordSetValue(person, kABPersonFirstNameProperty, firstName as CFTypeRef, nil) let couldSetLastName = ABRecordSetValue(person, kABPersonLastNameProperty, lastName as CFTypeRef, nil) var error: Unmanaged<CFErrorRef>? = nil let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error) if couldAddPerson{ println("Successfully added the person.") } else { println("Failed to add the person.") return nil } if ABAddressBookHasUnsavedChanges(inAddressBook){ var error: Unmanaged<CFErrorRef>? = nil let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error) if couldSaveAddressBook{ println("Successfully saved the address book.") } else { println("Failed to save the address book.") } } if couldSetFirstName && couldSetLastName{ println("Successfully set the first name " + "and the last name of the person") } else { println("Failed to set the first name and/or " + "the last name of the person") } return person } }
mit
bf2e3e15f3030c534ff3f7172d948064
31.456
128
0.518856
6.358934
false
false
false
false
gecko655/Swifter
Sources/HMAC.swift
4
1212
// // HMAC.swift // OAuthSwift // // Created by Dongri Jin on 1/28/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation public struct HMAC { internal static func sha1(key: Data, message: Data) -> Data? { var key = key.rawBytes let message = message.rawBytes // key if key.count > 64 { key = SHA1(message: Data(bytes: key)).calculate().rawBytes } if (key.count < 64) { key = key + [UInt8](repeating: 0, count: 64 - key.count) } // var opad = [UInt8](repeating: 0x5c, count: 64) for (idx, _) in key.enumerated() { opad[idx] = key[idx] ^ opad[idx] } var ipad = [UInt8](repeating: 0x36, count: 64) for (idx, _) in key.enumerated() { ipad[idx] = key[idx] ^ ipad[idx] } let ipadAndMessageHash = SHA1(message: Data(bytes: (ipad + message))).calculate().rawBytes let finalHash = SHA1(message: Data(bytes: opad + ipadAndMessageHash)).calculate().rawBytes let mac = finalHash return Data(bytes: UnsafePointer<UInt8>(mac), count: mac.count) } }
mit
645b2a86701664bf9a3a083aa38071ea
25.933333
98
0.542904
3.61791
false
false
false
false
leavez/ComponentSwift
Example/CKWrapperDemo/components/DemoComponent.swift
1
1776
// // DemoComponent.swift // ComponentSwiftDemo // // Created by Gao on 18/06/2017. // Copyright © 2017 leave. All rights reserved. // import Foundation import Foundation import ComponentSwift import WrapExisted class DemoComponent: CompositeComponent, ComponentInitialStateProtocol { typealias StateType = Bool init?(model:Int) { let scope = StateScope(with: type(of: self)) super.init(scope: scope) { (state) -> Component? in InsetComponent(insets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20), component: VerticalStackComponent( style: StackLayoutStyle() .spacing(10), children: TextComponent( TextAttributes("Chapter \(model)", font: .boldSystemFont(ofSize: 24)) ), TextComponent( TextAttributes().build({ $0.attributedString = getText() $0.maximumNumberOfLines = state ? 0 : 3 $0.truncationAttributedString = NSAttributedString(string:"...") }), viewAttributes: ViewAttributeMap( .tapGesture(#selector(didTap)) ) ).stackLayoutChild .flexGrow(true) .flexShrink(true) ) ) } } static func initialState() -> Bool { return false } @objc func didTap(sender: Any) { self.updateState({ !$0 }, asynchronously: true) } }
mit
4bc6d1d627933ead50882e44fc3d9e07
25.102941
93
0.476056
5.617089
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/PRODUCTNAME/Screens/Onboarding/OnboardingPageViewController.swift
1
6444
// // OnboardingPageViewController.swift // PRODUCTNAME // // Created by LEADDEVELOPER on TODAYSDATE. // Copyright © THISYEAR ORGANIZATION. All rights reserved. // import Anchorage import Swiftilities // MARK: OnboardingPageViewController class OnboardingPageViewController: UIViewController { fileprivate let viewControllers: [UIViewController] fileprivate let skipButton: UIButton = { let button = UIButton() button.bonMotStyle = .body button.bonMotStyle?.color = Color.darkGray button.setTitleColor(Color.darkGray.highlighted, for: .highlighted) button.styledText = L10n.Onboarding.Buttons.skip return button }() fileprivate let pageController = UIPageViewController( transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) fileprivate let firstHairline = HairlineView(axis: .horizontal) fileprivate let joinButton: UIButton = { let button = UIButton() button.bonMotStyle = .body button.bonMotStyle?.color = Color.green button.setTitleColor(Color.green.highlighted, for: .highlighted) button.styledText = L10n.Onboarding.Buttons.join return button }() fileprivate let secondHairline = HairlineView(axis: .horizontal) fileprivate let signInButton: UIButton = { let button = UIButton() button.bonMotStyle = .body button.bonMotStyle?.color = Color.darkGray button.styledText = L10n.Onboarding.Buttons.signIn button.setTitleColor(Color.darkGray.highlighted, for: .highlighted) return button }() weak var delegate: Delegate? init(viewModels: [OnboardingSamplePageViewModel]) { self.viewControllers = viewModels.map { OnboardingSamplePageViewController(viewModel: $0) } super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureView() configureLayout() } } // MARK: Actionable extension OnboardingPageViewController: Actionable { enum Action { case skipTapped case joinTapped case signInTapped } } // MARK: Private private extension OnboardingPageViewController { func configureView() { view.backgroundColor = .white view.addSubview(skipButton) skipButton.addTarget(self, action: #selector(skipTapped), for: .touchUpInside) pageController.setViewControllers( [viewControllers[0]], direction: .forward, animated: false, completion: nil) pageController.dataSource = self addChild(pageController) view.addSubview(pageController.view) pageController.didMove(toParent: self) let pageControlAppearance = UIPageControl.appearance( whenContainedInInstancesOf: [OnboardingPageViewController.self]) pageControlAppearance.pageIndicatorTintColor = Color.lightGray pageControlAppearance.currentPageIndicatorTintColor = Color.darkGray view.addSubview(firstHairline) joinButton.addTarget(self, action: #selector(joinTapped), for: .touchUpInside) view.addSubview(joinButton) view.addSubview(secondHairline) signInButton.addTarget(self, action: #selector(signInTapped), for: .touchUpInside) view.addSubview(signInButton) } struct Layout { static let skipButtonTrailingInset = CGFloat(20) static let skipButtonTopInset = CGFloat(22) static let pageViewTopSpace = CGFloat(20) static let joinVerticalSpace = CGFloat(8) static let signInVerticalSpace = CGFloat(18) } func configureLayout() { skipButton.topAnchor == view.safeAreaLayoutGuide.topAnchor + Layout.skipButtonTopInset skipButton.trailingAnchor == view.safeAreaLayoutGuide.trailingAnchor - Layout.skipButtonTrailingInset pageController.view.topAnchor == skipButton.bottomAnchor + Layout.pageViewTopSpace pageController.view.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors firstHairline.topAnchor == pageController.view.bottomAnchor firstHairline.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors joinButton.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors joinButton.topAnchor == firstHairline.bottomAnchor + Layout.joinVerticalSpace joinButton.bottomAnchor == secondHairline.topAnchor - Layout.joinVerticalSpace secondHairline.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors signInButton.horizontalAnchors == view.safeAreaLayoutGuide.horizontalAnchors signInButton.topAnchor == secondHairline.bottomAnchor + Layout.signInVerticalSpace signInButton.bottomAnchor == view.safeAreaLayoutGuide.bottomAnchor - Layout.signInVerticalSpace } } // MARK: Actions private extension OnboardingPageViewController { @objc func skipTapped() { notify(.skipTapped) } @objc func joinTapped() { notify(.joinTapped) } @objc func signInTapped() { notify(.signInTapped) } } // MARK: UIPageViewControllerDataSource extension OnboardingPageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.firstIndex(of: viewController), index > 0 else { return nil } return viewControllers[index - 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.firstIndex(of: viewController), index < viewControllers.count - 1 else { return nil } return viewControllers[index + 1] } func presentationCount(for pageViewController: UIPageViewController) -> Int { return viewControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let current = pageViewController.viewControllers?.first else { return 0 } return viewControllers.firstIndex(of: current) ?? 0 } }
mit
3b80c951cbdfac2689d242bb175b905e
34.401099
149
0.709763
5.535223
false
false
false
false
li1024316925/Swift-TimeMovie
Swift-TimeMovie/Swift-TimeMovie/HomeViewModel.swift
1
907
// // HomeViewModel.swift // Swift-TimeMovie // // Created by DahaiZhang on 16/10/18. // Copyright © 2016年 LLQ. All rights reserved. // import UIKit class HomeViewModel: NSObject { //首页电影列表数据 func loadMovieData(success: @escaping ([HomeModel])->()) -> Void { //加载Json文件 let dataDic = CoreDataFromJson.jsonObjectFromFileName(fileName: "home_header") guard let dictionary = dataDic else { return } let array = dictionary["movies"] as? NSArray guard let dataArray = array else { return } var dataList:[HomeModel] = [] for dic in dataArray { let model:HomeModel = HomeModel(dic: dic as! [String : Any]) dataList.append(model) } success(dataList) } }
apache-2.0
a99baf354706801a9ec67954783a9992
21
86
0.535227
4.536082
false
false
false
false
danielallsopp/Charts
Source/Charts/Utils/ChartPlatform.swift
1
15830
import Foundation /** This file provides a thin abstraction layer atop of UIKit (iOS, tvOS) and Cocoa (OS X). The two APIs are very much alike, and for the chart library's usage of the APIs it is often sufficient to typealias one to the other. The NSUI* types are aliased to either their UI* implementation (on iOS) or their NS* implementation (on OS X). */ #if os(iOS) || os(tvOS) import UIKit public typealias NSUIFont = UIFont public typealias NSUIColor = UIColor public typealias NSUIEvent = UIEvent public typealias NSUITouch = UITouch public typealias NSUIImage = UIImage public typealias NSUIScrollView = UIScrollView public typealias NSUIGestureRecognizer = UIGestureRecognizer public typealias NSUIGestureRecognizerState = UIGestureRecognizerState public typealias NSUIGestureRecognizerDelegate = UIGestureRecognizerDelegate public typealias NSUITapGestureRecognizer = UITapGestureRecognizer public typealias NSUIPanGestureRecognizer = UIPanGestureRecognizer #if !os(tvOS) public typealias NSUIPinchGestureRecognizer = UIPinchGestureRecognizer public typealias NSUIRotationGestureRecognizer = UIRotationGestureRecognizer #endif public typealias NSUIScreen = UIScreen public typealias NSUIDisplayLink = CADisplayLink extension NSUITapGestureRecognizer { final func nsuiNumberOfTouches() -> Int { return numberOfTouches() } final var nsuiNumberOfTapsRequired: Int { get { return self.numberOfTapsRequired } set { self.numberOfTapsRequired = newValue } } } extension NSUIPanGestureRecognizer { final func nsuiNumberOfTouches() -> Int { return numberOfTouches() } final func nsuiLocationOfTouch(touch: Int, inView: UIView?) -> CGPoint { return super.locationOfTouch(touch, inView: inView) } } #if !os(tvOS) extension NSUIRotationGestureRecognizer { final var nsuiRotation: CGFloat { get { return rotation } set { rotation = newValue } } } #endif #if !os(tvOS) extension NSUIPinchGestureRecognizer { final var nsuiScale: CGFloat { get { return scale } set { scale = newValue } } final func nsuiLocationOfTouch(touch: Int, inView: UIView?) -> CGPoint { return super.locationOfTouch(touch, inView: inView) } } #endif public class NSUIView: UIView { public final override func touchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { self.nsuiTouchesBegan(touches, withEvent: event) } public final override func touchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { self.nsuiTouchesMoved(touches, withEvent: event) } public final override func touchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { self.nsuiTouchesEnded(touches, withEvent: event) } public final override func touchesCancelled(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { self.nsuiTouchesCancelled(touches, withEvent: event) } public func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesBegan(touches, withEvent: event!) } public func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesMoved(touches, withEvent: event!) } public func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesEnded(touches, withEvent: event!) } public func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.touchesCancelled(touches!, withEvent: event!) } var nsuiLayer: CALayer? { return self.layer } } extension UIView { final var nsuiGestureRecognizers: [NSUIGestureRecognizer]? { return self.gestureRecognizers } } extension UIScreen { final var nsuiScale: CGFloat { return self.scale } } func NSUIGraphicsGetCurrentContext() -> CGContextRef? { return UIGraphicsGetCurrentContext() } func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage! { return UIGraphicsGetImageFromCurrentImageContext() } func NSUIGraphicsPushContext(context: CGContextRef) { UIGraphicsPushContext(context) } func NSUIGraphicsPopContext() { UIGraphicsPopContext() } func NSUIGraphicsEndImageContext() { UIGraphicsEndImageContext() } func NSUIImagePNGRepresentation(image: NSUIImage) -> NSData? { return UIImagePNGRepresentation(image) } func NSUIImageJPEGRepresentation(image: NSUIImage, _ quality: CGFloat = 0.8) -> NSData? { return UIImageJPEGRepresentation(image, quality) } func NSUIMainScreen() -> NSUIScreen? { return NSUIScreen.mainScreen() } func NSUIGraphicsBeginImageContextWithOptions(size: CGSize, _ opaque: Bool, _ scale: CGFloat) { UIGraphicsBeginImageContextWithOptions(size, opaque, scale) } #endif #if os(OSX) import Cocoa import Quartz public typealias NSUIFont = NSFont public typealias NSUIColor = NSColor public typealias NSUIEvent = NSEvent public typealias NSUITouch = NSTouch public typealias NSUIImage = NSImage public typealias NSUIScrollView = NSScrollView public typealias NSUIGestureRecognizer = NSGestureRecognizer public typealias NSUIGestureRecognizerState = NSGestureRecognizerState public typealias NSUIGestureRecognizerDelegate = NSGestureRecognizerDelegate public typealias NSUITapGestureRecognizer = NSClickGestureRecognizer public typealias NSUIPanGestureRecognizer = NSPanGestureRecognizer public typealias NSUIPinchGestureRecognizer = NSMagnificationGestureRecognizer public typealias NSUIRotationGestureRecognizer = NSRotationGestureRecognizer public typealias NSUIScreen = NSScreen /** On OS X there is no CADisplayLink. Use a 60 fps timer to render the animations. */ public class NSUIDisplayLink { private var timer: NSTimer? private var displayLink: CVDisplayLink? private var _timestamp: CFTimeInterval = 0.0 private weak var _target: AnyObject? private var _selector: Selector public var timestamp: CFTimeInterval { return _timestamp } init(target: AnyObject, selector: Selector) { _target = target _selector = selector if CVDisplayLinkCreateWithActiveCGDisplays(&displayLink) == kCVReturnSuccess { CVDisplayLinkSetOutputCallback(displayLink!, { (displayLink, inNow, inOutputTime, flagsIn, flagsOut, userData) -> CVReturn in let _self = unsafeBitCast(userData, NSUIDisplayLink.self) _self._timestamp = CFAbsoluteTimeGetCurrent() _self._target?.performSelectorOnMainThread(_self._selector, withObject: _self, waitUntilDone: false) return kCVReturnSuccess }, UnsafeMutablePointer(unsafeAddressOf(self))) } else { timer = NSTimer(timeInterval: 1.0 / 60.0, target: target, selector: selector, userInfo: nil, repeats: true) } } deinit { stop() } public func addToRunLoop(runloop: NSRunLoop, forMode: String) { if displayLink != nil { CVDisplayLinkStart(displayLink!) } else if timer != nil { runloop.addTimer(timer!, forMode: forMode) } } public func removeFromRunLoop(runloop: NSRunLoop, forMode: String) { stop() } private func stop() { if displayLink != nil { CVDisplayLinkStop(displayLink!) } if timer != nil { timer?.invalidate() } } } /** The 'tap' gesture is mapped to clicks. */ extension NSUITapGestureRecognizer { final func nsuiNumberOfTouches() -> Int { return 1 } final var nsuiNumberOfTapsRequired: Int { get { return self.numberOfClicksRequired } set { self.numberOfClicksRequired = newValue } } } extension NSUIPanGestureRecognizer { final func nsuiNumberOfTouches() -> Int { return 1 } /// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures. final func nsuiLocationOfTouch(touch: Int, inView: NSView?) -> NSPoint { return super.locationInView(inView) } } extension NSUIRotationGestureRecognizer { /// FIXME: Currently there are no velocities in OSX gestures, and not way to create custom touch gestures. final var velocity: CGFloat { return 0.1 } final var nsuiRotation: CGFloat { get { return -rotation } set { rotation = -newValue } } } extension NSUIPinchGestureRecognizer { final var nsuiScale: CGFloat { get { return magnification + 1.0 } set { magnification = newValue - 1.0 } } /// FIXME: Currently there are no more than 1 touch in OSX gestures, and not way to create custom touch gestures. final func nsuiLocationOfTouch(touch: Int, inView: NSView?) -> NSPoint { return super.locationInView(inView) } } extension NSView { final var nsuiGestureRecognizers: [NSGestureRecognizer]? { return self.gestureRecognizers } } public class NSUIView: NSView { public final override var flipped: Bool { return true } func setNeedsDisplay() { self.setNeedsDisplayInRect(self.bounds) } public final override func touchesBeganWithEvent(event: NSEvent) { self.nsuiTouchesBegan(event.touchesMatchingPhase(.Any, inView: self), withEvent: event) } public final override func touchesEndedWithEvent(event: NSEvent) { self.nsuiTouchesEnded(event.touchesMatchingPhase(.Any, inView: self), withEvent: event) } public final override func touchesMovedWithEvent(event: NSEvent) { self.nsuiTouchesMoved(event.touchesMatchingPhase(.Any, inView: self), withEvent: event) } public override func touchesCancelledWithEvent(event: NSEvent) { self.nsuiTouchesCancelled(event.touchesMatchingPhase(.Any, inView: self), withEvent: event) } public func nsuiTouchesBegan(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesBeganWithEvent(event!) } public func nsuiTouchesMoved(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesMovedWithEvent(event!) } public func nsuiTouchesEnded(touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { super.touchesEndedWithEvent(event!) } public func nsuiTouchesCancelled(touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { super.touchesCancelledWithEvent(event!) } var backgroundColor: NSUIColor? { get { return self.layer?.backgroundColor == nil ? nil : NSColor(CGColor: self.layer!.backgroundColor!) } set { self.layer?.backgroundColor = newValue == nil ? nil : newValue!.CGColor } } final var nsuiLayer: CALayer? { return self.layer } } extension NSFont { var lineHeight: CGFloat { // Not sure if this is right, but it looks okay return self.boundingRectForFont.size.height } } extension NSScreen { final var nsuiScale: CGFloat { return self.backingScaleFactor } } extension NSImage { var CGImage: CGImageRef? { return self.CGImageForProposedRect(nil, context: nil, hints: nil) } } extension NSTouch { /** Touch locations on OS X are relative to the trackpad, whereas on iOS they are actually *on* the view. */ func locationInView(view: NSView) -> NSPoint { let n = self.normalizedPosition let b = view.bounds return NSPoint(x: b.origin.x + b.size.width * n.x, y: b.origin.y + b.size.height * n.y) } } extension NSScrollView { var scrollEnabled: Bool { get { return true } set { // FIXME: We can't disable scrolling it on OSX } } } func NSUIGraphicsGetCurrentContext() -> CGContextRef? { return NSGraphicsContext.currentContext()?.CGContext } func NSUIGraphicsPushContext(context: CGContextRef) { let address = unsafeAddressOf(context) let ptr: UnsafeMutablePointer<CGContext> = UnsafeMutablePointer(UnsafePointer<CGContext>(address)) let cx = NSGraphicsContext(graphicsPort: ptr, flipped: true) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext(cx) } func NSUIGraphicsPopContext() { NSGraphicsContext.restoreGraphicsState() } func NSUIImagePNGRepresentation(image: NSUIImage) -> NSData? { image.lockFocus() let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height)) image.unlockFocus() return rep?.representationUsingType(.JPEG, properties: [:]) } func NSUIImageJPEGRepresentation(image: NSUIImage, _ quality: CGFloat = 0.9) -> NSData? { image.lockFocus() let rep = NSBitmapImageRep(focusedViewRect: NSMakeRect(0, 0, image.size.width, image.size.height)) image.unlockFocus() return rep?.representationUsingType(.JPEG, properties: [NSImageCompressionFactor: quality]) } private var imageContextStack: [CGFloat] = [] func NSUIGraphicsBeginImageContextWithOptions(size: CGSize, _ opaque: Bool, _ scale: CGFloat) { var scale = scale if scale == 0.0 { scale = NSScreen.mainScreen()?.backingScaleFactor ?? 1.0 } let width = Int(size.width * scale) let height = Int(size.height * scale) if width > 0 && height > 0 { imageContextStack.append(scale) let colorSpace = CGColorSpaceCreateDeviceRGB() let ctx = CGBitmapContextCreate(nil, width, height, 8, 4*width, colorSpace, (opaque ? CGImageAlphaInfo.NoneSkipFirst.rawValue : CGImageAlphaInfo.PremultipliedFirst.rawValue)) CGContextConcatCTM(ctx!, CGAffineTransformMake(1, 0, 0, -1, 0, CGFloat(height))) CGContextScaleCTM(ctx!, scale, scale) NSUIGraphicsPushContext(ctx!) } } func NSUIGraphicsGetImageFromCurrentImageContext() -> NSUIImage? { if !imageContextStack.isEmpty { let ctx = NSUIGraphicsGetCurrentContext() let scale = imageContextStack.last! if let theCGImage = CGBitmapContextCreateImage(ctx!) { let size = CGSizeMake(CGFloat(CGBitmapContextGetWidth(ctx!)) / scale, CGFloat(CGBitmapContextGetHeight(ctx!)) / scale) let image = NSImage(CGImage: theCGImage, size: size) return image } } return nil } func NSUIGraphicsEndImageContext() { if imageContextStack.last != nil { imageContextStack.removeLast() NSUIGraphicsPopContext() } } func NSUIMainScreen() -> NSUIScreen? { return NSUIScreen.mainScreen() } #endif
apache-2.0
cf338809bd285408afb235ba06646852
25.876061
178
0.646936
4.783923
false
false
false
false
sol/aeson
tests/JSONTestSuite/parsers/test_Freddy_2_1_0/test_Freddy/JSONEncodingDetector.swift
20
3810
// // JSONEncodingDetector.swift // Freddy // // Created by Robert Edwards on 1/27/16. // Copyright © 2016 Big Nerd Ranch. All rights reserved. // /// Struct for attempting to detect the Unicode encoding used with the data supplied to the JSONParser public struct JSONEncodingDetector { //// The Unicode encodings looked for during detection public enum Encoding { //// UTF-8 case UTF8 //// UTF-16 Little Endian case UTF16LE //// UTF-16 Big Endian case UTF16BE //// UTF-32 Little Endian case UTF32LE //// UTF-32 Big Endian case UTF32BE } //// The Unicode encodings supported by JSONParser.swift public static let supportedEncodings: [Encoding] = [.UTF8] typealias ByteStreamPrefixInformation = (encoding: Encoding, byteOrderMarkLength: Int) //// Attempts to detect the Unicode encoding used for a given set of data. //// //// This function initially looks for a Byte Order Mark in the following form: //// //// Bytes | Encoding Form //// --------------|---------------- //// 00 00 FE FF | UTF-32, big-endian //// FF FE 00 00 | UTF-32, little-endian //// FE FF | UTF-16, big-endian //// FF FE | UTF-16, little-endian //// EF BB BF | UTF-8 //// //// If a BOM is not found then we detect using the following approach described in //// the JSON RFC http://www.ietf.org/rfc/rfc4627.txt: //// //// Since the first two characters of a JSON text will always be ASCII //// characters [RFC0020], it is possible to determine whether an octet //// stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking //// at the pattern of nulls in the first four octets. //// //// 00 00 00 xx UTF-32BE //// 00 xx 00 xx UTF-16BE //// xx 00 00 00 UTF-32LE //// xx 00 xx 00 UTF-16LE //// xx xx xx xx UTF-8 //// //// - parameter header: The front Slice of data being read and evaluated. //// - returns: A tuple containing the detected Unicode encoding and the lenght of the byte order mark. static func detectEncoding(header: Slice<UnsafeBufferPointer<UInt8>>) -> ByteStreamPrefixInformation { guard let prefix = prefixFromHeader(header) else { return (.UTF8, 0) } if let prefixInfo = JSONEncodingDetector.encodingFromBOM(prefix) { return prefixInfo } else { switch prefix { case(0, 0, 0?, _): return (.UTF32BE, 0) case(_, 0, 0?, 0?): return (.UTF32LE, 0) case (0, _, 0?, _), (0, _, _, _): return (.UTF16BE, 0) case (_, 0, _, 0?), (_, 0, _, _): return (.UTF16LE, 0) default: return (.UTF8, 0) } } } private typealias EncodingBytePrefix = (UInt8, UInt8, UInt8?, UInt8?) private static func prefixFromHeader(header: Slice<UnsafeBufferPointer<UInt8>>) -> EncodingBytePrefix? { if header.count >= 4 { return(header[0], header[1], header[2], header[3]) } else if header.count >= 2 { return (header[0], header[1], nil, nil) } return nil } private static func encodingFromBOM(prefix: EncodingBytePrefix) -> ByteStreamPrefixInformation? { switch prefix { case(0xFE, 0xFF, _, _): return (.UTF16BE, 2) case(0x00, 0x00, 0xFE?, 0xFF?): return (.UTF32BE, 4) case(0xEF, 0xBB, 0xBF?, _): return (.UTF8, 3) case(0xFF, 0xFE, 0?, 0?): return (.UTF32LE, 4) case(0xFF, 0xFE, _, _): return (.UTF16LE, 2) default: return nil } } }
bsd-3-clause
909a1c8bbf2fa8c41151dd124366f8f3
33.627273
108
0.553689
4.069444
false
false
false
false
codepath-volunteer-app/VolunteerMe
VolunteerMe/Pods/ParseLiveQuery/Sources/ParseLiveQuery/Internal/Operation.swift
1
4263
/** * Copyright (c) 2016-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import Parse enum ClientOperation { case connect(applicationId: String, sessionToken: String) case subscribe(requestId: Client.RequestId, query: PFQuery<PFObject>, sessionToken: String?) case update(requestId: Client.RequestId, query: PFQuery<PFObject>) case unsubscribe(requestId: Client.RequestId) var JSONObjectRepresentation: [String : Any] { switch self { case .connect(let applicationId, let sessionToken): return [ "op": "connect", "applicationId": applicationId, "sessionToken": sessionToken ] case .subscribe(let requestId, let query, let sessionToken): var result: [String: Any] = [ "op": "subscribe", "requestId": requestId.value, "query": Dictionary<String, AnyObject>(query: query) ] if let sessionToken = sessionToken { result["sessionToken"] = sessionToken } return result case .update(let requestId, let query): return [ "op": "update", "requestId": requestId.value, "query": Dictionary<String, AnyObject>(query: query) ] case .unsubscribe(let requestId): return [ "op": "unsubscribe", "requestId": requestId.value ] } } } enum ServerResponse { case redirect(url: String) case connected() case subscribed(requestId: Client.RequestId) case unsubscribed(requestId: Client.RequestId) case enter(requestId: Client.RequestId, object: [String : AnyObject]) case leave(requestId: Client.RequestId, object: [String : AnyObject]) case update(requestId: Client.RequestId, object: [String : AnyObject]) case create(requestId: Client.RequestId, object: [String : AnyObject]) case delete(requestId: Client.RequestId, object: [String : AnyObject]) case error(requestId: Client.RequestId?, code: Int, error: String, reconnect: Bool) init(json: [String : AnyObject]) throws { func jsonValue<T>(_ json: [String:AnyObject], _ key: String) throws -> T { guard let value = json[key] as? T else { throw LiveQueryErrors.InvalidJSONError(json: json, expectedKey: key) } return value } func jsonRequestId(_ json: [String:AnyObject]) throws -> Client.RequestId { let requestId: Int = try jsonValue(json, "requestId") return Client.RequestId(value: requestId) } func subscriptionEvent( _ json: [String:AnyObject], _ eventType: (Client.RequestId, [String : AnyObject]) -> ServerResponse ) throws -> ServerResponse { return eventType(try jsonRequestId(json), try jsonValue(json, "object")) } let rawOperation: String = try jsonValue(json, "op") switch rawOperation { case "connected": self = .connected() case "redirect": self = .redirect(url: try jsonValue(json, "url")) case "subscribed": self = .subscribed(requestId: try jsonRequestId(json)) case "unsubscribed": self = .unsubscribed(requestId: try jsonRequestId(json)) case "enter": self = try subscriptionEvent(json, ServerResponse.enter) case "leave": self = try subscriptionEvent(json, ServerResponse.leave) case "update": self = try subscriptionEvent(json, ServerResponse.update) case "create": self = try subscriptionEvent(json, ServerResponse.create) case "delete": self = try subscriptionEvent(json, ServerResponse.delete) case "error": self = .error( requestId: try? jsonRequestId(json), code: try jsonValue(json, "code"), error: try jsonValue(json, "error"), reconnect: try jsonValue(json, "reconnect") ) default: throw LiveQueryErrors.InvalidJSONError(json: json, expectedKey: "op") } } }
mit
4688f61ca96b8102cc3c819970b91148
38.841121
146
0.632418
4.65393
false
false
false
false
csnu17/My-Swift-learning
GooglyPuff/GooglyPuff/AlbumsTableViewController.swift
1
6699
/* * Copyright (c) 2016 Razeware 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 import Photos private let reuseIdentifier = "AlbumsCell" class AlbumsTableViewController: UITableViewController { var selectedAssets: SelectedAssets? weak var assetPickerDelegate: AssetPickerDelegate? private let sectionNames = ["", "Albums"] private var userLibrary: PHFetchResult<PHAssetCollection>! private var userAlbums: PHFetchResult<PHCollection>! private var doneButton: UIBarButtonItem! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() if selectedAssets == nil { selectedAssets = SelectedAssets() } PHPhotoLibrary.requestAuthorization { status in DispatchQueue.main.async { switch status { case .authorized: self.fetchCollections() self.tableView.reloadData() default: self.showNoAccessAlertAndCancel() } } } doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(donePressed(_:))) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateDoneButton() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destination = segue.destination as! AssetsCollectionViewController // Set up AssetCollectionViewController destination.selectedAssets = selectedAssets let cell = sender as! UITableViewCell destination.title = cell.textLabel!.text destination.assetPickerDelegate = self let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let indexPath = tableView.indexPath(for: cell)! switch (indexPath.section) { case 0: // Camera Roll let library = userLibrary[indexPath.row] destination.assetsFetchResults = PHAsset.fetchAssets(in: library, options: options) as? PHFetchResult<AnyObject> case 1: // Albums let album = userAlbums[indexPath.row] as! PHAssetCollection destination.assetsFetchResults = PHAsset.fetchAssets(in: album, options: options) as? PHFetchResult<AnyObject> default: break } } @IBAction func cancelPressed(_ sender: Any) { assetPickerDelegate?.assetPickerDidCancel() } @IBAction func donePressed(_ sender: Any) { // Should only be invoked when there are selected assets if let assets = self.selectedAssets?.assets { assetPickerDelegate?.assetPickerDidFinishPickingAssets(assets) // Clear out selections self.selectedAssets?.assets.removeAll() } } } // MARK: - Private Methods extension AlbumsTableViewController { func fetchCollections() { userAlbums = PHCollectionList.fetchTopLevelUserCollections(with: nil) userLibrary = PHAssetCollection.fetchAssetCollections( with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil) } func showNoAccessAlertAndCancel() { let alert = UIAlertController(title: "No Photo Permissions", message: "Please grant photo permissions in Settings", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in UIApplication.shared.open( URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil) })) self.present(alert, animated: true) } private func updateDoneButton() { guard selectedAssets != nil else { return } // Add a done button when there are selected assets if (selectedAssets?.assets.count)! > 0 { self.navigationItem.rightBarButtonItem = doneButton } else { self.navigationItem.rightBarButtonItem = nil } } } // MARK: - Table view data source extension AlbumsTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sectionNames.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch (section) { case 0: return (userLibrary?.count ?? 0) case 1: return userAlbums?.count ?? 0 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) cell.textLabel!.text = "" switch(indexPath.section) { case 0: let library = userLibrary[indexPath.row] var title = library.localizedTitle! if library.estimatedAssetCount != NSNotFound { title += " (\(library.estimatedAssetCount))" } cell.textLabel!.text = title case 1: let album = userAlbums[indexPath.row] as! PHAssetCollection var title = album.localizedTitle! if album.estimatedAssetCount != NSNotFound { title += " (\(album.estimatedAssetCount))" } cell.textLabel!.text = title default: break } cell.accessoryType = .disclosureIndicator return cell } } // MARK: - AssetPickerDelegate extension AlbumsTableViewController: AssetPickerDelegate { func assetPickerDidCancel() { assetPickerDelegate?.assetPickerDidCancel() } func assetPickerDidFinishPickingAssets(_ selectedAssets: [PHAsset]) { assetPickerDelegate?.assetPickerDidFinishPickingAssets(selectedAssets) // Clear out selections self.selectedAssets?.assets.removeAll() } }
mit
74ae58e7d14ed88ea0faaa324b34f2b7
31.519417
143
0.69891
4.969585
false
false
false
false
adilbenmoussa/ABReviewReminder
Example/MyAwesomeApp/Pods/ABReviewReminder/ABReviewReminder/ABReviewReminder.swift
1
28017
/* ABReviewReminder.swift ABReviewReminder is a utility that reminds the iPhone and iPad app users to review your app. 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. * * Created by Adil Ben Moussa on 11/28/2015. * https://github.com/adilbenmoussa * Copyright 2012 Arash Payan. All rights reserved. */ import SystemConfiguration //////////////////////////////////////// // ABReviewReminder Delegate // //////////////////////////////////////// @objc public protocol ABReviewReminderDelegate { // called when the use clicks on the rate app button optional func userDidOptToRate() // called when the use clicks on the decline rate app button optional func userDidDeclineToRate() // called when the use clicks on the remind me later button optional func userDidOptToRemindLater() // called when network status changes optional func reachabilityChangedWithNetworkStatus(newNetworkStatus: String) } // List of the possible options to use public enum ABReviewReminderOptions : Int { /** * Debug (Bool | Optional) If set the alert will be shown every time the app starts * WARNING: don't forget to set debug flag back to false when deploying to production * Default is false. */ case Debug /** * Delegate (ABReviewReminderDelegate | Optional) If set the ABReviewReminder events will be delegated * Default is nil. */ case Delegate /** * DaysUntilPrompt (Int | Optional) The amount of days to wait to show the alert for a specific version of the app * Default is 30. */ case DaysUntilPrompt /** * UsesUntilPrompt (Int | Optional) If set the alert will be shown every time the app starts * An example of a 'use' would be if the user launched the app. Bringing the app * into the foreground (on devices that support it) would also be considered * a 'use'. You tell ABReviewReminder about these events using the two methods: * ABReviewReminder.appLaunched() and when app triggers the UIApplicationWillEnterForegroundNotification event * * * Users need to 'use' the same version of the app this many times before * before they will be prompted to rate it. * Default is 20. */ case UsesUntilPrompt /* * TimeBeforeReminding (Int | Optional) Once the rating alert is presented to the user, they might select *'Remind me later'. This value specifies how long (in days) ABReviewReminder * will wait before reminding them. * Default is 1. */ case TimeBeforeReminding /** * AppVersionType (String | Optional) The app version type ABReviewReminder will track. Default the major version "CFBundleVersion" * Options: ["CFBundleVersion", "CFBundleShortVersionString"] * Default is "CFBundleVersion". */ case AppVersionType /** * UseMainBundle (Bool | Optional) If set to true, the main bundle will always be used to load localized strings. * Set this to true if you have provided your own custom localizations in ABReviewReminderLocalizable.strings * in your main bundle. * Default is false. */ case UseMainBundle } // List of the possible Alert string overrides public enum ABAlertStrings : Int { // This is the title of the message alert that users will see. case AlertTitle // This is the message your users will see once they've passed the day+launches threshold. case AlertMessage // The text of the button that declines reviewing the app. case AlertDeclineTitle // Text of button that will send user to app review page. case AlertRateTitle // Text for button to remind the user to review later. case AlertRateLaterTitle } // Network status public enum ABNetworkStatus : String { // case when the network is offline case Offline = "Offline" // case when the network is online case Online = "Online" // case when the network is unknow case Unknown = "Unknown" } //////////////////////////////////////// // ABReviewReminder // //////////////////////////////////////// public class ABReviewReminder { // Singlton instance private class var instance: ABReviewReminder { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: ABReviewReminder? = nil } dispatch_once(&Static.onceToken) { Static.instance = ABReviewReminder() // register the app events NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWillResignActive", name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWillEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil) } return Static.instance! } //////////////////// // MARK: Constants //////////////////// let kSavedVersion = "abrrSavedVersion" let kUseCount = "abrrUseCount" let kFirstUseDate = "abrrFirstUseDate" let kRatedCurrentVersion = "abrrRatedCurrentVersion" let kDeclinedToRate = "abrrDeclinedToRate" let kReminderRequestDate = "abrrReminderRequestDate" //////////////////// // MARK: Variables //////////////////// // Id of the app to review (Id was generate by Apple's Itunesconnect when creating a new app) private var _appId: String! // Default options private var _options:[ABReviewReminderOptions : AnyObject] = [ .Debug: false, .DaysUntilPrompt: 30, .UsesUntilPrompt: 20, .TimeBeforeReminding: 1, .AppVersionType: "CFBundleVersion", .UseMainBundle: false ] // Default strings private var _strings: [ABAlertStrings : String] = [:] // keep a reference to the alert controller private var _alertController: UIAlertController? // Keep a reference of the custom actions private var _actions: [UIAlertAction] = [] // Keep a reference to the network status private var networkStatus: ABNetworkStatus = ABNetworkStatus.Unknown //////////////////// // MARK: Public methods //////////////////// // Starts the signlton ABReviewReminder session // @param appId (Mandatory) id of the app to review // @param options (Optional) options to extends the default options // @param strings (Optional) strings to override the default localization provided by ABReviewReminder public class func startSession(appId: String, withOptions options: [ABReviewReminderOptions : AnyObject]? = nil, strings: [ABAlertStrings : String]? = nil ) { instance._appId = appId instance.monitorNetworkChanges() instance.extendOptions(options) instance.initStrings(strings) instance.initActions() instance.debug("ABReviewReminder started session with appId: \(appId)") } // Tells ABReviewReminder that the app has launched. // You should call this method at the end of your application delegate's // application:didFinishLaunchingWithOptions: method. public class func appLaunched() { instance.appLaunched() } // Add a Alert custom action at the passed index // @param action The custom action to add // @param index The position where the action will be added, default will be 0 // Note: The Reject action item will be always put at the end of the actions list public class func addAlertAction(action: UIAlertAction, atIndex index: Int = 0){ instance.addAlertAction(action, atIndex: index) } //////////////////// // MARK: Private methods //////////////////// @objc private class func appWillResignActive() { instance.debug("ABReviewReminder appWillResignActive") instance.hideAlert() } @objc private class func appWillEnterForeground() { instance.debug("ABReviewReminder appWillEnterForeground") if instance._appId == nil { //somehow the session has not started yet, so skip this return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> Void in ABReviewReminder.instance.incrementAndRate() } } // Handle the app launched event private func appLaunched(){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> Void in ABReviewReminder.instance.incrementAndRate() } } // Handle the app entering the foreground event private func appEnteredForeground() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> Void in ABReviewReminder.instance.incrementAndRate() } } // Increments the use count private func incrementUseCount() { let currentVersion = Double(currentAppVersion())! let userDefaults = NSUserDefaults.standardUserDefaults() // a version has been found var savedVersion: Double? = userDefaults.doubleForKey(kSavedVersion) if (savedVersion == nil) { savedVersion = currentVersion userDefaults.setDouble(currentVersion, forKey: kSavedVersion) } debug("ABReviewReminder tracking the saved version: \(currentVersion)") // a new app version if found, so start tracking again if savedVersion != currentVersion { userDefaults.setDouble(currentVersion, forKey: kSavedVersion) userDefaults.setInteger(1, forKey: kUseCount) userDefaults.setDouble(NSDate().timeIntervalSince1970, forKey: kFirstUseDate) userDefaults.setBool(false, forKey: kRatedCurrentVersion) userDefaults.setBool(false, forKey: kDeclinedToRate) userDefaults.setDouble(0, forKey: kReminderRequestDate) } else{ //retrieve the saved first used date if available let firstUseDate = userDefaults.objectForKey(kFirstUseDate) as? NSTimeInterval // set the date if not present if firstUseDate == nil { userDefaults.setDouble(NSDate().timeIntervalSince1970, forKey: kFirstUseDate) } // increment the use count var useCount = userDefaults.integerForKey(kUseCount) useCount++ userDefaults.setInteger(useCount, forKey: kUseCount) debug("ABReviewReminder use count: \(useCount)") } userDefaults.synchronize() } private func incrementAndRate() { // network stauts not defined yet, so do nothing till we know more about the connection if networkStatus == ABNetworkStatus.Unknown { return } incrementUseCount() if ratingAlertIsAppropriate() && ratingConditionsHaveBeenMet() { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.showAlert() }) } } // add the alert action at the passed index private func addAlertAction(action: UIAlertAction, atIndex index: Int = 0){ var insertionIndex: Int! // health check if index < 0 { insertionIndex = 0 //force leaving the reject rate button at the last positions } else if index > _actions.count - 1 { insertionIndex = _actions.count - 1 } // user choise else{ insertionIndex = index } _actions.insert(action, atIndex: insertionIndex) } // is this an ok time to show the alert? (regardless of whether the rating conditions have been met) // // things checked here: // * connectivity with network // * whether user has rated before // * whether user has declined to rate // * whether rating alert is currently showing visibly private func ratingAlertIsAppropriate() ->Bool { let userDefaults = NSUserDefaults.standardUserDefaults() let connectionAvailable: Bool = networkStatus == ABNetworkStatus.Online let userHasDeclinedToRate: Bool = userDefaults.boolForKey(kDeclinedToRate) let userHasRatedCurrentVersion: Bool = userDefaults.boolForKey(kRatedCurrentVersion) let isRatingAlertVisible: Bool = _alertController != nil ? _alertController!.isBeingPresented() : false return connectionAvailable && !userHasDeclinedToRate && !userHasRatedCurrentVersion && !isRatingAlertVisible } // have the rating conditions been met/earned? (regardless of whether this would be a moment when it's appropriate to show a new rating alert) // // things checked here: // * time since first launch // * number of uses of app // * time since last reminder private func ratingConditionsHaveBeenMet() -> Bool { let debugMode: Bool = _options[ABReviewReminderOptions.Debug] as! Bool if debugMode { return true } let userDefaults = NSUserDefaults.standardUserDefaults() let dateOfFirstLaunch = NSDate(timeIntervalSince1970: (userDefaults.objectForKey(kFirstUseDate) as? NSTimeInterval)!) let timeSinceFirstLaunch = NSDate().timeIntervalSinceDate(dateOfFirstLaunch) let daysUntilPrompt: Int = (_options[ABReviewReminderOptions.DaysUntilPrompt] as? Int)! let timeUntilRate: NSTimeInterval = 60 * 60 * 24 * Double(daysUntilPrompt) if timeSinceFirstLaunch < timeUntilRate { return false } // check if the user has used the app enough times let usesUntilPrompt: Int = (_options[ABReviewReminderOptions.UsesUntilPrompt] as? Int)! let useCount = userDefaults.integerForKey(kUseCount) if useCount < usesUntilPrompt { return false } // Check whether enough time has passed when the user wanted to be reminded later let dateSinceReminderRequest = NSDate(timeIntervalSince1970: (userDefaults.objectForKey(kReminderRequestDate) as? NSTimeInterval)!) let timeSinceReminderRequest: NSTimeInterval = NSDate().timeIntervalSinceDate(dateSinceReminderRequest) let timeBeforeReminding: Int = (_options[ABReviewReminderOptions.TimeBeforeReminding] as? Int)! let timeUntilReminder: NSTimeInterval = 60 * 60 * 24 * Double(timeBeforeReminding) if timeSinceReminderRequest < timeUntilReminder { return false } return true } // Show the alert private func showAlert() { let rootViewContoller = rootViewController() _alertController = UIAlertController(title: _strings[ABAlertStrings.AlertTitle], message: _strings[ABAlertStrings.AlertMessage], preferredStyle: .ActionSheet) for action in _actions { _alertController!.addAction(action) } //Present the AlertController if isIpad { let popPresenter: UIPopoverPresentationController = _alertController!.popoverPresentationController! popPresenter.sourceView = rootViewContoller.view popPresenter.sourceRect = CGRectMake(0, 0 , 50, 50) } rootViewContoller.presentViewController(_alertController!, animated: true, completion: nil) } // Hide the alert is visible private func hideAlert() { debug("ABReviewReminder hiding alert") _alertController?.dismissViewControllerAnimated(false, completion: nil) } //////////////////// // MARK: Utilities //////////////////// // check whether we are running on the iPad or not. private let isIpad = UIDevice.currentDevice().userInterfaceIdiom == .Pad // Extends the default options set by the passed new ones // @param newOptions New options to extend the default ones private func extendOptions(newOptions: [ABReviewReminderOptions : AnyObject]?) { if newOptions != nil { for (key, value) in newOptions! { _options.updateValue(value, forKey: key) } } } // Extends the default strings set by the passed new ones // @param newStrings New strings to extend the default ones private func initStrings(newStrings: [ABAlertStrings : String]?) { // get the current bundle to use let bundle = currentBundle() // get the applciation name to use let appName = currentAppName() // start the string overrides if newStrings != nil && newStrings![.AlertTitle] != nil { _strings[.AlertTitle] = newStrings![.AlertTitle] } else{ _strings[.AlertTitle] = String(format: NSLocalizedString("Rate %@", tableName: "ABReviewReminderLocalizable", bundle: bundle, value: "", comment: ""), appName) } if newStrings != nil && newStrings![.AlertMessage] != nil { _strings[.AlertMessage] = newStrings![.AlertMessage] } else{ _strings[.AlertMessage] = String(format: NSLocalizedString("If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!", tableName: "ABReviewReminderLocalizable", bundle: bundle, value: "", comment: ""), appName) } if newStrings != nil && newStrings![.AlertDeclineTitle] != nil { _strings[.AlertDeclineTitle] = newStrings![.AlertDeclineTitle] } else{ _strings[.AlertDeclineTitle] = NSLocalizedString("No, Thanks", tableName: "ABReviewReminderLocalizable", bundle: bundle, value: "", comment: "") } if newStrings != nil && newStrings![.AlertRateTitle] != nil { _strings[.AlertRateTitle] = newStrings![.AlertRateTitle] } else{ _strings[.AlertRateTitle] = String(format: NSLocalizedString("Rate %@", tableName: "ABReviewReminderLocalizable", bundle: bundle, value: "", comment: ""), appName) } if newStrings != nil && newStrings![.AlertRateLaterTitle] != nil { _strings[.AlertRateLaterTitle] = newStrings![.AlertRateLaterTitle] } else{ _strings[.AlertRateLaterTitle] = NSLocalizedString("Remind me later", tableName: "ABReviewReminderLocalizable", bundle: bundle, value: "", comment: "") } } // Init the alert action list private func initActions() { let userDefaults = NSUserDefaults.standardUserDefaults() // Rate action definiton and handeling let rateAction = UIAlertAction(title: _strings[.AlertRateTitle], style: .Default, handler: { (alert: UIAlertAction!) -> Void in self.debug("ABReviewReminder Rate button clicked.") #if TARGET_IPHONE_SIMULATOR self.debug("ABReviewReminder NOTE: iTunes App Store is not supported on the iOS simulator. Unable to open App Store page."); #else userDefaults.setBool(true, forKey: self.kRatedCurrentVersion) userDefaults.synchronize() // open the app store to rate let reviewTemplateUrl: String = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&type=Purple+Software&mt=8" let appReviewUrl = String(format: NSLocalizedString(reviewTemplateUrl, comment: ""), self._appId) UIApplication.sharedApplication().openURL(NSURL(string: appReviewUrl)!) // notify the delegage if available if let delegate: ABReviewReminderDelegate = ABReviewReminder.instance._options[ABReviewReminderOptions.Delegate] as? ABReviewReminderDelegate { delegate.userDidOptToRate?() } #endif }) // Rate later action definiton and handeling let rateLaterAction = UIAlertAction(title: _strings[.AlertRateLaterTitle], style: .Default, handler: { (alert: UIAlertAction!) -> Void in self.debug("ABReviewReminder Rate later button clicked.") userDefaults.setDouble(NSDate().timeIntervalSince1970, forKey: self.kReminderRequestDate) userDefaults.synchronize() // notify the delegage if available if let delegate: ABReviewReminderDelegate = ABReviewReminder.instance._options[ABReviewReminderOptions.Delegate] as? ABReviewReminderDelegate { delegate.userDidOptToRemindLater?() } }) // Decline action definiton and handeling let declineRateAction = UIAlertAction(title: _strings[.AlertDeclineTitle], style: .Default, handler: { (alert: UIAlertAction!) -> Void in self.debug("ABReviewReminder Decline rate button clicked.") userDefaults.setBool(true, forKey: self.kDeclinedToRate) userDefaults.synchronize() // notify the delegage if available if let delegate: ABReviewReminderDelegate = ABReviewReminder.instance._options[ABReviewReminderOptions.Delegate] as? ABReviewReminderDelegate { delegate.userDidDeclineToRate?() } }) _actions.append(rateAction) _actions.append(rateLaterAction) _actions.append(declineRateAction) } // Monitor the network changes private func monitorNetworkChanges() { let host = "google.com" var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) let reachability = SCNetworkReachabilityCreateWithName(nil, host)! // handles the receives callbacks when the reachability of the target changes. SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in let currentNetworkStatus: ABNetworkStatus = ABReviewReminder.instance.networkStatus if !flags.contains(SCNetworkReachabilityFlags.ConnectionRequired) && flags.contains(SCNetworkReachabilityFlags.Reachable) { ABReviewReminder.instance.debug("ABReviewReminder Network status changed to Online") ABReviewReminder.instance.networkStatus = ABNetworkStatus.Online } else { ABReviewReminder.instance.debug("ABReviewReminder Network status changed to Offline") ABReviewReminder.instance.networkStatus = ABNetworkStatus.Offline } // we didn't know what kind of network it was, so try to increament and show the alert again if currentNetworkStatus == ABNetworkStatus.Unknown && ABReviewReminder.instance.networkStatus != ABNetworkStatus.Unknown { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { () -> Void in ABReviewReminder.instance.incrementAndRate() } } // call the delegate with the new network change network status as bonus if let delegate: ABReviewReminderDelegate = ABReviewReminder.instance._options[ABReviewReminderOptions.Delegate] as? ABReviewReminderDelegate { delegate.reachabilityChangedWithNetworkStatus?(ABReviewReminder.instance.networkStatus.rawValue) } }, &context) SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes) } // Gets the bundle to use private func currentBundle()-> NSBundle { var bundle: NSBundle! let useMainBundle: Bool = _options[ABReviewReminderOptions.UseMainBundle] as! Bool if useMainBundle { bundle = NSBundle.mainBundle() } else{ let frameworkBundle = NSBundle(forClass: self.dynamicType) if let abreviewReminderBundleURL = frameworkBundle.URLForResource("ABReviewReminder", withExtension: "bundle") { // ABReviewReminder will likely only exist when used via CocoaPods bundle = NSBundle(URL: abreviewReminderBundleURL) } else{ bundle = NSBundle.mainBundle() } } return bundle } // Prints only if the debug flag is set private func debug(items: Any...){ let canDebug: Bool = _options[ABReviewReminderOptions.Debug] as! Bool if canDebug { print(items) } } // Get App name to show, check whether the app is localized or not // @return The app name is going to be used in the alert private func currentAppName()-> String { if let localizedInfoDictionary = NSBundle.mainBundle().localizedInfoDictionary { if let localizedAppName = localizedInfoDictionary["CFBundleDisplayName"] as? String { // we found a lozalized app name so, return it return localizedAppName; } } return NSBundle.mainBundle().infoDictionary?["CFBundleName"] as! String } // Gets the current app version private func currentAppVersion()-> String{ let versionType: String = (_options[ABReviewReminderOptions.AppVersionType] as? String)! return (NSBundle.mainBundle().infoDictionary?[versionType] as? String)! } // Get the root view controller private func rootViewController() -> UIViewController { let window: UIWindow = UIApplication.sharedApplication().keyWindow! if (window.windowLevel != UIWindowLevelNormal) { for window in UIApplication.sharedApplication().windows { if (window.windowLevel == UIWindowLevelNormal) { break; } } } return iterateSubViewsForViewController(window) as! UIViewController } private func iterateSubViewsForViewController(parentView: UIView) -> AnyObject? { for subView in parentView.subviews { if let responder:UIViewController = subView.nextResponder() as? UIViewController{ return topMostViewController(responder) } if let found = iterateSubViewsForViewController(subView) { return found } } return nil } private func topMostViewController(var controller: UIViewController) -> UIViewController { var isPresenting = false repeat { let presented = controller.presentedViewController isPresenting = presented != nil if(presented != nil) { controller = presented! } } while isPresenting return controller } }
mit
1ae7a664c9fa6a60087a79e40c5b138c
40.691964
290
0.645679
5.213435
false
false
false
false
brentsimmons/Evergreen
iOS/Settings/EnableExtensionViewController.swift
1
3762
// // EnableExtensionViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 4/16/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import UIKit import AuthenticationServices import Account import OAuthSwift import Secrets class EnableExtensionPointViewController: UITableViewController { @IBOutlet weak var extensionDescription: UILabel! private let callbackURL = URL(string: "vincodennw://")! private var oauth: OAuthSwift? weak var delegate: AddExtensionPointDismissDelegate? var extensionPointType: ExtensionPoint.Type? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = extensionPointType?.title ?? "" extensionDescription = extensionPointType?.extensionDescription ?? "" tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } @IBAction func cancel(_ sender: Any) { dismiss(animated: true, completion: nil) delegate?.dismiss() } @IBAction func enable(_ sender: Any) { guard let extensionPointType = extensionPointType else { return } if let oauth1 = extensionPointType as? OAuth1SwiftProvider.Type { enableOauth1(oauth1) } else { ExtensionPointManager.shared.activateExtensionPoint(extensionPointType) dismiss(animated: true, completion: nil) delegate?.dismiss() } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView headerView.imageView.image = extensionPointType?.templateImage return headerView } else { return super.tableView(tableView, viewForHeaderInSection: section) } } } extension EnableExtensionPointViewController: OAuthSwiftURLHandlerType { public func handle(_ url: URL) { let session = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackURL.scheme, completionHandler: { (url, error) in if let callbackedURL = url { OAuth1Swift.handle(url: callbackedURL) } guard let error = error else { return } self.oauth?.cancel() self.oauth = nil DispatchQueue.main.async { self.dismiss(animated: true, completion: nil) self.delegate?.dismiss() } if case ASWebAuthenticationSessionError.canceledLogin = error { print("Login cancelled.") } else { self.presentError(error) } }) session.presentationContextProvider = self if !session.start() { print("Session failed to start!!!") } } } extension EnableExtensionPointViewController: ASWebAuthenticationPresentationContextProviding { public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return view.window! } } private extension EnableExtensionPointViewController { func enableOauth1(_ provider: OAuth1SwiftProvider.Type) { let oauth1 = provider.oauth1Swift self.oauth = oauth1 oauth1.authorizeURLHandler = self oauth1.authorize(withCallbackURL: callbackURL) { [weak self] result in guard let self = self, let extensionPointType = self.extensionPointType else { return } switch result { case .success(let tokenSuccess): ExtensionPointManager.shared.activateExtensionPoint(extensionPointType, tokenSuccess: tokenSuccess) self.dismiss(animated: true, completion: nil) self.delegate?.dismiss() case .failure(let oauthSwiftError): self.presentError(oauthSwiftError) } self.oauth?.cancel() self.oauth = nil } } }
mit
3ba07eb52a6301e7559e59cda8732cfa
27.492424
128
0.751662
4.206935
false
false
false
false
yoonapps/QPXExpressWrapper
QPXExpressWrapper/Classes/TripOptionSliceSegmentLeg.swift
1
3086
// // TripOptionSliceLeg.swift // Flights // // Created by Kyle Yoon on 2/14/16. // Copyright © 2016 Kyle Yoon. All rights reserved. // import Foundation import Gloss public struct TripOptionSliceSegmentLeg: Decodable { public let kind: String public let identifier: String? public let aircraft: String? public let arrivalTime: Date? // TODO: We have to show the local time of that location. public let departureTime: Date? // TODO: We have to show the local time of that location. public let origin: String? public let destination: String? public let originTerminal: String? public let destinationTerminal: String? public let duration: Int? public let onTimePerformance: Int? public let operatingDisclosure: String? public let mileage: Int? public let meal: String? public let secure: Bool? public let connectionDuration: Int? public init?(json: JSON) { guard let kind: String = "kind" <~~ json else { return nil } self.kind = kind self.identifier = "id" <~~ json self.aircraft = "aircraft" <~~ json if let arrivalTimeString: String = "arrivalTime" <~~ json { self.arrivalTime = SearchResults.dateFormatter.decodedDate(for: arrivalTimeString) } else { self.arrivalTime = nil } if let departureTimeString: String = "departureTime" <~~ json { self.departureTime = SearchResults.dateFormatter.decodedDate(for: departureTimeString) } else { self.departureTime = nil } self.origin = "origin" <~~ json self.destination = "destination" <~~ json self.originTerminal = "originTerminal" <~~ json self.destinationTerminal = "destinationTerminal" <~~ json self.duration = "duration" <~~ json self.onTimePerformance = "onTimePerformance" <~~ json self.operatingDisclosure = "operatingDisclosure" <~~ json self.mileage = "mileage" <~~ json self.meal = "meal" <~~ json self.secure = "secure" <~~ json self.connectionDuration = "connectionDuration" <~~ json } } extension TripOptionSliceSegmentLeg: Equatable {} public func ==(lhs: TripOptionSliceSegmentLeg, rhs: TripOptionSliceSegmentLeg) -> Bool { return lhs.kind == rhs.kind && lhs.identifier == rhs.identifier && lhs.aircraft == rhs.aircraft && (lhs.arrivalTime == rhs.arrivalTime) && (lhs.departureTime == rhs.departureTime) && lhs.origin == rhs.origin && lhs.destination == rhs.destination && lhs.originTerminal == rhs.originTerminal && lhs.destinationTerminal == rhs.destinationTerminal && lhs.duration == rhs.duration && lhs.mileage == rhs.mileage && lhs.meal == rhs.meal && lhs.secure == rhs.secure && lhs.onTimePerformance == rhs.onTimePerformance && lhs.operatingDisclosure == rhs.operatingDisclosure && lhs.connectionDuration == rhs.connectionDuration }
mit
84b2cc6b5ca79a9d8bcc86f6f042db8a
35.294118
98
0.633387
4.458092
false
false
false
false
elslooo/hoverboard
Hoverboard/Utilities/LoginItem.swift
1
6470
/* * Copyright (c) 2017 Tim van Elsloo * * 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 /** * This class provides a wrapper around LSSharedFileListItem for * kLSSharedFileListSessionLoginItems. */ public class LoginItem { /** * A login item is referenced by its url of the application to start at * launch. */ public let url: URL /** * If this login item already exists, we keep a reference to the * corresponding `LSSharedFileListItem` so we can use that to remove it * later on. */ private var reference: LSSharedFileListItem? /** * This is a login item for the main bundle. Most of the time, this is the * only login item you will need. The only exception is when you're bundling * helper apps. * * - NOTE: this does not mean that the login item is automatically added to * the system. */ public static let main = LoginItem(url: Bundle.main.bundleURL) /** * This function initializes a new login item with the given url. It does * not automatically enable it, however. If it already exists, it also does * not disable it. */ public init(url: URL) { self.url = url if let item = LoginItem.all.first(where: { $0.url == url }) { self.reference = item.reference } } /** * This function initializes a new login item with the given native * reference. */ private init?(reference: LSSharedFileListItem) { self.reference = reference let resolutionFlags = UInt32(kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes) // We retrieve the url that corresponds to the given item. For some // reason, Apple indicates that this method may fail, therefore this // initializer is failable as well. guard let url = LSSharedFileListItemCopyResolvedURL(reference, resolutionFlags, nil) else { return nil } self.url = url.takeUnretainedValue() as URL } /** * This property returns a list of all login items registered on the user * system. * * - NOTE: this also includes login items for other applications. */ public static var all: [LoginItem] { // We want to retrieve login items. let type = kLSSharedFileListSessionLoginItems.takeUnretainedValue() // If we cannot retrieve them (I guess for example if the app is // sandboxed), this call will fail and we return an empty array. guard let items = LSSharedFileListCreate(nil, type, nil) else { return [] } let list = items.takeUnretainedValue() // Snapshot seed can be used to update an existing snapshot (educated // guess). We don't need that. var seed: UInt32 = 0 guard let copy = LSSharedFileListCopySnapshot(list, &seed) else { return [] } guard let snapshot = copy.takeUnretainedValue() as? [LSSharedFileListItem] else { return [] } var results: [LoginItem] = [] for item in snapshot { guard let item = LoginItem(reference: item) else { continue } results.append(item) } // At least in Swift 3.1, memory of the file list and its snapshot is // managed by the system and we should not manually release any of it. return results } /** * This property returns a boolean that reflects whether or not the login * item is actually enabled. Upon changing this value, we automatically add * or remove the login item from / to the system's login items list. This * operation may fail, in which case the getter will reflect the actual * state of the login item. */ var isEnabled: Bool { get { return LoginItem.all.contains(where: { $0.url == self.url }) } set { if self.isEnabled == newValue { return } // We want to retrieve login items. let type = kLSSharedFileListSessionLoginItems.takeUnretainedValue() guard let items = LSSharedFileListCreate(nil, type, nil) else { return } if newValue { // I am not sure why this is an optional. My guess would be it // may not be available on all systems and is NULL or nil on // earlier systems. guard let order = kLSSharedFileListItemBeforeFirst else { return } LSSharedFileListInsertItemURL(items.takeUnretainedValue(), order.takeUnretainedValue(), nil, nil, self.url as CFURL, nil, nil) if let item = LoginItem.all.first(where: { $0.url == url }) { self.reference = item.reference } } else { LSSharedFileListItemRemove(items.takeUnretainedValue(), self.reference) self.reference = nil } } } }
mit
98bac2ec011b39f8a7aa7841640abc72
34.944444
80
0.598764
5.07451
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Cells/AwesomeMediaFileTableViewCell.swift
1
2378
// // AwesomeMediaFileTableViewCell.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 5/3/18. // import UIKit public class AwesomeMediaFileTableViewCell: UITableViewCell { @IBOutlet public weak var mainView: UIView! @IBOutlet public weak var coverImageView: UIImageView! @IBOutlet public weak var coverIconImageView: UIImageView! @IBOutlet public weak var fullscreenButton: UIButton! @IBOutlet public weak var titleLabel: UILabel! @IBOutlet public weak var descLabel: UILabel! // Public variables public var mediaParams = AwesomeMediaParams() public override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } public func configure(withMediaParams mediaParams: AwesomeMediaParams) { self.mediaParams = mediaParams // Load cover Image loadCoverImage() // Set Media Information updateMediaInformation() } // MARK: - Events @IBAction public func fullscreenButtonPressed(_ sender: Any) { guard let url = mediaParams.url?.url else { return } self.parentViewController?.presentWebPageInSafari(withURL: url) // track event track(event: .toggleFullscreen, source: .fileCell, params: mediaParams) } // MARK: - Dimensions public static var defaultSize: CGSize { var defaultSize = UIScreen.main.bounds.size defaultSize.height = isPad ? 200 : 140 return defaultSize } } // MARK: - Media Information extension AwesomeMediaFileTableViewCell { public func updateMediaInformation() { titleLabel.text = mediaParams.title descLabel.text = "" if let type = mediaParams.type { descLabel.text = type.uppercased().appending(" ") coverIconImageView.isHidden = type.uppercased() != "PDF" } if let size = mediaParams.size { descLabel.text?.append("(\(size.uppercased()))") } } public func loadCoverImage() { guard let coverImageUrl = mediaParams.coverUrl else { return } // set the cover image coverImageView.setImage(coverImageUrl) } }
mit
2cfed4dc797bbf1df480a439d04fb766
26.022727
79
0.618587
5.416856
false
false
false
false
jensmeder/DarkLightning
Sources/Daemon/Sources/Messages/ConnectMessageData.swift
1
2230
/** * * DarkLightning * * * * The MIT License (MIT) * * Copyright (c) 2017 Jens Meder * * 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 internal final class ConnectMessageData: OODataWrap { private static let DictionaryKeyMessageType = "MessageType" private static let MessageTypeConnect = "Connect" private static let ProgNameValue = "DarkLightning" private static let DictionaryKeyProgName = "ProgName" private static let DictionaryKeyDeviceID = "DeviceID" private static let DictionaryKeyPortNumber = "PortNumber" // MARK: Init internal required init(deviceID: Int, port: UInt32) { let p: UInt32 = ((port<<8) & 0xFF00) | (port>>8) super.init( origin: MessageData( data: DictData( dict: [ ConnectMessageData.DictionaryKeyMessageType: ConnectMessageData.MessageTypeConnect, ConnectMessageData.DictionaryKeyDeviceID: NSNumber(integerLiteral: deviceID), ConnectMessageData.DictionaryKeyPortNumber: NSNumber(integerLiteral: Int(p)), ConnectMessageData.DictionaryKeyProgName: ConnectMessageData.ProgNameValue ] ), packetType: 8, messageTag: 1, protocolType: 1 ) ) } }
mit
fefb1d38b6d519d9e9f68c2ab6ec4eeb
36.166667
89
0.739462
4.121996
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Message/Friend/FriendMessageViewController.swift
1
3194
// // FriendMessageViewController.swift // HiPDA // // Created by leizh007 on 2017/6/28. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation class FriendMessageViewController: MessageTableViewController { var friendMessageViewModel: FriendMessageViewModel! override var viewModel: MessageTableViewModel! { get { return friendMessageViewModel } set { friendMessageViewModel = newValue as? FriendMessageViewModel } } override func skinViewModel() { friendMessageViewModel = FriendMessageViewModel() } override func skinTableView() { super.skinTableView() tableView.register(FriendMessageTableViewCell.self) } } extension FriendMessageViewController { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as FriendMessageTableViewCell skinCell(cell, at: indexPath.row) return cell } private func skinCell(_ cell: FriendMessageTableViewCell, at index: Int) { cell.separatorInset = .zero cell.title = friendMessageViewModel.title(at: index) cell.time = friendMessageViewModel.time(at: index) cell.isRead = friendMessageViewModel.isRead(at: index) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { super.tableView(tableView, didSelectRowAt: indexPath) let user = self.friendMessageViewModel.model(at: indexPath.row).sender let vc = UIAlertController(title: "好友消息操作", message: "处理 \(user.name) 发送的好友请求", preferredStyle: .actionSheet) let userProfileAction = UIAlertAction(title: "查看 \(user.name) 的资料", style: .default) { [weak self] _ in guard let `self` = self else { return } let vc = UserProfileViewController.load(from: .home) vc.uid = user.uid self.pushViewController(vc, animated: true) } let addFriendAction = UIAlertAction(title: "加 \(user.name) 为好友", style: .default) { [weak self] _ in guard let `self` = self else { return } self.showPromptInformation(of: .loading("正在添加好友...")) self.friendMessageViewModel.addFriend(at: indexPath.row) { [weak self] result in self?.hidePromptInformation() switch result { case .success(let info): self?.showPromptInformation(of: .success(info)) case .failure(let error): self?.showPromptInformation(of: .failure(error.localizedDescription)) } } } let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil) vc.addAction(userProfileAction) vc.addAction(addFriendAction) vc.addAction(cancel) present(vc, animated: true, completion: nil) } }
mit
866ae2e95de01421286088a6185b80e0
37.604938
117
0.641829
4.863142
false
false
false
false
jmgc/swift
test/SILGen/initializers.swift
1
42646
// RUN: %target-swift-emit-silgen -disable-objc-attr-requires-foundation-module -enable-objc-interop %s -module-name failable_initializers | %FileCheck %s // High-level tests that silgen properly emits code for failable and thorwing // initializers. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = Canary() return nil } init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } init?(failBeforeInitialization: ()) { return nil } init?(failAfterPartialInitialization: ()) { x = T() return nil } init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes //// //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } init?(failBeforeFullInitialization: ()) { return nil } init?(failAfterFullInitialization: ()) { member = Canary() return nil } convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br bb2([[RESULT]] : $Optional<FailableBaseClass>) // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[RESULT]] // CHECK-NEXT: } convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: cond_br {{.*}}, [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB:bb[0-9]+]]: // CHECK: destroy_value [[NEW_SELF]] // CHECK: br [[FAIL_EPILOG_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK: [[UNWRAPPED_NEW_SELF:%.*]] = unchecked_enum_data [[NEW_SELF]] : $Optional<FailableBaseClass>, #Optional.some!enumelt // CHECK: assign [[UNWRAPPED_NEW_SELF]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_EPILOG_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: br [[EPILOG_BB]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional // // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17FailableBaseClassC21failDuringDelegation2ACSgyt_tcfC // CHECK: bb0([[SELF_META:%.*]] : $@thick FailableBaseClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[SELF_META]]) // CHECK: switch_enum [[NEW_SELF]] : $Optional<FailableBaseClass>, case #Optional.some!enumelt: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: unreachable // // CHECK: [[SUCC_BB]]([[RESULT:%.*]] : @owned $FailableBaseClass): // CHECK: assign [[RESULT]] to [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[RESULT]] : $FailableBaseClass // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>): // CHECK: return [[WRAPPED_RESULT]] // CHECK-NEXT: } convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // CHECK-NEXT: br bb1 // // CHECK: bb1: // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br bb2([[RESULT]] // // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> { // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass): init?(derivedFailDuringDelegation: ()) { // First initialize the lvalue for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[OLD_SELF]] to [init] [[PB_BOX]] // // Then assign canary to other member using a borrow. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_BOX]] // CHECK: [[CANARY_VALUE:%.*]] = apply // CHECK: [[CANARY_GEP:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[CANARY_GEP]] : $*Canary // CHECK: assign [[CANARY_VALUE]] to [[WRITE]] self.otherMember = Canary() // Finally, begin the super init sequence. // CHECK: [[LOADED_SELF:%.*]] = load [take] [[PB_BOX]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[LOADED_SELF]] // CHECK: [[OPT_NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_SELF]]) : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> // CHECK: [[IS_NIL:%.*]] = select_enum [[OPT_NEW_SELF]] // CHECK: cond_br [[IS_NIL]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // And then return nil making sure that we do not insert any extra values anywhere. // CHECK: [[SUCC_BB]]: // CHECK: [[NEW_SELF:%.*]] = unchecked_enum_data [[OPT_NEW_SELF]] // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_BOX]] // CHECK: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[WRAPPED_RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt, [[RESULT]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: br [[EPILOG_BB:bb[0-9]+]]([[WRAPPED_RESULT]] // // CHECK: [[FAIL_BB]]: // CHECK: destroy_value [[MARKED_SELF_BOX]] super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} required init(throwingCanary: Canary) throws {} init(canary: Canary) {} init(noFail: ()) {} init(fail: Int) throws {} init(noFail: Int) {} } class ThrowDerivedClass : ThrowBaseClass { var canary: Canary? required init(throwingCanary: Canary) throws { } required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } override init(fail: Int) throws {} override init(noFail: Int) {} // ---- Delegating to super // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: store [[OPT_CANARY]] to [init] [[CANARY_ADDR]] // CHECK: end_borrow [[SELF]] // // Now we perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // CHECK: [[NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_BASE:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[BASE_INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[SELF_INIT_BASE:%.*]] = apply [[BASE_INIT_FN]]([[SELF_BASE]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[SELF_INIT_BASE]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // Finally the error BB. We do not touch self since self is still in the // box implying that destroying MARK_UNINIT will destroy it for us. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc' init(delegatingFailBeforeDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Then initialize the canary with nil. We are able to borrow the initialized self to avoid retain/release overhead. // CHECK: [[SELF:%.*]] = load_borrow [[PROJ]] // CHECK: [[CANARY_ADDR:%.*]] = ref_element_addr [[SELF]] // CHECK: [[CANARY_FUNC:%.*]] = function_ref @$s21failable_initializers17ThrowDerivedClassC6canaryAA6CanaryCSgvpfi : // CHECK: [[OPT_CANARY:%.*]] = apply [[CANARY_FUNC]]() // CHECK: store [[OPT_CANARY]] to [init] [[CANARY_ADDR]] // CHECK: end_borrow [[SELF]] // // Now we begin argument emission where we perform the unwrap. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Now we emit the call to the initializer. Notice how we return self back to // its memory locatio nbefore any other work is done. // CHECK: [[NORMAL_BB]]( // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) // CHECK: [[BASE_SELF_INIT:%.*]] = apply [[INIT_FN]]({{%.*}}, [[BASE_SELF]]) // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // // Handle the return value. // CHECK: [[SELF:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[SELF]] // // When the error is thrown, we need to: // 1. Store self back into the "conceptually" uninitialized box. // 2. destroy the box. // 3. Perform the rethrow. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF]] to [init] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc' init(delegatingFailDuringDelegationArgEmission : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassCACyKcfc : $@convention(method) // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> (@owned ThrowBaseClass, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]([[BASE_SELF_INIT:%.*]] : @owned $ThrowBaseClass): // CHECK: [[OUT_SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[OUT_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc' init(delegatingFailDuringDelegationCall : Int) throws { try super.init() } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // CHECK: bb0( // First initialize. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // CHECK: store {{%.*}} to [init] [[PROJ]] // // Call the initializer and then store the new self back into its memory slot. // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method) // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF_CAST]] to [init] [[PROJ]] // // Finally perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]] // // Insert the return statement into the normal block... // CHECK: [[NORMAL_BB]]( // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARK_UNINIT]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc' init(delegatingFailAfterDelegation : Int) throws { super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) { // Create our box. // CHECK: [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass } // CHECK: [[PROJ:%.*]] = project_box [[MARK_UNINIT]] // // Perform the unwrap. // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB:bb[0-9]+]], error [[UNWRAP_ERROR_BB:bb[0-9]+]] // // Now we begin argument emission where we perform another unwrap. // CHECK: [[UNWRAP_NORMAL_BB]]( // CHECK: [[SELF:%.*]] = load [take] [[PROJ]] // CHECK: [[SELF_CAST:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass // CHECK: [[UNWRAP_FN2:%.*]] = function_ref @$s21failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error) // CHECK: try_apply [[UNWRAP_FN2]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB2:bb[0-9]+]], error [[UNWRAP_ERROR_BB2:bb[0-9]+]] // // Then since this example has a // CHECK: [[UNWRAP_NORMAL_BB2]]([[INT:%.*]] : $Int): // CHECK: [[INIT_FN2:%.*]] = function_ref @$s21failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF_CAST:%.*]] = apply [[INIT_FN2]]([[INT]], [[SELF_CAST]]) : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass // CHECK: [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[NEW_SELF]] to [init] [[PROJ]] // CHECK: [[RESULT:%.*]] = load [copy] [[PROJ]] // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: return [[RESULT]] // // ... and destroy the box in the error block. // CHECK: [[UNWRAP_ERROR_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK: br [[ERROR_JOIN:bb[0-9]+]]([[ERROR]] // // CHECK: [[UNWRAP_ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK: [[SELF_CASTED_BACK:%.*]] = unchecked_ref_cast [[SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass // CHECK: store [[SELF_CASTED_BACK]] to [init] [[PROJ]] // CHECK: br [[ERROR_JOIN]]([[ERROR]] // // CHECK: [[ERROR_JOIN]]([[ERROR_PHI:%.*]] : @owned $Error): // CHECK: destroy_value [[MARK_UNINIT]] // CHECK: throw [[ERROR_PHI]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc' init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() } init(delegatingFailBeforeDelegation : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: ()) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init() try unwrap(delegatingFailAfterDelegation) } init(delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int, delegatingFailDuringDelegationCall : Int, delegatingFailAfterDelegation : Int) throws { try unwrap(delegatingFailBeforeDelegation) try super.init(fail: try unwrap(delegatingFailDuringDelegationArgEmission)) try unwrap(delegatingFailAfterDelegation) } // ---- Delegating to other self method. convenience init(chainingFailBeforeDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) } convenience init(chainingFailDuringDelegationArgEmission : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationCall : Int) throws { try self.init() } convenience init(chainingFailAfterDelegation : Int) throws { self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() } convenience init(chainingFailBeforeDelegation : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: ()) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC39chainingFailDuringDelegationArgEmission0fghI4CallACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]( // CHECK: try_apply {{.*}}({{.*}}, [[SELF_META]]) : {{.*}}, normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers17ThrowDerivedClassC32chainingFailDuringDelegationCall0fg5AfterI0ACSi_SitKcfC // CHECK: bb0({{.*}}, [[SELF_META:%.*]] : $@thick ThrowDerivedClass.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self" // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: try_apply {{.*}}([[SELF_META]]) : {{.*}}, normal [[SUCC_BB1:bb[0-9]+]], error [[ERROR_BB1:bb[0-9]+]] // // CHECK: [[SUCC_BB1]]([[NEW_SELF:%.*]] : @owned $ThrowDerivedClass): // CHECK-NEXT: assign [[NEW_SELF]] to [[PB_BOX]] // CHECK-NEXT: // function_ref // CHECK-NEXT: function_ref @ // CHECK-NEXT: try_apply {{.*}}({{.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[SUCC_BB2:bb[0-9]+]], error [[ERROR_BB2:bb[0-9]+]] // // CHECK: [[SUCC_BB2]]( // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[PB_BOX]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[RESULT]] // // CHECK: [[ERROR_BB1]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB:bb[0-9]+]]([[ERROR]] // // CHECK: [[ERROR_BB2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: br [[THROWING_BB]]([[ERROR]] // // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$s21failable_initializers17ThrowDerivedClassC28chainingFailBeforeDelegation0fg6DuringI11ArgEmission0fgjI4CallACSi_S2itKcfC' convenience init(chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) self.init(noFail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init() try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } convenience init(chainingFailBeforeDelegation : Int, chainingFailDuringDelegationArgEmission : Int, chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws { try unwrap(chainingFailBeforeDelegation) try self.init(fail: try unwrap(chainingFailDuringDelegationArgEmission)) try unwrap(chainingFailAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } @objc protocol P3 { init?(p3: Int64) } extension P3 { init!(p3a: Int64) { self.init(p3: p3a)! // unnecessary-but-correct '!' } init(p3b: Int64) { self.init(p3: p3b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } } class InOutInitializer { // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s21failable_initializers16InOutInitializerC1xACSiz_tcfC : $@convention(method) (@inout Int, @thick InOutInitializer.Type) -> @owned InOutInitializer { // CHECK: bb0(%0 : $*Int, %1 : $@thick InOutInitializer.Type): init(x: inout Int) {} } // <rdar://problem/16331406> class SuperVariadic { init(ints: Int...) { } } class SubVariadic : SuperVariadic { } // CHECK-LABEL: sil hidden [ossa] @$s21failable_initializers11SubVariadicC4intsACSid_tcfc // CHECK: bb0(%0 : @owned $Array<Int>, %1 : @owned $SubVariadic): // CHECK: [[SELF_UPCAST:%.*]] = upcast {{.*}} : $SubVariadic to $SuperVariadic // CHECK: [[T0:%.*]] = begin_borrow %0 : $Array<Int> // CHECK: [[T1:%.*]] = copy_value [[T0]] : $Array<Int> // CHECK: [[SUPER_INIT:%.*]] = function_ref @$s21failable_initializers13SuperVariadicC4intsACSid_tcfc // CHECK: apply [[SUPER_INIT]]([[T1]], [[SELF_UPCAST]]) // CHECK-LABEL: } // end sil function public struct MemberInits<Value : Equatable> { private var box: MemberInitsHelper<Value>? fileprivate var value: String = "default" } class MemberInitsHelper<T> { } extension MemberInits { // CHECK-LABEL: sil [ossa] @$s21failable_initializers11MemberInitsVyACySayqd__GGSayACyqd__GGcADRszSQRd__lufC : $@convention(method) <Value><T where Value == Array<T>, T : Equatable> (@owned Array<MemberInits<T>>, @thin MemberInits<Array<T>>.Type) -> @owned MemberInits<Array<T>> { public init<T>(_ array: [MemberInits<T>]) where Value == [T] { box = nil // CHECK: [[INIT_FN:%.*]] = function_ref @$s21failable_initializers11MemberInitsV5value33_4497B2E9306011E5BAC13C07BEAC2557LLSSvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String // CHECK-NEXT: = apply [[INIT_FN]]<Array<T>>() : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> () -> @owned String } } // rdar://problem/51302498 class Butt { init(foo: inout (Int, Int)) { } }
apache-2.0
f7040fb4c740696771c7144e307b6d34
36.015625
282
0.657099
3.614648
false
false
false
false
slavapestov/swift
test/SILGen/reabstract.swift
1
2674
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s func takeFn<T>(f : T -> T?) {} func liftOptional(x : Int) -> Int? { return x } func test0() { takeFn(liftOptional) } // CHECK: sil hidden @_TF10reabstract5test0FT_T_ : $@convention(thin) () -> () { // CHECK: [[T0:%.*]] = function_ref @_TF10reabstract6takeFn // Emit a generalized reference to liftOptional. // TODO: just emit a globalized thunk // CHECK-NEXT: reabstract.liftOptional // CHECK-NEXT: [[T1:%.*]] = function_ref @_TF10reabstract12liftOptional // CHECK-NEXT: [[T2:%.*]] = thin_to_thick_function [[T1]] // CHECK-NEXT: reabstraction thunk // CHECK-NEXT: [[T3:%.*]] = function_ref [[THUNK:@.*]] : // CHECK-NEXT: [[T4:%.*]] = partial_apply [[T3]]([[T2]]) // CHECK-NEXT: apply [[T0]]<Int>([[T4]]) // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil shared [transparent] [reabstraction_thunk] [[THUNK]] : $@convention(thin) (@out Optional<Int>, @in Int, @owned @callee_owned (Int) -> Optional<Int>) -> () { // CHECK: [[T0:%.*]] = load %1 : $*Int // CHECK-NEXT: [[T1:%.*]] = apply %2([[T0]]) // CHECK-NEXT: store [[T1]] to %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_TF10reabstract10testThrowsFP_T_ // CHECK: function_ref @_TTRXFo_iT__iT__XFo__dT__ // CHECK: function_ref @_TTRXFo_iT__iT_zoPs9ErrorType__XFo__dT_zoPS___ func testThrows(x: Any) { _ = x as? () -> () _ = x as? () throws -> () } // Make sure that we preserve inout-ness when lowering types with maximum // abstraction level -- <rdar://problem/21329377> class C {} struct Box<T> { let t: T } func notFun(inout c: C, i: Int) {} func testInoutOpaque(c: C, i: Int) { var c = c let box = Box(t: notFun) box.t(&c, i: i) } // CHECK-LABEL: sil hidden @_TF10reabstract15testInoutOpaqueFTCS_1C1iSi_T_ // CHECK: function_ref @_TF10reabstract6notFunFTRCS_1C1iSi_T_ // CHECK: thin_to_thick_function {{%[0-9]+}} // CHECK: function_ref @_TTRXFo_lC10reabstract1CdSi_dT__XFo_lS0_iSi_iT__ // CHECK: partial_apply // CHECK: store // CHECK: load // CHECK: function_ref @_TTRXFo_lC10reabstract1CiSi_iT__XFo_lS0_dSi_dT__ // CHECK: partial_apply // CHECK: apply // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_lC10reabstract1CdSi_dT__XFo_lS0_iSi_iT__ : $@convention(thin) (@out (), @inout C, @in Int, @owned @callee_owned (@inout C, Int) -> ()) -> () { // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_lC10reabstract1CiSi_iT__XFo_lS0_dSi_dT__ : $@convention(thin) (@inout C, Int, @owned @callee_owned (@out (), @inout C, @in Int) -> ()) -> () {
apache-2.0
57fc6d652db66e95bed712cc6c7d9fb8
39.515152
214
0.613313
2.964523
false
true
false
false
abertelrud/swift-package-manager
Sources/Commands/PackageTools/DumpCommands.swift
2
5065
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2022 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 ArgumentParser import Basics import CoreCommands import Foundation import PackageModel import XCBuildSupport struct DumpSymbolGraph: SwiftCommand { static let configuration = CommandConfiguration( abstract: "Dump Symbol Graph") static let defaultMinimumAccessLevel = SymbolGraphExtract.AccessLevel.public @OptionGroup(_hiddenFromHelp: true) var globalOptions: GlobalOptions @Flag(help: "Pretty-print the output JSON.") var prettyPrint = false @Flag(help: "Skip members inherited through classes or default implementations.") var skipSynthesizedMembers = false @Option(help: "Include symbols with this access level or more. Possible values: \(SymbolGraphExtract.AccessLevel.allValueStrings.joined(separator: " | "))") var minimumAccessLevel = defaultMinimumAccessLevel @Flag(help: "Skip emitting doc comments for members inherited through classes or default implementations.") var skipInheritedDocs = false @Flag(help: "Add symbols with SPI information to the symbol graph.") var includeSPISymbols = false func run(_ swiftTool: SwiftTool) throws { // Build the current package. // // We turn build manifest caching off because we need the build plan. let buildSystem = try swiftTool.createBuildSystem(explicitBuildSystem: .native, cacheBuildManifest: false) try buildSystem.build() // Configure the symbol graph extractor. let symbolGraphExtractor = try SymbolGraphExtract( fileSystem: swiftTool.fileSystem, tool: swiftTool.getDestinationToolchain().getSymbolGraphExtract(), skipSynthesizedMembers: skipSynthesizedMembers, minimumAccessLevel: minimumAccessLevel, skipInheritedDocs: skipInheritedDocs, includeSPISymbols: includeSPISymbols, outputFormat: .json(pretty: prettyPrint) ) // Run the tool once for every library and executable target in the root package. let buildPlan = try buildSystem.buildPlan let symbolGraphDirectory = buildPlan.buildParameters.dataPath.appending(component: "symbolgraph") let targets = try buildSystem.getPackageGraph().rootPackages.flatMap{ $0.targets }.filter{ $0.type == .library || $0.type == .executable } for target in targets { print("-- Emitting symbol graph for", target.name) try symbolGraphExtractor.extractSymbolGraph( target: target, buildPlan: buildPlan, outputDirectory: symbolGraphDirectory, verboseOutput: swiftTool.logLevel <= .info ) } print("Files written to", symbolGraphDirectory.pathString) } } struct DumpPackage: SwiftCommand { static let configuration = CommandConfiguration( abstract: "Print parsed Package.swift as JSON") @OptionGroup(_hiddenFromHelp: true) var globalOptions: GlobalOptions func run(_ swiftTool: SwiftTool) throws { let workspace = try swiftTool.getActiveWorkspace() let root = try swiftTool.getWorkspaceRoot() let rootManifests = try temp_await { workspace.loadRootManifests( packages: root.packages, observabilityScope: swiftTool.observabilityScope, completion: $0 ) } guard let rootManifest = rootManifests.values.first else { throw StringError("invalid manifests at \(root.packages)") } let encoder = JSONEncoder.makeWithDefaults() encoder.userInfo[Manifest.dumpPackageKey] = true let jsonData = try encoder.encode(rootManifest) let jsonString = String(data: jsonData, encoding: .utf8)! print(jsonString) } } struct DumpPIF: SwiftCommand { @OptionGroup(_hiddenFromHelp: true) var globalOptions: GlobalOptions @Flag(help: "Preserve the internal structure of PIF") var preserveStructure: Bool = false func run(_ swiftTool: SwiftTool) throws { let graph = try swiftTool.loadPackageGraph() let pif = try PIFBuilder.generatePIF( buildParameters: swiftTool.buildParameters(), packageGraph: graph, fileSystem: swiftTool.fileSystem, observabilityScope: swiftTool.observabilityScope, preservePIFModelStructure: preserveStructure) print(pif) } var toolWorkspaceConfiguration: ToolWorkspaceConfiguration { return .init(wantsMultipleTestProducts: true) } }
apache-2.0
dc679227bfdfc0da90966dbff2226515
37.664122
160
0.66693
5.20555
false
true
false
false
MrMage/DateRangePicker
DateRangePicker/DateRangePickerView.swift
1
16636
// // DateRangePickerView.swift // DateRangePicker // // Created by Daniel Alm on 07.11.15. // Copyright © 2015 Daniel Alm. All rights reserved. // import Cocoa @objc public protocol DateRangePickerViewDelegate { func dateRangePickerView( _ dateRangePickerView: DateRangePickerView, willPresentExpandedDateRangePickerController expandedDateRangePickerController: ExpandedDateRangePickerController) func dateRangePickerViewDidCloseExpandedDateRangePickerController(_ dateRangePickerView: DateRangePickerView) } public protocol DateRangePickerViewDelegateSwiftOnly: DateRangePickerViewDelegate { func dateRangePickerView(_ dateRangePickerView: DateRangePickerView, descriptionFor dateRange: DateRange, formatter: DateFormatter) -> String } @IBDesignable open class DateRangePickerView: NSControl, ExpandedDateRangePickerControllerDelegate, NSPopoverDelegate { public let segmentedControl: NSSegmentedControl public let dateFormatter = DateFormatter() fileprivate var dateRangePickerController: ExpandedDateRangePickerController? open weak var delegate: DateRangePickerViewDelegate? // MARK: - Date properties fileprivate var _dateRange: DateRange // Should almost never be accessed directly open var dateRange: DateRange { get { return _dateRange } set { var restrictedValue = newValue.restrictTo(minDate: minDate, maxDate: maxDate) restrictedValue.hourShift = self.hourShift if _dateRange != restrictedValue { self.willChangeValue(forKey: #keyPath(endDate)) self.willChangeValue(forKey: #keyPath(startDate)) _dateRange = restrictedValue self.didChangeValue(forKey: #keyPath(endDate)) self.didChangeValue(forKey: #keyPath(startDate)) if dateRangePickerController?.dateRange != dateRange { dateRangePickerController?.dateRange = dateRange } updateSegmentedControl() sendAction(action, to: target) } } } @objc open dynamic var hourShift: Int = 0 { didSet { dateRange.hourShift = hourShift dateRangePickerController?.hourShift = hourShift } } @objc open func dayChanged(_ notification: Notification) { // If the current date ranged is specified in a relative fashion, // it might change on actual day changes, so make sure to notify any observers. self.willChangeValue(forKey: #keyPath(endDate)) self.willChangeValue(forKey: #keyPath(startDate)) self.didChangeValue(forKey: #keyPath(endDate)) self.didChangeValue(forKey: #keyPath(startDate)) } // Can be used for restricting the selectable dates to a specific range. @objc open dynamic var minDate: Date? { didSet { dateRangePickerController?.minDate = minDate // Enforces the new date range restriction dateRange = _dateRange updateSegmentedControl() } } @objc open dynamic var maxDate: Date? { didSet { dateRangePickerController?.maxDate = maxDate // Enforces the new date range restriction dateRange = _dateRange updateSegmentedControl() } } @available(*, deprecated, message: "Use .dateFormatter directly instead") open var dateStyle: DateFormatter.Style { get { return dateFormatter.dateStyle } set { dateFormatter.dateStyle = newValue updateSegmentedControl() } } @objc open var dateRangeString: String { if let delegate = delegate as? DateRangePickerViewDelegateSwiftOnly { return delegate.dateRangePickerView(self, descriptionFor: dateRange, formatter: dateFormatter) } return dateRange.dateRangeDescription(withFormatter: dateFormatter) } // MARK: - Objective-C interoperability @objc open dynamic var startDate: Date { get { return dateRange.startDate } set { dateRange = DateRange.custom(newValue, endDate, hourShift: self.hourShift) } } @objc open dynamic var endDate: Date { get { return dateRange.endDate } set { dateRange = DateRange.custom(startDate, newValue, hourShift: self.hourShift) } } open override var isEnabled: Bool { get { return segmentedControl.isEnabled } set { segmentedControl.isEnabled = newValue } } private var _touchBarItem: NSObject? // A touch bar item representing this date picker, with a popover menu to select different date ranges. @available(OSX 10.12.2, *) open var touchBarItem: NSPopoverTouchBarItem { get { if _touchBarItem == nil { _touchBarItem = makeTouchBarItem() } return _touchBarItem as! NSPopoverTouchBarItem } } // The date ranges available from the touch bar item popover. // Needs to be set before touchBarItem is accessed. open var popoverItemDateRanges: [DateRange?] { return [ .pastDays(7, hourShift: self.hourShift), .pastDays(15, hourShift: self.hourShift), .pastDays(30, hourShift: self.hourShift), nil, .calendarUnit(0, .day, hourShift: self.hourShift), .calendarUnit(-1, .day, hourShift: self.hourShift), nil, .calendarUnit(0, .weekOfYear, hourShift: self.hourShift), .calendarUnit(0, .month, hourShift: self.hourShift), .calendarUnit(0, .year, hourShift: self.hourShift) ] } // The segmented control used by the touch bar item. open fileprivate(set) var touchBarSegment: NSSegmentedControl? open func setStartDate(_ startDate: Date, endDate: Date) { dateRange = .custom(startDate, endDate, hourShift: self.hourShift) } @IBAction open func selectToday(_ sender: AnyObject?) { self.dateRange = DateRange.calendarUnit(0, .day, hourShift: self.hourShift) } // In Objective-C, the DateRange type isn't available. In order to still persist the picker's // date range (e.g. between launches), you can use these functions instead. open func dateRangeAsData() -> Data { return dateRange.toData() as Data } open func loadDateRangeFromData(_ data: Data) { guard let newRange = DateRange.from(data: data) else { return } dateRange = newRange } // MARK: - Other properties @objc open var segmentStyle: NSSegmentedControl.Style { get { return segmentedControl.segmentStyle } set { segmentedControl.segmentStyle = newValue } } @objc open override var controlSize: NSControl.ControlSize { get { return segmentedControl.controlSize } set { segmentedControl.controlSize = newValue } } // If true, segmented control's height will be fixed and its vertical offset adjusted // to hopefully align it with other buttons in the toolbar. @IBInspectable open var optimizeForToolbarDisplay: Bool = false // MARK: - Methods open func makePopover() -> NSPopover { let popover = NSPopover() popover.behavior = .transient return popover } open func displayExpandedDatePicker() { if dateRangePickerController != nil { return } let popover = makePopover() let controller = ExpandedDateRangePickerController(dateRange: dateRange, hourShift: hourShift) controller.minDate = minDate controller.maxDate = maxDate controller.delegate = self self.dateRangePickerController = controller delegate?.dateRangePickerView(self, willPresentExpandedDateRangePickerController: controller) popover.contentViewController = dateRangePickerController popover.delegate = self popover.show(relativeTo: self.bounds, of: self, preferredEdge: .minY) updateSegmentedControl() } // MARK: - Initializers fileprivate func sharedInit() { segmentedControl.segmentCount = 3 if #available(OSX 11.0, *) { segmentedControl.setImage( NSImage(systemSymbolName: "chevron.left", accessibilityDescription: NSLocalizedString("Previous", bundle: getBundle(), comment: "Accessibility label for the button to go back in time.")), forSegment: 0) segmentedControl.setImage( NSImage(systemSymbolName: "chevron.right", accessibilityDescription: NSLocalizedString("Next", bundle: getBundle(), comment: "Accessibility label for the button to go forward in time.")), forSegment: 2) } else { segmentedControl.setLabel("◀", forSegment: 0) segmentedControl.setLabel("▶", forSegment: 2) } segmentedControl.action = #selector(segmentDidChange(_:)) segmentedControl.autoresizingMask = NSView.AutoresizingMask() segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.target = self self.addSubview(segmentedControl) if #available(OSX 10.15, *) { // Auto Layout might also work on macOS 10.14, but we currently don't have a system to test that on, // so we err on the side of caution. self.addConstraints(NSLayoutConstraint.constraints( // Add 1pt horizontal padding to avoid clipping the segmented control. withVisualFormat: "H:|-1-[segmentedControl]-1-|", options: [], metrics: nil, views: ["segmentedControl": segmentedControl])) self.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[segmentedControl]|", options: [], metrics: nil, views: ["segmentedControl": segmentedControl])) } self.dateFormatter.dateStyle = .medium NotificationCenter.default.addObserver(self, selector: #selector(dayChanged(_:)), name: NSNotification.Name.NSCalendarDayChanged, object: nil) // Required to display the proper title from the beginning, even if .dateRange is not changed before displaying // the control. updateSegmentedControl() updateSegmentedControlFrame() } override public init(frame frameRect: NSRect) { segmentedControl = NSSegmentedControl() _dateRange = .pastDays(7, hourShift: 0) super.init(frame: frameRect) sharedInit() } required public init?(coder: NSCoder) { segmentedControl = NSSegmentedControl() _dateRange = .pastDays(7, hourShift: 0) super.init(coder: coder) sharedInit() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - NSControl // Without this, the control's target and action are not being set on Mavericks. // (See http://stackoverflow.com/questions/3889043/nscontrol-subclass-cant-read-the-target) override open class var cellClass: AnyClass? { get { return NSActionCell.self } set { } } open func updateSegmentedControlFrame() { let sideButtonWidth: CGFloat = 22 if #available(OSX 10.15, *) { segmentedControl.setWidth(sideButtonWidth, forSegment: 0) segmentedControl.setWidth(sideButtonWidth, forSegment: 2) // On newer platforms, Auto Layout does the rest for us. return } // Magic number to avoid the segmented control overflowing out of its bounds. let unusedControlWidth: CGFloat = 8 segmentedControl.setWidth(sideButtonWidth, forSegment: 0) segmentedControl.setWidth(self.bounds.size.width - 2 * sideButtonWidth - unusedControlWidth, forSegment: 1) segmentedControl.setWidth(sideButtonWidth, forSegment: 2) // It would be nice to use Auto Layout instead, but that doesn't play nicely with views in a toolbar pre-macOS 10.15. var segmentedControlFrame = self.bounds // Ensure that the segmented control is large enough to not be clipped. if optimizeForToolbarDisplay { segmentedControlFrame.size.height = 25 if self.window?.screen?.backingScaleFactor == 2 { segmentedControlFrame.origin.y = -0.5 } } segmentedControl.frame = segmentedControlFrame } // MARK: - Internal override open func resizeSubviews(withOldSize size: CGSize) { updateSegmentedControlFrame() super.resizeSubviews(withOldSize: size) } @objc func segmentDidChange(_ sender: NSSegmentedControl) { switch sender.selectedSegment { case 0: dateRange = dateRange.previous() case 1: if NSEvent.modifierFlags.contains(.option) { // Make option-clicking the main element immediately switch to "Today". selectToday(sender) } else { displayExpandedDatePicker() } case 2: dateRange = dateRange.next() default: break } } open func updateSegmentedControl() { let dateRangeString = self.dateRangeString segmentedControl.setLabel(dateRangeString, forSegment: 1) touchBarSegment?.setLabel(dateRangeString, forSegment: 1) // Only enable the previous/next buttons if they do not touch outside the date restrictions range already. let previousAllowed = minDate != nil ? dateRange.startDate != minDate?.drp_beginning(ofCalendarUnit: .day) : true segmentedControl.setEnabled(previousAllowed, forSegment: 0) touchBarSegment?.setEnabled(previousAllowed, forSegment: 0) let nextAllowed = maxDate != nil ? dateRange.endDate != maxDate?.drp_end(ofCalendarUnit: .day) : true segmentedControl.setEnabled(nextAllowed, forSegment: 2) touchBarSegment?.setEnabled(nextAllowed, forSegment: 2) // Display the middle segment as selected while the expanded date range popover is being shown. (segmentedControl.cell as? NSSegmentedCell)?.trackingMode = dateRangePickerController != nil ? .selectOne : .momentary segmentedControl.selectedSegment = dateRangePickerController != nil ? 1 : -1 } // MARK: - ExpandedDateRangePickerControllerDelegate open func expandedDateRangePickerControllerDidChangeDateRange(_ controller: ExpandedDateRangePickerController) { if controller === dateRangePickerController { self.dateRange = controller.dateRange } } // MARK: - NSPopoverDelegate @objc open func popoverWillClose(_ notification: Notification) { guard let popover = notification.object as? NSPopover else { return } if popover.contentViewController === dateRangePickerController { dateRangePickerController = nil updateSegmentedControl() delegate?.dateRangePickerViewDidCloseExpandedDateRangePickerController(self) } } override open func viewDidChangeBackingProperties() { super.viewDidChangeBackingProperties() updateSegmentedControlFrame() } } @available(OSX 10.12.2, *) extension DateRangePickerView: NSTouchBarDelegate { public static let touchBarItemIdentifier = NSTouchBarItem.Identifier("de.danielalm.DateRangePicker.DateRangePickerViewTouchBarItem") private static let popoverItemIdentifierPrefix = "de.danielalm.DateRangePicker.DateRangePickerViewPopoverTouchBar." fileprivate func makeTouchBarItem() -> NSTouchBarItem { let segment = NSSegmentedControl(labels: ["", "", ""], trackingMode: .momentary, target: self, action: #selector(DateRangePickerView.touchBarSegmentPressed(_:))) segment.setImage(NSImage(named: NSImage.touchBarGoBackTemplateName)!, forSegment: 0) segment.setImage(NSImage(named: NSImage.touchBarGoForwardTemplateName)!, forSegment: 2) segment.setWidth(30, forSegment: 0) segment.setWidth(250, forSegment: 1) segment.setWidth(30, forSegment: 2) self.touchBarSegment = segment touchBarSegment?.segmentStyle = .separated updateSegmentedControl() let item = NSPopoverTouchBarItem(identifier: DateRangePickerView.touchBarItemIdentifier) item.collapsedRepresentation = segment item.customizationLabel = NSLocalizedString("Date Range", bundle: getBundle(), comment: "Customization label for the Date Range picker.") item.popoverTouchBar.defaultItemIdentifiers = popoverItemDateRanges.map { guard let dateRange = $0 else { return .flexibleSpace } // This does create very ugly identifiers, but they are sufficient for our use case. return NSTouchBarItem.Identifier(DateRangePickerView.popoverItemIdentifierPrefix + String(describing: dateRange)) } item.popoverTouchBar.delegate = self return item } @objc func touchBarSegmentPressed(_ sender: NSSegmentedControl) { switch sender.selectedSegment { case 0: dateRange = dateRange.previous() case 1: touchBarItem.showPopover(sender) case 2: dateRange = dateRange.next() default: break } } public func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? { if identifier.rawValue.hasPrefix(DateRangePickerView.popoverItemIdentifierPrefix) { let identifierSuffix = identifier.rawValue[DateRangePickerView.popoverItemIdentifierPrefix.endIndex...] // Not very efficient, but more than fast enough for our purposes. guard let (itemIndex, dateRange) = (popoverItemDateRanges .enumerated() .first { guard let dateRange = $0.1 else { return false } return String(describing: dateRange) == identifierSuffix }), let dateRangeTitle = dateRange?.shortTitle else { return nil } let button = NSButton(title: dateRangeTitle, target: self, action: #selector(DateRangePickerView.popoverItemPressed(_:))) button.tag = itemIndex let item = NSCustomTouchBarItem(identifier: identifier) item.view = button return item } return nil } @objc func popoverItemPressed(_ sender: NSButton) { guard sender.tag >= 0 && sender.tag < popoverItemDateRanges.count, let dateRange = popoverItemDateRanges[sender.tag] else { return } self.dateRange = dateRange touchBarItem.dismissPopover(sender) } }
isc
e5697817deb5ed010ea9c9683bf79787
34.61242
144
0.751969
4.216785
false
false
false
false
LawrenceHan/iOS-project-playground
Homepwner_swift/Homepwner/AppDelegate.swift
1
2245
// // Copyright © 2015 Big Nerd Ranch // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let itemStore = ItemStore() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let imageStore = ImageStore() let navController = window!.rootViewController as! UINavigationController let itemsController = navController.topViewController as! ItemsViewController itemsController.itemStore = itemStore itemsController.imageStore = imageStore return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { let success = itemStore.saveChanges() if (success) { print("Saved all of the Items") } else { print("Could not save any of the Items") } } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
308a6b1d234fa83c8053b8decc1d96a2
39.8
285
0.716132
5.73913
false
false
false
false
powerytg/Accented
Accented/Core/API/Requests/FollowUserRequest.swift
1
1454
// // FollowUserRequest.swift // Accented // // Request to follow usere // // Created by Tiangong You on 9/10/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class FollowUserRequest: APIRequest { private var userId : String init(userId : String, success : SuccessAction?, failure : FailureAction?) { self.userId = userId super.init(success: success, failure: failure) ignoreCache = true url = "\(APIRequest.baseUrl)users/\(userId)/friends" } override func handleSuccess(data: Data, response: HTTPURLResponse?) { super.handleSuccess(data: data, response: response) let userInfo : [String : Any] = [RequestParameters.userId : userId, RequestParameters.response : data] NotificationCenter.default.post(name: APIEvents.didFollowUser, object: nil, userInfo: userInfo) if let success = successAction { success() } } override func handleFailure(_ error: Error) { super.handleFailure(error) let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription] NotificationCenter.default.post(name: APIEvents.failedFollowUser, object: nil, userInfo: userInfo) if let failure = failureAction { failure(error.localizedDescription) } } }
mit
8f5e20c7d86f4b08e3502bf2bb88e3e1
30.586957
106
0.624914
4.748366
false
false
false
false
xedin/swift
stdlib/public/Darwin/Accelerate/vImage_Error.swift
2
4063
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // vImage_Error // //===----------------------------------------------------------------------===// @available(iOS 9999, OSX 9999, tvOS 9999, watchOS 9999, *) extension vImage { /// Error codes returned by vImage operations. public enum Error: Int, Swift.Error { /// The vImage function completed without error. case noError = 0 // The region of interest, as specified by the `srcOffsetToROI_X` and // `srcOffsetToROI_Y` parameters and the height and width of the destination // buffer, extends beyond the bottom edge or right edge of the source buffer. case roiLargerThanInputBuffer = -21766 /// Either the kernel height, the kernel width, or both, are even. case invalidKernelSize = -21767 /// The edge style specified is invalid. case invalidEdgeStyle = -21768 /// The `srcOffsetToROI_X` parameter that specifies the left edge of /// the region of interest is greater than the width of the source image. case invalidOffset_X = -21769 /// The `srcOffsetToROI_X` parameter that specifies the left edge of /// the region of interest is greater than the height of the source image. case invalidOffset_Y = -21770 /// An attempt to allocate memory failed. case memoryAllocationError = -21771 /// A pointer parameter is NULL and it must not be. case nullPointerArgument = -21772 /// Invalid parameter. case invalidParameter = -21773 /// The function requires the source and destination buffers to have /// the same height and the same width, but they do not. case bufferSizeMismatch = -21774 /// The flag is not recognized. case unknownFlagsBit = -21775 /// A serious error occured inside vImage, which prevented vImage /// from continuing. case internalError = -21776 /// The vImage_Buffer.rowBytes field is invalid. case invalidRowBytes = -21777 /// a `vImage_CGImageFormat` or `vImageCVImageFormatRef` contains /// an invalid format. case invalidImageFormat = -21778 /// ColorSync.framework is completely missing. case colorSyncIsAbsent = -21779 /// The source images and destination images may not alias the same image data. case outOfPlaceOperationRequired = -21780 /// An invalid `CGImageRef` or `CVPixelBufferRef` was passed to the function. case invalidImageObject = -21781 /// A `vImageCVImageFormatRef` contains an invalid format. case invalidCVImageFormat = -21782 /// Some lower level conversion APIs only support conversion among a /// sparse matrix of image formats. case unsupportedConversion = -21783 /// Core Video is absent. case coreVideoIsAbsent = -21784 public init(vImageError: vImage_Error) { self = Error(rawValue: vImageError) ?? .internalError } } }
apache-2.0
069a3e6d9ab8293dfd5f018ecb5d6443
40.886598
87
0.535565
5.339028
false
false
false
false
keyeMyria/edx-app-ios
Source/DownloadProgressViewController.swift
4
1919
// // DownloadProgressViewController.swift // edX // // Created by Akiva Leffert on 6/3/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public protocol DownloadProgressViewControllerDelegate : class { func downloadProgressControllerChoseShowDownloads(controller : DownloadProgressViewController) } public class DownloadProgressViewController : ViewTopMessageController { public class Environment { private let interface : OEXInterface? private let reachability : Reachability private let styles : OEXStyles public init(interface : OEXInterface?, reachability : Reachability = InternetReachability(), styles : OEXStyles) { self.interface = interface self.reachability = reachability self.styles = styles } } var delegate : DownloadProgressViewControllerDelegate? public init(environment : Environment) { let messageView = CourseOutlineHeaderView(frame: CGRectZero, styles: environment.styles, titleText: OEXLocalizedString("VIDEO_DOWNLOADS_IN_PROGRESS", nil), subtitleText: nil, shouldShowSpinner: true) super.init(messageView : messageView, active : { let progress = environment.interface?.totalProgress ?? 0 return progress != 0 && progress != 1 && environment.reachability.isReachable() }) messageView.setViewButtonAction {[weak self] _ in self.map { $0.delegate?.downloadProgressControllerChoseShowDownloads($0) } } for notification in [OEXDownloadProgressChangedNotification, OEXDownloadEndedNotification, kReachabilityChangedNotification] { NSNotificationCenter.defaultCenter().oex_addObserver(self, name: notification) { (_, observer, _) -> Void in observer.updateAnimated() } } } }
apache-2.0
086a17e146d62d62b287ecc90de830ea
36.647059
207
0.676394
5.644118
false
false
false
false
MaTriXy/androidtool-mac
AndroidTool/UITweaker.swift
1
5496
// // UITweaker.swift // AndroidTool // // Created by Morten Just Petersen on 11/16/15. // Copyright © 2015 Morten Just Petersen. All rights reserved. // import Cocoa protocol UITweakerDelegate { func UITweakerStatusChanged(status: String) } class UITweaker: NSObject { var adbIdentifier:String! var delegate:UITweakerDelegate? init(adbIdentifier:String){ self.adbIdentifier = adbIdentifier; } struct Tweak { var command:String! var description:String! } func start(callback:()->Void){ var cmdString = "" for tweak in collectAllTweaks() { cmdString = "\(tweak.command)~\(cmdString)" } ShellTasker(scriptFile: "setDemoModeOptions").run(arguments: [self.adbIdentifier, cmdString], isUserScript: false, isIOS: false) { (output) -> Void in // print("Done executing \(cmdString)") print(output) callback() } } func collectAllTweaks() -> [Tweak] { let ud = NSUserDefaults.standardUserDefaults() var tweaks = [Tweak]() for prop in C.tweakProperties { switch prop { case "airplane", "nosim", "carriernetworkchange": // network showhide let cmd = "network" var show = "hide" if ud.boolForKey(prop) { show = "show" } let tweak = Tweak(command: "\(cmd) -e \(prop) \(show)", description: "\(show) \(prop)") tweaks.append(tweak) break case "location", "alarm", "sync", "tty", "eri", "mute", "speakerphone": // status showhide let cmd = "status" var show = "hide" if ud.boolForKey(prop) { show = "show" } let tweak = Tweak(command: "\(cmd) -e \(prop) \(show)", description: "\(show) \(prop)") tweaks.append(tweak) break case "bluetooth": var show = "hide" if ud.boolForKey("bluetooth") { show = "connected" } let tweak = Tweak(command: "status -e bluetooth \(show)", description: "Tweaking Bluetooth") tweaks.append(tweak) break case "notifications": var visible = "false" if ud.boolForKey(prop) { visible = "true" } let tweak = Tweak(command: "\(prop) -e visible \(visible)", description: "Tweaking notfications") tweaks.append(tweak) break case "clock": if ud.boolForKey(prop) { let hhmm = formatTime(ud.stringForKey("timeValue")!) let tweak = Tweak(command: "clock -e hhmm \(hhmm)", description: "Setting time to \(ud.stringForKey("timeValue"))") tweaks.append(tweak) } break case "wifi": var show = "hide" var level = "" if ud.boolForKey("wifi") { show = "show" level = " -e level 4" } let tweak = Tweak(command: "network -e \(prop) \(show) \(level)", description: "\(show) \(prop)") tweaks.append(tweak) break case "mobile": var tweak:Tweak! if ud.boolForKey(prop){ let mobileDatatype = ud.stringForKey("mobileDatatype") let mobileLevel = ud.stringForKey("mobileLevel")!.stringByReplacingOccurrencesOfString(" bars", withString: "").stringByReplacingOccurrencesOfString(" bar", withString: "") tweak = Tweak(command: "network -e mobile show -e datatype \(mobileDatatype) -e level \(mobileLevel)", description: "Turn cell icon on") } else { tweak = Tweak(command: "network -e mobile hide", description: "Turn cell icon off") } tweaks.append(tweak) break case "batteryCharging": var showCharging = "false" var description = "Set battery not charging" let batLevel = ud.stringForKey("batteryLevel")?.stringByReplacingOccurrencesOfString("%", withString: "") if ud.boolForKey("batteryCharging") { showCharging = "true" description = "Set battery charging" } let tweak = Tweak(command: "battery -e plugged \(showCharging) -e level \(batLevel!)", description: description) tweaks.append(tweak) break default: break } } return tweaks } func formatTime(t:String) -> String { // remove : in hh:mm return t.stringByReplacingOccurrencesOfString(":", withString: "") } func end(){ ShellTasker(scriptFile: "exitDemoMode").run(arguments: [self.adbIdentifier], isUserScript: false, isIOS: false) { (output) -> Void in ///aaaaand done } } }
apache-2.0
7d215cb33f6cf95961c8ab17e59e5f89
39.109489
196
0.486624
5.233333
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Models/Period.swift
1
882
// // Period.swift // macWebretail // // Created by Gerardo Grisolini on 19/06/17. // Copyright © 2017 Gerardo Grisolini. All rights reserved. // class Period: Codable { public var start : Int = 0 public var finish : Int = 0 private enum CodingKeys: String, CodingKey { case start case finish } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) start = try container.decode(String.self, forKey: .start).DateToInt() finish = try container.decode(String.self, forKey: .finish).DateToInt() } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(start, forKey: .start) try container.encode(finish, forKey: .finish) } }
apache-2.0
29a74805075eb990c043a771c1c9292d
25.69697
79
0.634506
4.15566
false
false
false
false
Marquis103/RecipeFinder
RecipeFinder/RecipeTableViewControllerDelegate.swift
1
908
// // RecipeTableViewControllerDelegate.swift // RecipeFinder // // Created by Marquis Dennis on 5/8/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit class RecipeTableViewControllerDelegate: NSObject, UITableViewDelegate { let recipeAPI = RecipeAPI.sharedAPI var tableViewController = RecipeTableViewController() private var isUpdating = false func scrollViewDidScroll(scrollView: UIScrollView) { let currentOffset = scrollView.contentOffset.y let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height let deltaOffset = maximumOffset - currentOffset if deltaOffset <= 0 && !isUpdating { isUpdating = true recipeAPI.getRecipes(forFoodWithName: String.Empty, isUpdatingQuery: true) { (error) in self.isUpdating = false performUIUpdatesOnMain({ self.tableViewController.tableView.reloadData() }) } } } }
gpl-3.0
3e10b741e98e42f0c6635d5fb1bf1734
27.375
90
0.754135
4.278302
false
false
false
false