repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hmuronaka/SwiftlySalesforce
Example/Tests/MockJSONData.swift
1
884
// // MockJSONData.swift // SwiftlySalesforce // // For license & details see: https://www.github.com/mike4aday/SwiftlySalesforce // Copyright (c) 2016. All rights reserved. // import Foundation protocol MockJSONData: class { var identityJSON: Any? { get } var queryResultJSON: Any? { get } } extension MockJSONData { func read(fileName: String, ofType: String = "json") -> Any? { guard let path = Bundle(for: type(of: self)).path(forResource: fileName, ofType: ofType) else { return nil } let url = URL(fileURLWithPath: path) guard let data = try? Data(contentsOf: url), let json = try? JSONSerialization.jsonObject(with: data) else { return nil } return json } var identityJSON: Any? { return read(fileName: "IdentityResponse", ofType: "json") } var queryResultJSON: Any? { return read(fileName: "QueryResponse", ofType: "json") } }
mit
450bcdf149c925104516ae978727fd8c
22.263158
97
0.686652
3.286245
false
false
false
false
diesmal/thisorthat
ThisOrThat/Code/Modules/Units/Questionnaire/QuestionnaireViewController.swift
1
1416
// // QuestionnaireViewController.swift // ThisOrThat // // Created by Ilya Nikolaenko on 30/01/2017. // Copyright © 2017 Ilya Nikolaenko. All rights reserved. // import UIKit class QuestionnaireViewController: BaseViewController { override var assembly: Assembly? { return QuestionnaireAssembly() } var questionsVC: QuestionsViewController? var viewModel: QuestionnaireViewModel? @IBOutlet weak var notModeratedLabel: UILabel! override func bindUI() { super.bindUI() guard let questionsVM = self.questionsVC?.viewModel else { return } questionsVM.question.subscribe(self) { [unowned self] (question) in guard let moderated = question?.moderated else { self.notModeratedLabel.isHidden = true return } self.notModeratedLabel.isHidden = moderated } } @IBAction func onAddQuestion(_ sender: UIButton) { self.viewModel?.onAddQuestion() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "EmbedQuestionsSegue") { questionsVC = segue.destination as? QuestionsViewController if let questionsVC = questionsVC { self.assembly?.activate(definition: questionsVC) } } } }
apache-2.0
201474b9fe128ba98db6cdf18f91d504
26.211538
75
0.613428
4.930314
false
false
false
false
kosicki123/eidolon
KioskTests/Models/ArtworkTests.swift
1
765
import Quick import Nimble import Kiosk class ArtworkTests: QuickSpec { override func spec() { it("converts from JSON") { let id = "wah-wah" let title = "title" let date = "late 2014" let blurb = "pretty good" let artistID = "artist-1" let artistName = "Artist 1" let artistDict = ["id" : artistID, "name": artistName] let data:[String: AnyObject] = ["id":id , "title" : title, "date":date, "blurb":blurb, "artist":artistDict] let artwork = Artwork.fromJSON(data) as Artwork expect(artwork.id) == id expect(artwork.artists?.count) == 1 expect(artwork.artists?.first?.id) == artistID } } }
mit
db39202f49d40bb92bc2bbf54f72b08d
26.321429
120
0.538562
4.090909
false
false
false
false
banxi1988/Staff
Pods/BXForm/Pod/Classes/Buttons/OutlineButton.swift
1
2620
// // OutlineButton.swift // SubjectEditorDemo // // Created by Haizhen Lee on 15/6/3. // Copyright (c) 2015年 banxi1988. All rights reserved. // import UIKit public enum BXOutlineStyle:Int{ case Rounded case Oval case Semicircle } public class OutlineButton: UIButton { public init(style:BXOutlineStyle = .Rounded){ super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) outlineStyle = style } public var useTitleColorAsStrokeColor = true { didSet{ updateOutlineColor() } } public var outlineColor:UIColor?{ didSet{ updateOutlineColor() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public var outlineStyle = BXOutlineStyle.Rounded{ didSet{ updateOutlinePath() } } public var cornerRadius:CGFloat = 4.0 { didSet{ updateOutlinePath() } } public var lineWidth :CGFloat = 0.5 { didSet{ outlineLayer.lineWidth = lineWidth } } public lazy var maskLayer : CAShapeLayer = { [unowned self] in let maskLayer = CAShapeLayer() maskLayer.frame = self.frame self.layer.mask = maskLayer return maskLayer }() public lazy var outlineLayer : CAShapeLayer = { [unowned self] in let outlineLayer = CAShapeLayer() outlineLayer.frame = self.frame outlineLayer.lineWidth = self.lineWidth outlineLayer.fillColor = UIColor.clearColor().CGColor outlineLayer.strokeColor = self.currentTitleColor.CGColor self.layer.addSublayer(outlineLayer) return outlineLayer }() public override func layoutSubviews() { super.layoutSubviews() maskLayer.frame = bounds outlineLayer.frame = bounds updateOutlineColor() updateOutlinePath() } private func updateOutlinePath(){ let path:UIBezierPath switch outlineStyle{ case .Rounded: path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) case .Oval: path = UIBezierPath(ovalInRect: bounds) case .Semicircle: path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.height * 0.5) } maskLayer.path = path.CGPath outlineLayer.path = path.CGPath } private func updateOutlineColor(){ if let color = outlineColor{ outlineLayer.strokeColor = color.CGColor }else if useTitleColorAsStrokeColor{ outlineLayer.strokeColor = currentTitleColor.CGColor }else{ outlineLayer.strokeColor = tintColor.CGColor } } public override func tintColorDidChange() { super.tintColorDidChange() updateOutlineColor() } }
mit
7723ff6c569e2b043f7e496c8c4875a2
21.765217
81
0.677998
4.498282
false
false
false
false
blokadaorg/blokada
ios/App/Repository/AccountRepo.swift
1
15966
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import Combine import UIKit class AccountRepo: Startable { var accountHot: AnyPublisher<AccountWithKeypair, Never> { self.writeAccount.compactMap { $0 }.eraseToAnyPublisher() } var accountIdHot: AnyPublisher<AccountId, Never> { self.accountHot.map { it in it.account.id }.removeDuplicates().eraseToAnyPublisher() } var accountTypeHot: AnyPublisher<AccountType, Never> { self.writeAccountType.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher() } fileprivate let writeAccount = CurrentValueSubject<AccountWithKeypair?, Never>(nil) fileprivate let writeAccountType = CurrentValueSubject<AccountType?, Never>(nil) fileprivate let accountInitT = Tasker<Ignored, Bool>("accountInit") fileprivate let proposeAccountT = Tasker<Account, Bool>("proposeAccount") fileprivate let refreshAccountT = Tasker<AccountId, Account>("refreshAccount", debounce: 0.0) fileprivate let restoreAccountT = Tasker<AccountId, Account>("restoreAccount") private lazy var enteredForegroundHot = Repos.stageRepo.enteredForegroundHot private lazy var activeTabHot = Repos.navRepo.activeTabHot private lazy var local = Services.persistenceLocal private lazy var remote = Services.persistenceRemote private lazy var remoteLegacy = Services.persistenceRemoteLegacy private lazy var crypto = Services.crypto private lazy var api = Services.api private lazy var timer = Services.timer private lazy var dialog = Services.dialog private let decoder = blockaDecoder private let encoder = blockaEncoder private var cancellables = Set<AnyCancellable>() private let bgQueue = DispatchQueue(label: "AccountRepoBgQueue") private let lastAccountRequestTimestamp = Atomic<Double>(0) private let ACCOUNT_REFRESH_SEC: Double = 10 * 60 // Same as on Android func start() { onAccountInit() onProposeAccountRequests() onRefreshAccountRequests() onRestoreAccountRequests() onAccountExpiring_RefreshAccount() onAccountAboutToExpire_MarkExpiredAndInformUser() onAccountChanged_EmitAccountType() onForeground_RefreshAccountPeriodically() onSettingsTab_RefreshAccount() accountInitT.send(true) } // Gets account from API based on user entered account ID. Does sanitization. func restoreAccount(_ newAccountId: AccountId) -> AnyPublisher<Account, Error> { return restoreAccountT.send(newAccountId) } // Accepts account received from the payment callback (usually old receipt). func proposeAccount(_ newAccount: Account) -> AnyPublisher<Bool, Error> { return proposeAccountT.send(newAccount) } private func onAccountInit() { accountInitT.setTask { _ in self.loadFromPersistenceOrCreateAccount() // A delayed retry (total 3 attemps spread 1-5 sec at random) .tryCatch { error -> AnyPublisher<AccountWithKeypair, Error> in return self.loadFromPersistenceOrCreateAccount() .delay(for: DispatchQueue.SchedulerTimeType.Stride(integerLiteral: Int.random(in: 1..<5)), scheduler: self.bgQueue) .retry(2) .eraseToAnyPublisher() } .map { it in self.writeAccount.send(it) } .map { _ in true } // Show dialog and rethrow error (user have to retry) .tryCatch { err in self.dialog.showAlert( message: L10n.errorCreatingAccount, header: L10n.alertErrorHeader, okText: L10n.universalActionContinue, okAction: { self.accountInitT.send(true) } ) .tryMap { _ -> Ignored in throw err } .eraseToAnyPublisher() } .eraseToAnyPublisher() } } private func loadFromPersistenceOrCreateAccount() -> AnyPublisher<AccountWithKeypair, Error> { return Publishers.CombineLatest( self.loadAccountFromPersistence(), self.loadKeypairFromPersistence() ) .tryMap { it in try self.validateAccount(it.0, it.1) return AccountWithKeypair(account: it.0, keypair: it.1) } .tryCatch { err -> AnyPublisher<AccountWithKeypair, Error> in if err as? CommonError == CommonError.emptyResult { return self.createNewUser() } throw err } .flatMap { it in Publishers.CombineLatest( self.saveAccountToPersistence(it.account), self.saveKeypairToPersistence(it.keypair) ) .tryMap { _ in it } } .eraseToAnyPublisher() } // Receives Account object to be verified and saved. No request, but may regen keys. private func onProposeAccountRequests() { proposeAccountT.setTask { account in Just(account) .flatMap { it in Publishers.CombineLatest( Just(it), self.accountHot.first() )} .tryMap { it -> (Account, AccountWithKeypair?) in try self.validateAccountId(it.0.id) return it } .flatMap { it -> AnyPublisher<(Account, Keypair), Error> in let accountPublisher: AnyPublisher<Account, Error> = Just(it.0) .setFailureType(to: Error.self) .eraseToAnyPublisher() var keypairPublisher: AnyPublisher<Keypair, Error> = self.crypto.generateKeypair() if let acc = it.1, acc.account.id == it.0.id { // Use same keypair if account ID hasn't changed keypairPublisher = Just(acc.keypair) .setFailureType(to: Error.self) .eraseToAnyPublisher() } return Publishers.CombineLatest( accountPublisher, keypairPublisher ) .eraseToAnyPublisher() } .tryMap { it -> AccountWithKeypair in try self.validateAccount(it.0, it.1) return AccountWithKeypair(account: it.0, keypair: it.1) } .flatMap { it in Publishers.CombineLatest( self.saveAccountToPersistence(it.account), self.saveKeypairToPersistence(it.keypair) ) .tryMap { _ in it } } .tryMap { it in self.writeAccount.send(it) return true } .eraseToAnyPublisher() } } // Account ID is sanitised and validated, do the request and update Account model private func onRefreshAccountRequests() { refreshAccountT.setTask { accountId in Just(accountId) .flatMap { accountId in self.api.getAccount(id: accountId) } .tryMap { account -> Account in self.lastAccountRequestTimestamp.value = Date().timeIntervalSince1970 self.proposeAccountT.send(account) return account } .eraseToAnyPublisher() } } // Account ID is input from user, sanitize it and then forward to do the refresh private func onRestoreAccountRequests() { restoreAccountT.setTask { accountId in Just(accountId) // .removeDuplicates() .map { accountId in accountId.lowercased().trimmingCharacters(in: CharacterSet.whitespaces) } .tryMap { accountId in try self.validateAccountId(accountId) return accountId } .flatMap { accountId in self.refreshAccountT.send(accountId) } .eraseToAnyPublisher() } } // Re-check account just before it expires in case it was extended externally. // We do it to make sure we still have connectivity. private func onAccountExpiring_RefreshAccount() { accountHot.map { it in it.account } .sink(onValue: { it in let until = it.activeUntil()?.shortlyBefore() ?? Date() if until > Date() { self.timer.createTimer(NOTIF_ACC_EXP, when: until) .flatMap { _ in self.timer.obtainTimer(NOTIF_ACC_EXP) } .sink( onFailure: { err in Logger.e("AppRepo", "Acc expiration timer failed: \(err)") }, onSuccess: { Logger.v("AppRepo", "Account soon to expire, refreshing") self.refreshAccountT.send(it.id) .sink(onFailure: { err in // If cannot refresh, emit expired account manually. // We may be out of connectivity. self.proposeAccount(Account( id: it.id, active_until: nil, active: false, type: "libre" )) }) .store(in: &self.cancellables) } ) .store(in: &self.cancellables) // TODO: not sure if it's the best idea } else { self.timer.cancelTimer(NOTIF_ACC_EXP) } }) .store(in: &cancellables) } private func onAccountAboutToExpire_MarkExpiredAndInformUser() { accountHot.map { it in it.account } .filter { it in if !it.isActive() { return false } if let until = it.activeUntil(), until.shortlyBefore() < Date() { return true } else { return false } } .sink(onValue: { it in // Mark account as expired internally Logger.v( "AppRepo", "Marking account as expired, now: \(Date()), acc: \(it.activeUntil()?.shortlyBefore())" ) self.proposeAccount(Account( id: it.id, active_until: nil, active: false, type: "libre" )) // Inform user self.dialog.showAlert( message: L10n.notificationAccBody, header: L10n.notificationAccHeader ) .sink() .store(in: &self.cancellables) }) .store(in: &cancellables) } private func onAccountChanged_EmitAccountType() { accountHot.map { it in it.account.type } .map { it in mapAccountType(it) } .sink(onValue: { it in self.writeAccountType.send(it) }) .store(in: &cancellables) } // When app enters foreground, periodically refresh account private func onForeground_RefreshAccountPeriodically() { enteredForegroundHot .filter { it in self.lastAccountRequestTimestamp.value < Date().timeIntervalSince1970 - self.ACCOUNT_REFRESH_SEC } .flatMap { it in self.accountHot.first() } .sink( onValue: { it in self.lastAccountRequestTimestamp.value = Date().timeIntervalSince1970 self.refreshAccountT.send(it.account.id) } ) .store(in: &cancellables) } private func onSettingsTab_RefreshAccount() { activeTabHot .filter { it in it == .Settings } .flatMap { it in self.accountHot.first() } .sink(onValue: { it in self.refreshAccountT.send(it.account.id) }) .store(in: &cancellables) } private func createNewUser() -> AnyPublisher<AccountWithKeypair, Error> { Logger.w("Account", "Creating new user") return Publishers.CombineLatest( self.api.postNewAccount(), self.crypto.generateKeypair() ) .tryMap { it in try self.validateAccount(it.0, it.1) return AccountWithKeypair(account: it.0, keypair: it.1) } .eraseToAnyPublisher() } private func validateAccount(_ account: Account, _ keypair: Keypair) throws { try validateAccountId(account.id) if keypair.privateKey.isEmpty || keypair.publicKey.isEmpty { throw "account with empty keypair" } if Services.env.isProduction && CRYPTO_MOCKED_KEYS.contains(keypair) { Logger.w("Account", "Mocked keys detected, recreating account") throw CommonError.emptyResult } } private func validateAccountId(_ accountId: AccountId) throws { if accountId.isEmpty { throw "account with empty ID" } } private func saveAccountToPersistence(_ account: Account) -> AnyPublisher<Ignored, Error> { Just(account).encode(encoder: self.encoder) .tryMap { it -> String in guard let it = String(data: it, encoding: .utf8) else { throw "account: could not encode json data to string" } return it } .flatMap { it in return self.remote.setString(it, forKey: "account") } .eraseToAnyPublisher() } private func saveKeypairToPersistence(_ keypair: Keypair) -> AnyPublisher<Ignored, Error> { Just(keypair).encode(encoder: self.encoder) .tryMap { it -> String in guard let it = String(data: it, encoding: .utf8) else { throw "keypair: could not encode json data to string" } return it } .flatMap { it in return self.local.setString(it, forKey: "keypair") } .eraseToAnyPublisher() } private func loadAccountFromPersistence() -> AnyPublisher<Account, Error> { return remote.getString(forKey: "account").tryCatch { err -> AnyPublisher<String, Error> in // A legacy read of the account - to be removed later return self.remoteLegacy.getString(forKey: "account") } .tryMap { it -> Data in guard let it = it.data(using: .utf8) else { throw "account: failed reading persisted account data" } return it } .decode(type: Account.self, decoder: self.decoder) .eraseToAnyPublisher() } private func loadKeypairFromPersistence() -> AnyPublisher<Keypair, Error> { return local.getString(forKey: "keypair").tryMap { it -> Data in guard let it = it.data(using: .utf8) else { throw "keypair: failed reading persisted keypair data" } return it } .decode(type: Keypair.self, decoder: self.decoder) .tryCatch { err -> AnyPublisher<Keypair, Error> in // A legacy read of the keys - to be removed later return Publishers.CombineLatest( self.local.getString(forKey: "privateKey"), self.local.getString(forKey: "publicKey") ) .tryMap { it in return Keypair(privateKey: it.0, publicKey: it.1) } .eraseToAnyPublisher() } .eraseToAnyPublisher() } } class DebugAccountRepo: AccountRepo { private let log = Logger("AccRepo") private var cancellables = Set<AnyCancellable>() override init() { super.init() accountHot.sink( onValue: { it in self.log.v("Account: \(it)") } ) .store(in: &cancellables) } }
mpl-2.0
fd98977a5356dde2431d1e13d16159e3
36.301402
131
0.57814
4.761408
false
false
false
false
ColinConduff/BlocFit
BlocFit/Main Components/Side Menu/SideMenuTableDelegate.swift
1
2736
// // SideMenuTableDelegate.swift // BlocFit // // Created by Colin Conduff on 12/27/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import UIKit class SideMenuTableDelegate: NSObject, UITableViewDelegate { unowned var seguePerformer: SegueCoordinationDelegate init(segueCoordinator: SegueCoordinationDelegate) { self.seguePerformer = segueCoordinator } // Make the profile cell larger to accomodate more information func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == Cell.profile.sec && indexPath.row == Cell.profile.row { return 80 } else { return 40 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let segueIdentifier = segueIdentifier(section: indexPath.section, row: indexPath.row) { seguePerformer.transition(withSegueIdentifier: segueIdentifier) } tableView.deselectRow(at: indexPath, animated: true) } // Section and row numbers corresponding to static table cells private struct Cell { static let profile = (sec: 0, row: 0) static let friends = (sec: 1, row: 0) static let gameCenter = (sec: 1, row: 1) static let runHistory = (sec: 2, row: 0) static let statistics = (sec: 2, row: 1) static let settings = (sec: 3, row: 0) } // Return the segueIdentifier corresponding to the selected static table cell private func segueIdentifier(section: Int, row: Int) -> String? { var segueIdentifier: String? if section == Cell.friends.sec || section == Cell.gameCenter.sec { if row == Cell.friends.row { segueIdentifier = SegueIdentifier.friendTableSegue } else if row == Cell.gameCenter.row { segueIdentifier = SegueIdentifier.gameCenterSegue } } else if section == Cell.runHistory.sec || section == Cell.statistics.sec { if row == Cell.runHistory.row { segueIdentifier = SegueIdentifier.runHistoryTableSegue } else if row == Cell.statistics.row { segueIdentifier = SegueIdentifier.statisticsTableSegue } } else if section == Cell.settings.sec && row == Cell.settings.row { segueIdentifier = SegueIdentifier.settingsTableSegue } return segueIdentifier } }
mit
2c71380c2617e564f2a48cf2bd425499
32.765432
94
0.583181
5.24952
false
false
false
false
frootloops/swift
test/Generics/conditional_conformances.swift
1
16609
// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck %s -verify // RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump protocol P1 {} protocol P2 {} protocol P3 {} protocol P4: P1 {} protocol P5: P2 {} // expected-note@-1{{type 'InheritImplicitGood<T>' does not conform to inherited protocol 'P2'}} // expected-note@-2{{type 'InheritImplicitBad<T>' does not conform to inherited protocol 'P2'}} protocol P6: P2 {} // expected-note@-1{{type 'InheritImplicitBad<T>' does not conform to inherited protocol 'P2'}} protocol Assoc { associatedtype AT } func takes_P2<X: P2>(_: X) {} // FIXME: "requirement specified as..." isn't accurate below // expected-note@-2{{candidate requires that the types 'U' and 'V' be equivalent (requirement specified as 'U' == 'V')}} // expected-note@-3{{requirement from conditional conformance of 'SameTypeGeneric<U, V>' to 'P2'}} // expected-note@-4{{candidate requires that the types 'U' and 'Int' be equivalent (requirement specified as 'U' == 'Int')}} // expected-note@-5{{requirement from conditional conformance of 'SameTypeGeneric<U, Int>' to 'P2'}} // expected-note@-6{{candidate requires that the types 'Int' and 'Float' be equivalent (requirement specified as 'Int' == 'Float')}} // expected-note@-7{{requirement from conditional conformance of 'SameTypeGeneric<Int, Float>' to 'P2'}} // expected-note@-8{{candidate requires that 'C1' inherit from 'U' (requirement specified as 'U' : 'C1')}} // expected-note@-9{{requirement from conditional conformance of 'ClassFree<U>' to 'P2'}} // expected-note@-10{{candidate requires that 'C3' inherit from 'U' (requirement specified as 'U' : 'C3')}} // expected-note@-11{{requirement from conditional conformance of 'ClassMoreSpecific<U>' to 'P2'}} // expected-note@-12{{candidate requires that 'C1' inherit from 'Int' (requirement specified as 'Int' : 'C1')}} // expected-note@-13{{requirement from conditional conformance of 'SubclassBad' to 'P2'}} // expected-note@-14{{candidate requires that the types 'Float' and 'Int' be equivalent (requirement specified as 'Float' == 'Int')}} // expected-note@-15{{requirement from conditional conformance of 'Infer<Constrained<U>, V>' to 'P2'}} // expected-note@-16{{candidate requires that the types 'Constrained<U>' and 'Constrained<V>' be equivalent (requirement specified as 'Constrained<U>' == 'Constrained<V>')}} // expected-note@-17{{candidate requires that the types 'U' and 'Int' be equivalent (requirement specified as 'U' == 'Int')}} // expected-note@-18{{requirement from conditional conformance of 'SameType<Float>' to 'P2'}} // expected-note@-19{{requirement from conditional conformance of 'SameType<U>' to 'P2'}} func takes_P5<X: P5>(_: X) {} struct Free<T> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=Free<T> // CHECK-NEXT: (normal_conformance type=Free<T> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P1) extension Free: P2 where T: P1 {} func free_good<U: P1>(_: U) { takes_P2(Free<U>()) } func free_bad<U>(_: U) { takes_P2(Free<U>()) // expected-error{{type 'U' does not conform to protocol 'P1'}}}} // expected-error@-1{{'<X where X : P2> (X) -> ()' requires that 'U' conform to 'P1'}} // expected-note@-2{{requirement specified as 'U' : 'P1'}} // expected-note@-3{{requirement from conditional conformance of 'Free<U>' to 'P2'}} } struct Constrained<T: P1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=Constrained<T> // CHECK-NEXT: (normal_conformance type=Constrained<T> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P3) extension Constrained: P2 where T: P3 {} func constrained_good<U: P1 & P3>(_: U) { takes_P2(Constrained<U>()) } func constrained_bad<U: P1>(_: U) { takes_P2(Constrained<U>()) // expected-error{{type 'U' does not conform to protocol 'P3'}} // expected-error@-1{{'<X where X : P2> (X) -> ()' requires that 'U' conform to 'P3'}} // expected-note@-2{{requirement specified as 'U' : 'P3'}} // expected-note@-3{{requirement from conditional conformance of 'Constrained<U>' to 'P2'}} } struct RedundantSame<T: P1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSame<T> // CHECK-NEXT: (normal_conformance type=RedundantSame<T> protocol=P2) extension RedundantSame: P2 where T: P1 {} struct RedundantSuper<T: P4> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSuper<T> // CHECK-NEXT: (normal_conformance type=RedundantSuper<T> protocol=P2) extension RedundantSuper: P2 where T: P1 {} struct OverlappingSub<T: P1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=OverlappingSub<T> // CHECK-NEXT: (normal_conformance type=OverlappingSub<T> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P4) extension OverlappingSub: P2 where T: P4 {} func overlapping_sub_good<U: P4>(_: U) { takes_P2(OverlappingSub<U>()) } func overlapping_sub_bad<U: P1>(_: U) { takes_P2(OverlappingSub<U>()) // expected-error{{type 'U' does not conform to protocol 'P4'}} // expected-error@-1{{'<X where X : P2> (X) -> ()' requires that 'U' conform to 'P4'}} // expected-note@-2{{requirement specified as 'U' : 'P4'}} // expected-note@-3{{requirement from conditional conformance of 'OverlappingSub<U>' to 'P2'}} } struct SameType<T> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=SameType<Int> // CHECK-NEXT: (normal_conformance type=SameType<T> protocol=P2 // CHECK-NEXT: same_type: τ_0_0 Int) extension SameType: P2 where T == Int {} func same_type_good() { takes_P2(SameType<Int>()) } func same_type_bad<U>(_: U) { takes_P2(SameType<U>()) // expected-error{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SameType<U>)'}} takes_P2(SameType<Float>()) // expected-error{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SameType<Float>)'}} } struct SameTypeGeneric<T, U> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=SameTypeGeneric<T, T> // CHECK-NEXT: (normal_conformance type=SameTypeGeneric<T, U> protocol=P2 // CHECK-NEXT: same_type: τ_0_0 τ_0_1) extension SameTypeGeneric: P2 where T == U {} func same_type_generic_good<U, V>(_: U, _: V) where U: Assoc, V: Assoc, U.AT == V.AT { takes_P2(SameTypeGeneric<Int, Int>()) takes_P2(SameTypeGeneric<U, U>()) takes_P2(SameTypeGeneric<U.AT, V.AT>()) } func same_type_bad<U, V>(_: U, _: V) { takes_P2(SameTypeGeneric<U, V>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SameTypeGeneric<U, V>)'}} takes_P2(SameTypeGeneric<U, Int>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SameTypeGeneric<U, Int>)'}} takes_P2(SameTypeGeneric<Int, Float>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SameTypeGeneric<Int, Float>)'}} } struct Infer<T, U> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=Infer<Constrained<U>, U> // CHECK-NEXT: (normal_conformance type=Infer<T, U> protocol=P2 // CHECK-NEXT: same_type: τ_0_0 Constrained<τ_0_1> // CHECK-NEXT: conforms_to: τ_0_1 P1) extension Infer: P2 where T == Constrained<U> {} func infer_good<U: P1>(_: U) { takes_P2(Infer<Constrained<U>, U>()) } func infer_bad<U: P1, V>(_: U, _: V) { takes_P2(Infer<Constrained<U>, V>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(Infer<Constrained<U>, V>)'}} takes_P2(Infer<Constrained<V>, V>()) // expected-error@-1{{type 'V' does not conform to protocol 'P1'}} } struct InferRedundant<T, U: P1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=InferRedundant<Constrained<U>, U> // CHECK-NEXT: (normal_conformance type=InferRedundant<T, U> protocol=P2 // CHECK-NEXT: same_type: τ_0_0 Constrained<τ_0_1>) extension InferRedundant: P2 where T == Constrained<U> {} func infer_redundant_good<U: P1>(_: U) { takes_P2(InferRedundant<Constrained<U>, U>()) } func infer_redundant_bad<U: P1, V>(_: U, _: V) { takes_P2(InferRedundant<Constrained<U>, V>()) // expected-error@-1{{type 'V' does not conform to protocol 'P1'}} takes_P2(InferRedundant<Constrained<V>, V>()) // expected-error@-1{{type 'V' does not conform to protocol 'P1'}} } class C1 {} class C2: C1 {} class C3: C2 {} struct ClassFree<T> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassFree<T> // CHECK-NEXT: (normal_conformance type=ClassFree<T> protocol=P2 // CHECK-NEXT: superclass: τ_0_0 C1) extension ClassFree: P2 where T: C1 {} func class_free_good<U: C1>(_: U) { takes_P2(ClassFree<U>()) } func class_free_bad<U>(_: U) { takes_P2(ClassFree<U>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(ClassFree<U>)'}} } struct ClassMoreSpecific<T: C1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassMoreSpecific<T> // CHECK-NEXT: (normal_conformance type=ClassMoreSpecific<T> protocol=P2 // CHECK-NEXT: superclass: τ_0_0 C3) extension ClassMoreSpecific: P2 where T: C3 {} func class_more_specific_good<U: C3>(_: U) { takes_P2(ClassMoreSpecific<U>()) } func class_more_specific_bad<U: C1>(_: U) { takes_P2(ClassMoreSpecific<U>()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(ClassMoreSpecific<U>)'}} } struct ClassLessSpecific<T: C3> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassLessSpecific<T> // CHECK-NEXT: (normal_conformance type=ClassLessSpecific<T> protocol=P2) extension ClassLessSpecific: P2 where T: C1 {} // Inherited conformances: class Base<T> {} extension Base: P2 where T: C1 {} class SubclassGood: Base<C1> {} func subclass_good() { takes_P2(SubclassGood()) } class SubclassBad: Base<Int> {} func subclass_bad() { takes_P2(SubclassBad()) // expected-error@-1{{cannot invoke 'takes_P2(_:)' with an argument list of type '(SubclassBad)'}} } // Inheriting conformances: struct InheritEqual<T> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual<T> // CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P1) extension InheritEqual: P2 where T: P1 {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual<T> // CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P5 // CHECK-NEXT: conforms_to: τ_0_0 P1) extension InheritEqual: P5 where T: P1 {} func inheritequal_good<U: P1>(_: U) { takes_P2(InheritEqual<U>()) takes_P5(InheritEqual<U>()) } func inheritequal_bad<U>(_: U) { takes_P2(InheritEqual<U>()) // expected-error{{type 'U' does not conform to protocol 'P1'}} // expected-error@-1{{'<X where X : P2> (X) -> ()' requires that 'U' conform to 'P1'}} // expected-note@-2{{requirement specified as 'U' : 'P1'}} // expected-note@-3{{requirement from conditional conformance of 'InheritEqual<U>' to 'P2'}} takes_P5(InheritEqual<U>()) // expected-error{{type 'U' does not conform to protocol 'P1'}} // expected-error@-1{{'<X where X : P5> (X) -> ()' requires that 'U' conform to 'P1'}} // expected-note@-2{{requirement specified as 'U' : 'P1'}} // expected-note@-3{{requirement from conditional conformance of 'InheritEqual<U>' to 'P5'}} } struct InheritLess<T> {} extension InheritLess: P2 where T: P1 {} extension InheritLess: P5 {} // expected-error{{type 'T' does not conform to protocol 'P1'}} // expected-error@-1{{'P5' requires that 'T' conform to 'P1'}} // expected-note@-2{{requirement specified as 'T' : 'P1'}} // expected-note@-3{{requirement from conditional conformance of 'InheritLess<T>' to 'P2'}} struct InheritMore<T> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore<T> // CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P1) extension InheritMore: P2 where T: P1 {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore<T> // CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P5 // CHECK-NEXT: conforms_to: τ_0_0 P4) extension InheritMore: P5 where T: P4 {} func inheritequal_good_good<U: P4>(_: U) { takes_P2(InheritMore<U>()) takes_P5(InheritMore<U>()) } func inheritequal_good_bad<U: P1>(_: U) { takes_P2(InheritMore<U>()) takes_P5(InheritMore<U>()) // expected-error{{type 'U' does not conform to protocol 'P4'}} // expected-error@-1{{'<X where X : P5> (X) -> ()' requires that 'U' conform to 'P4'}} // expected-note@-2{{requirement specified as 'U' : 'P4'}} // expected-note@-3{{requirement from conditional conformance of 'InheritMore<U>' to 'P5'}} } func inheritequal_bad_bad<U>(_: U) { takes_P2(InheritMore<U>()) // expected-error{{type 'U' does not conform to protocol 'P1'}} // expected-error@-1{{'<X where X : P2> (X) -> ()' requires that 'U' conform to 'P1'}} // expected-note@-2{{requirement specified as 'U' : 'P1'}} // expected-note@-3{{requirement from conditional conformance of 'InheritMore<U>' to 'P2'}} takes_P5(InheritMore<U>()) // expected-error{{type 'U' does not conform to protocol 'P4'}} // expected-error@-1{{'<X where X : P5> (X) -> ()' requires that 'U' conform to 'P4'}} // expected-note@-2{{requirement specified as 'U' : 'P4'}} // expected-note@-3{{requirement from conditional conformance of 'InheritMore<U>' to 'P5'}} } struct InheritImplicitGood<T> {} // FIXME: per SE-0143, this should result in an implicit conformance // InheritImplicitGood: P2. extension InheritImplicitGood: P5 where T: P1 {} // expected-error@-1{{type 'InheritImplicitGood<T>' does not conform to protocol 'P2'}} struct InheritImplicitBad<T> {} // This shouldn't give anything implicit since either conformance could imply // InheritImplicitBad: P2. extension InheritImplicitBad: P5 where T: P1 {} // expected-error@-1{{type 'InheritImplicitBad<T>' does not conform to protocol 'P2'}} extension InheritImplicitBad: P6 where T: P1 {} // expected-error@-1{{type 'InheritImplicitBad<T>' does not conform to protocol 'P2'}} // "Multiple conformances" from SE0143 struct TwoConformances<T> {} extension TwoConformances: P2 where T: P1 {} // expected-error@-1{{redundant conformance of 'TwoConformances<T>' to protocol 'P2'}} extension TwoConformances: P2 where T: P3 {} // expected-note@-1{{'TwoConformances<T>' declares conformance to protocol 'P2' here}} struct TwoDisjointConformances<T> {} extension TwoDisjointConformances: P2 where T == Int {} // expected-error@-1{{redundant conformance of 'TwoDisjointConformances<T>' to protocol 'P2'}} extension TwoDisjointConformances: P2 where T == String {} // expected-note@-1{{'TwoDisjointConformances<T>' declares conformance to protocol 'P2' here}} // FIXME: these cases should be equivalent (and both with the same output as the // first), but the second one choses T as the representative of the // equivalence class containing both T and U in the extension's generic // signature, meaning the stored conditional requirement is T: P1, which isn't // true in the original type's generic signature. struct RedundancyOrderDependenceGood<T: P1, U> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood<T, T> // CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceGood<T, U> protocol=P2 // CHECK-NEXT: same_type: τ_0_0 τ_0_1) extension RedundancyOrderDependenceGood: P2 where U: P1, T == U {} struct RedundancyOrderDependenceBad<T, U: P1> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad<T, T> // CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceBad<T, U> protocol=P2 // CHECK-NEXT: conforms_to: τ_0_0 P1 // CHECK-NEXT: same_type: τ_0_0 τ_0_1) extension RedundancyOrderDependenceBad: P2 where T: P1, T == U {} // Checking of conditional requirements for existential conversions. func existential_good<T: P1>(_: T.Type) { _ = Free<T>() as P2 } func existential_bad<T>(_: T.Type) { // FIXME: Poor diagnostic. _ = Free<T>() as P2 // expected-error{{'Free<T>' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} } // rdar://problem/35837054 protocol P7 { } protocol P8 { associatedtype A } struct X0 { } struct X1 { } extension X1: P8 { typealias A = X0 } struct X2<T> { } extension X2: P7 where T: P8, T.A: P7 { } func takesF7<T: P7>(_: T) { } func passesConditionallyNotF7(x21: X2<X1>) { takesF7(x21) // expected-error{{type 'X1.A' (aka 'X0') does not conform to protocol 'P7'}} // expected-error@-1{{'<T where T : P7> (T) -> ()' requires that 'X1.A' (aka 'X0') conform to 'P7'}} // expected-note@-2{{requirement specified as 'X1.A' (aka 'X0') : 'P7'}} // expected-note@-3{{requirement from conditional conformance of 'X2<X1>' to 'P7'}} }
apache-2.0
45ed98c3014b1f8625a9ae94d614412e
44.820442
173
0.683125
3.271598
false
false
false
false
siuying/SignalKit
SignalKit/UIKit/UITextViewFunctions.swift
1
1556
// // UITextViewFunctions.swift // SignalKit // // Created by Yanko Dimitrov on 7/15/15. // Copyright (c) 2015 Yanko Dimitrov. All rights reserved. // import UIKit /** Observe the text in UITextView */ public func observe(textIn textView: UITextView) -> Signal<String> { let notificationSignal = observe(UITextViewTextDidChangeNotification, fromObject: textView) let signal = notificationSignal.map { [weak textView] _ in textView?.text ?? "" } signal.dispatch(textView.text ?? "") return signal } /** Observe the attributed text in UITextView */ public func observe(attributedTextIn textView: UITextView) -> Signal<NSAttributedString> { let notificationSignal = observe(UITextViewTextDidChangeNotification, fromObject: textView) let signal = notificationSignal.map { [weak textView] _ in textView?.attributedText ?? NSAttributedString(string: "") } signal.dispatch(textView.attributedText ?? NSAttributedString(string: "")) return signal } /** Bind a String value to the text property of UITextView */ public func textIn(textView: UITextView) -> String -> Void { return { [weak textView] text in textView?.text = text } } /** Bind a NSAttributedString to the attributedText property of UITextView */ public func attributedTextIn(textView: UITextView) -> NSAttributedString -> Void { return { [weak textView] text in textView?.attributedText = text } }
mit
ce62cbee8ff39e6b0eb4682f9bc1806d
21.550725
95
0.663239
4.8625
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Breadcrumbs/Breadcrumbs-5/Breadcrumbs/ViewController.swift
4
6129
// // ViewController.swift // Breadcrumbs // // Created by Nicholas Outram on 20/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { /// The application state - "where we are in a known sequence" enum AppState { case waitingForViewDidLoad case requestingAuth case liveMapNoLogging case liveMapLogging init() { self = .waitingForViewDidLoad } } /// The type of input (and its value) applied to the state machine enum AppStateInputSource { case none case start case authorisationStatus(Bool) case userWantsToStart(Bool) } // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var startButton: UIBarButtonItem! @IBOutlet weak var stopButton: UIBarButtonItem! @IBOutlet weak var clearButton: UIBarButtonItem! @IBOutlet weak var optionsButton: UIBarButtonItem! // MARK: - Properties lazy var locationManager : CLLocationManager = { let loc = CLLocationManager() //Set up location manager with defaults loc.desiredAccuracy = kCLLocationAccuracyBest loc.distanceFilter = kCLDistanceFilterNone loc.delegate = self //Optimisation of battery loc.pausesLocationUpdatesAutomatically = true loc.activityType = CLActivityType.fitness loc.allowsBackgroundLocationUpdates = false return loc }() //Applicaion state fileprivate var state : AppState = AppState() { willSet { print("Changing from state \(state) to \(newValue)") } didSet { self.updateOutputWithState() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.updateStateWithInput(.start) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.authorizedAlways { self.updateStateWithInput(.authorisationStatus(true)) } else { self.updateStateWithInput(.authorisationStatus(false)) } } // MARK: Action and Events @IBAction func doStart(_ sender: AnyObject) { self.updateStateWithInput(.userWantsToStart(true)) } @IBAction func doStop(_ sender: AnyObject) { self.updateStateWithInput(.userWantsToStart(false)) } @IBAction func doClear(_ sender: AnyObject) { } @IBAction func doOptions(_ sender: AnyObject) { } // MARK: State Machine //UPDATE STATE func updateStateWithInput(_ ip : AppStateInputSource) { var nextState = self.state switch (self.state) { case .waitingForViewDidLoad: if case .start = ip { nextState = .requestingAuth } case .requestingAuth: if case .authorisationStatus(let val) = ip, val == true { nextState = .liveMapNoLogging } case .liveMapNoLogging: //Check for user cancelling permission if case .authorisationStatus(let val) = ip, val == false { nextState = .requestingAuth } //Check for start button else if case .userWantsToStart(let val) = ip, val == true { nextState = .liveMapLogging } case .liveMapLogging: //Check for user cancelling permission if case .authorisationStatus(let val) = ip, val == false { nextState = .requestingAuth } //Check for stop button else if case .userWantsToStart(let val) = ip, val == false { nextState = .liveMapNoLogging } } self.state = nextState } //UPDATE (MOORE) OUTPUTS func updateOutputWithState() { switch (self.state) { case .waitingForViewDidLoad: break case .requestingAuth: locationManager.requestAlwaysAuthorization() //Set UI into default state until authorised //Buttons startButton.isEnabled = false stopButton.isEnabled = false clearButton.isEnabled = false optionsButton.isEnabled = false //Map defaults (pedantic) mapView.delegate = nil mapView.showsUserLocation = false //Location manger (pedantic) locationManager.stopUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = false case .liveMapNoLogging: //Buttons for logging startButton.isEnabled = true stopButton.isEnabled = false optionsButton.isEnabled = true //Live Map mapView.showsUserLocation = true mapView.userTrackingMode = .follow mapView.showsTraffic = true mapView.delegate = self case .liveMapLogging: //Buttons startButton.isEnabled = false stopButton.isEnabled = true optionsButton.isEnabled = true //Map mapView.showsUserLocation = true mapView.userTrackingMode = .follow mapView.showsTraffic = true mapView.delegate = self } } }
mit
cee607d5334cbeb0541e304421a5dcbd
28.320574
110
0.571638
5.87536
false
false
false
false
thomas-sivilay/roulette-ios
Roulette/Roulette/Sources/Features/Home/Home Cell/HomeCell.swift
1
1120
// // HomeCell.swift // Roulette // // Created by Thomas Sivilay on 6/26/17. // Copyright © 2017 Thomas Sivilay. All rights reserved. // import UIKit final class HomeCell: UICollectionViewCell { // MARK: - Properties private let titleLabel: UILabel = { let label = UILabel() label.backgroundColor = .clear label.textColor = .black label.textAlignment = .center return label }() // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Instance methods // MARK: Internal func configure(with viewModel: HomeCellViewModel) { titleLabel.text = viewModel.state.choice } // MARK: Private private func setupView() { addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsetsMake(0, 20, 0, 20)) } } }
mit
97d1597a3d085254c57795a24d550365
21.38
127
0.590706
4.54878
false
false
false
false
JulianNicholls/Clonagram
ParseStarterProject/UserListViewController.swift
1
4404
// // UserListViewController.swift // Clonagram // // Created by Julian Nicholls on 12/01/2016. // Copyright © 2016 Parse. All rights reserved. // import UIKit import Parse class UserListViewController: UITableViewController { var userlist = [Dictionary<String, String>]() var refresher: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() refresher = UIRefreshControl() refresher.attributedTitle = NSAttributedString(string: "Pull to refresh user list") refresher.addTarget(self, action: "loadUsers", forControlEvents: .ValueChanged) self.tableView.addSubview(refresher) loadUsers() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userlist.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel!.text = userlist[indexPath.row]["name"] if userlist[indexPath.row]["following"] == "1" { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } // Configure the cell... return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = self.tableView.cellForRowAtIndexPath(indexPath) let following = userlist[indexPath.row]["following"] == "1" if following { userlist[indexPath.row]["following"] = "0" let query = PFQuery(className: "follower") query.whereKey("follower", equalTo: (PFUser.currentUser()?.objectId)!) query.whereKey("following", equalTo: userlist[indexPath.row]["id"]!) query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in if let objects = objects { for obj in objects { obj.deleteInBackground() } } }) cell?.accessoryType = .None } else { userlist[indexPath.row]["following"] = "1" let relation = PFObject(className: "follower") relation["following"] = userlist[indexPath.row]["id"] relation["follower"] = PFUser.currentUser()?.objectId relation.saveInBackground() cell?.accessoryType = .Checkmark } } func loadUsers() { let query = PFUser.query() query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in if let users = objects { self.userlist.removeAll(keepCapacity: true) for object in users { if let user = object as? PFUser { if user.objectId != PFUser.currentUser()?.objectId { let query = PFQuery(className: "follower") query.whereKey("follower", equalTo: (PFUser.currentUser()?.objectId)!) query.whereKey("following", equalTo: user.objectId!) query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in var following = "0" if let objects = objects { if objects.count > 0 { following = "1" } } self.userlist.append(["name": user.username!, "id": user.objectId!, "following": following]) self.tableView.reloadData() }) } } } } // print(self.userlist) }) self.refresher.endRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
db3b96cfd460a1a96b2ca486fd866bad
29.157534
124
0.53509
5.748042
false
false
false
false
rogeruiz/MacPin
modules/MacPin/WebViewController.swift
2
2236
/// MacPin WebViewController /// /// Interlocute WebViews to general app UI import WebKit import JavaScriptCore @objc protocol WebViewControllerScriptExports: JSExport { // $.browser.tabs[N] #if os(OSX) var view: NSView { get } #elseif os(iOS) var view: UIView! { get } #endif var webview: MPWebView! { get } } @objc class WebViewController: ViewController, WebViewControllerScriptExports { var jsdelegate = AppScriptRuntime.shared.jsdelegate // FIXME: use webview.jsdelegate instead ?? dynamic var webview: MPWebView! = nil #if os(OSX) required init?(coder: NSCoder) { super.init(coder: coder) } // required by NSCoding protocol override init!(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nil, bundle:nil) } //calls loadView convenience required init(webview: MPWebView) { self.init(nibName: nil, bundle: nil) // calls init!() http://stackoverflow.com/a/26516534/3878712 webview.UIDelegate = self //alert(), window.open(): see <platform>/WebViewDelegates webview.navigationDelegate = self // allows/denies navigation actions: see WebViewDelegates self.webview = webview representedObject = webview // FIXME use NSProxy instead for both OSX and IOS view = webview } #elseif os(iOS) required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } required init(webview: MPWebView) { super.init(nibName: nil, bundle: nil) webview.UIDelegate = self //alert(), window.open(): see <platform>/WebViewDelegates webview.navigationDelegate = self // allows/denies navigation actions: see WebViewDelegates self.webview = webview view = webview } #endif override var title: String? { get { if let wti = webview.title where !wti.isEmpty { return wti } else if let urlstr = webview.URL?.absoluteString where !urlstr.isEmpty { return urlstr } else { return "Untitled" } } set { //noop } } override func viewDidLoad() { super.viewDidLoad() } func closeTab() { removeFromParentViewController() } func askToOpenCurrentURL() { askToOpenURL(webview.URL!) } // sugar for opening a new tab in parent browser VC func popup(webview: MPWebView) { parentViewController?.addChildViewController(self.dynamicType(webview: webview)) } }
gpl-3.0
bcfd8a3631efebe4ec3a96d3e9a434b4
34.492063
137
0.736136
3.802721
false
false
false
false
wibosco/ASOS-Consumer
ASOSConsumer/Networking/Product/ProductAPIManager.swift
1
1014
// // ProductAPIManager.swift // ASOSConsumer // // Created by William Boles on 07/03/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit class ProductAPIManager: APIManager { //MARK: - Retrieval class func retrieveProduct(categoryProduct: CategoryProduct, completion:((product: Product?) -> Void)?) { let stringURL = "\(kASOSBaseURL)/anyproduct_details.json?catid=\(categoryProduct.categoryProductID!)" let url = NSURL(string: stringURL)! let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in let operation = ProductRetrievalOperation.init(data: data!, completion: completion) QueueManager.sharedInstance.queue.addOperation(operation) }) } task.resume() } }
mit
9fc321d6d4cd9916c39b24dc809b9cbe
30.65625
119
0.623889
4.689815
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Home/Liveky/LiveTableViewController.swift
1
7077
// LiveTableViewController.swift // Created by ming on 16/9/19. // Copyright © 2017年 明. All rights reserved. // http://service.ingkee.com/api/live/gettop?imsi=&uid=17800399&proto=5&idfa=A1205EB8-0C9A-4131-A2A2-27B9A1E06622&lc=0000000000000026&cc=TG0001&imei=&sid=20i0a3GAvc8ykfClKMAen8WNeIBKrUwgdG9whVJ0ljXi1Af8hQci3&cv=IK3.1.00_Iphone&devi=bcb94097c7a3f3314be284c8a5be2aaeae66d6ab&conn=Wifi&ua=iPhone&idfv=DEBAD23B-7C6A-4251-B8AF-A95910B778B7&osversion=ios_9.300000&count=15&multiaddr=2 import Just import Kingfisher import UIKit import MJRefresh class LiveTableViewController: UITableViewController { // MARK: - 属性 var topicType: LivekyTopicType = .top fileprivate lazy var list : [LiveCell] = [LiveCell]() var multiaddr: Int = 0 var proto: Int = 5 fileprivate lazy var livekyHeaderView: LivekyCycleHeader = {[unowned self] in let hdcView = LivekyCycleHeader(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: MGScreenW/2.8),type: self.topicType == .top ? .top : .search) // 图片轮播器点击回调 hdcView.imageClickBlock = { [unowned self] (cycleHeaderModel) in if (cycleHeaderModel.url != nil) { let webViewVc = WebViewController(navigationTitle: cycleHeaderModel.title, urlStr: cycleHeaderModel.url!) self.show(webViewVc, sender: nil) } } return hdcView }() override func viewDidLoad() { super.viewDidLoad() tableView.tableHeaderView = livekyHeaderView if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) } } // self.tableView.estimatedRowHeight = 150 // self.tableView.rowHeight = UITableView.automaticDimension // 头部刷新 self.tableView.mj_header = MJRefreshGifHeader(refreshingBlock: { self.proto = 5 self.livekyHeaderView.loadData() // 轮播器数据 self.list.removeAll() self.loadList() }) // 下拉刷新 self.tableView.mj_footer = MJRefreshAutoGifFooter(refreshingBlock: { self.multiaddr += 5 self.proto += 5 self.loadList() }) self.tableView.mj_header?.beginRefreshing() } // 加载数据 func loadList() { var urlStr = "" if topicType == .top { urlStr = "http://service.ingkee.com/api/live/gettop?imsi=&uid=17800399&proto=\(proto)&idfa=A1205EB8-0C9A-4131-A2A2-27B9A1E06622&lc=0000000000000026&cc=TG0001&imei=&sid=20i0a3GAvc8ykfClKMAen8WNeIBKrUwgdG9whVJ0ljXi1Af8hQci3&cv=IK3.1.00_Iphone&devi=bcb94097c7a3f3314be284c8a5be2aaeae66d6ab&conn=Wifi&ua=iPhone&idfv=DEBAD23B-7C6A-4251-B8AF-A95910B778B7&osversion=ios_9.300000&count=10&multiaddr=\(self.multiaddr)" }else { urlStr = "http://120.55.238.158/api/live/themesearch?lc=0000000000000040&cc=TG0001&cv=IK3.7.00_Iphone&proto=\(proto)&idfa=00000000-0000-0000-0000-000000000000&idfv=64020C43-7EE7-4175-8A40-0DDC48C913B6&devi=41c42500bc5f28f4a79c6eb529706b12817052eb&osversion=ios_10.000000&ua=iPhone8_4&imei=&imsi=&uid=248036681&sid=20i1SHXxme13D7ooInw1pcWhrmyi0cK6rMjAsn7rWc12Chj7rHFI&conn=wifi&mtid=95d648efc6268131017dbba9f494bca9&mtxid=6c408c17cf2&logid=&keyword=AFCC0BC263924F20&longitude=108.893557&latitude=34.245905&s_sg=75be1abb462c90405b82c8a40f004bde&s_sc=100&s_st=1478569622" } Just.post(urlStr) { (r) in guard let json = r.json as? NSDictionary else { self.tableView.mj_header?.endRefreshing() self.tableView.mj_footer?.endRefreshing() return } let lives = YKLiveList(fromDictionary: json).lives! self.list += lives.map({ (live) -> LiveCell in return LiveCell(portrait: live.creator.portrait, addr: live.city, cover: "", viewers: live.onlineUsers, caster: live.creator.nick, url: live.streamAddr) }) OperationQueue.main.addOperation({ self.tableView.reloadData() }) self.tableView.mj_header?.endRefreshing() self.tableView.mj_footer?.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.tableView.mj_footer != nil) { self.tableView.mj_footer?.isHidden = (list.count == 0) } return list.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LiveTableViewCell", for: indexPath) as! LiveTableViewCell let live = list[indexPath.row] cell.labelNick.text = live.caster cell.labelAddr.text = live.addr.isEmpty ? "未知星球" : live.addr cell.labelViewers.text = "\(live.viewers)" //头像 var imgUrl = URL(string: live.portrait) if imgUrl == nil { imgUrl = URL(string: "http://img.meelive.cn/" + live.portrait) } //封面 cell.imgPortrait.kf.setImage(with: imgUrl, placeholder: UIImage(named: "10")) cell.imgCover.kf.setImage(with: imgUrl, placeholder: UIImage(named: "10")) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let playerVC = UIStoryboard(name: "Liveky", bundle: nil).instantiateViewController(withIdentifier: "KTurnToPlayerID") as! PlayerViewController playerVC.live = list[indexPath.row] present(playerVC, animated: true, completion: nil) } } // MARK: - PEEK和POP extension LiveTableViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location) else { return nil } guard let cell = tableView.cellForRow(at: indexPath) else { return nil } if #available(iOS 9.0, *) { previewingContext.sourceRect = cell.frame } let playerVC = UIStoryboard(name: "Liveky", bundle: nil).instantiateViewController(withIdentifier: "KTurnToPlayerID") as! PlayerViewController playerVC.live = list[indexPath.row] return playerVC } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { present(viewControllerToCommit, animated: true, completion: nil) } }
mit
fd7183aee5ce515e71fa40a91a11db04
43.291139
580
0.657331
3.726305
false
false
false
false
lhc70000/iina
iina/AppData.swift
1
4821
// // Data.swift // iina // // Created by lhc on 8/7/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa struct AppData { /** time interval to sync play pos */ static let getTimeInterval: Double = 0.1 /** speed values when clicking left / right arrow button */ // static let availableSpeedValues: [Double] = [-32, -16, -8, -4, -2, -1, 1, 2, 4, 8, 16, 32] // Stopgap for https://github.com/mpv-player/mpv/issues/4000 static let availableSpeedValues: [Double] = [0.03125, 0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16, 32] /** min/max speed for playback **/ static let minSpeed = 0.25 static let maxSpeed = 16.0 /** generate aspect and crop options in menu */ static let aspects: [String] = ["4:3", "5:4", "16:9", "16:10", "1:1", "3:2", "2.21:1", "2.35:1", "2.39:1"] static let aspectsInPanel: [String] = ["Default", "4:3", "16:9", "16:10", "21:9", "5:4"] static let cropsInPanel: [String] = ["None", "4:3", "16:9", "16:10", "21:9", "5:4"] static let rotations: [Int] = [0, 90, 180, 270] /** Seek amount */ static let seekAmountMap = [0, 0.05, 0.1, 0.25, 0.5] static let seekAmountMapMouse = [0, 0.5, 1, 2, 4] static let volumeMap = [0, 0.25, 0.5, 0.75, 1] static let encodings = CharEncoding.list static let userInputConfFolder = "input_conf" static let watchLaterFolder = "watch_later" static let historyFile = "history.plist" static let thumbnailCacheFolder = "thumb_cache" static let githubLink = "https://github.com/lhc70000/iina" static let contributorsLink = "https://github.com/lhc70000/iina/graphs/contributors" static let wikiLink = "https://github.com/lhc70000/iina/wiki" static let websiteLink = "https://lhc70000.github.io/iina/" static let emailLink = "[email protected]" static let ytdlHelpLink = "https://github.com/rg3/youtube-dl/blob/master/README.md#readme" static let appcastLink = "https://www.iina.io/appcast.xml" static let appcastBetaLink = "https://www.iina.io/appcast-beta.xml" static let assrtRegisterLink = "https://secure.assrt.net/user/register.xml?redir=http%3A%2F%2Fassrt.net%2Fusercp.php" static let chromeExtensionLink = "https://chrome.google.com/webstore/detail/open-in-iina/pdnojahnhpgmdhjdhgphgdcecehkbhfo" static let firefoxExtensionLink = "https://addons.mozilla.org/addon/open-in-iina-x" static let widthWhenNoVideo = 480 static let heightWhenNoVideo = 480 static let sizeWhenNoVideo = NSSize(width: widthWhenNoVideo, height: heightWhenNoVideo) } struct Constants { struct String { static let degree = "°" static let dot = "●" static let play = "▶︎" static let videoTimePlaceholder = "--:--:--" static let trackNone = NSLocalizedString("track.none", comment: "<None>") static let chapter = "Chapter" static let fullScreen = NSLocalizedString("menu.fullscreen", comment: "Fullscreen") static let exitFullScreen = NSLocalizedString("menu.exit_fullscreen", comment: "Exit Fullscreen") static let pause = NSLocalizedString("menu.pause", comment: "Pause") static let resume = NSLocalizedString("menu.resume", comment: "Resume") static let `default` = NSLocalizedString("quicksetting.item_default", comment: "Default") static let none = NSLocalizedString("quicksetting.item_none", comment: "None") static let audioDelay = "Audio Delay" static let subDelay = "Subtitle Delay" static let pip = NSLocalizedString("menu.pip", comment: "Enter Picture-in-Picture") static let exitPIP = NSLocalizedString("menu.exit_pip", comment: "Exit Picture-in-Picture") } struct Time { static let infinite = VideoTime(999, 0, 0) } struct FilterName { static let crop = "iina_crop" static let flip = "iina_flip" static let mirror = "iina_mirror" static let audioEq = "iina_aeq" static let delogo = "iina_delogo" } } extension Notification.Name { static let iinaMainWindowChanged = Notification.Name("IINAMainWindowChanged") static let iinaPlaylistChanged = Notification.Name("IINAPlaylistChanged") static let iinaTracklistChanged = Notification.Name("IINATracklistChanged") static let iinaVIDChanged = Notification.Name("iinaVIDChanged") static let iinaAIDChanged = Notification.Name("iinaAIDChanged") static let iinaSIDChanged = Notification.Name("iinaSIDChanged") static let iinaMediaTitleChanged = Notification.Name("IINAMediaTitleChanged") static let iinaVFChanged = Notification.Name("IINAVfChanged") static let iinaAFChanged = Notification.Name("IINAAfChanged") static let iinaKeyBindingInputChanged = Notification.Name("IINAkeyBindingInputChanged") static let iinaFileLoaded = Notification.Name("IINAFileLoaded") static let iinaHistoryUpdated = Notification.Name("IINAHistoryUpdated") static let iinaLegacyFullScreen = Notification.Name("IINALegacyFullScreen") }
gpl-3.0
4444e703cbe4cc9410b00a29ac9d794c
43.155963
124
0.712445
3.457615
false
false
false
false
mparrish91/gifRecipes
application/LinkContainerCellar.swift
2
1391
// // LinkContainerCellar.swift // reddift // // Created by sonson on 2016/10/05. // Copyright © 2016年 sonson. All rights reserved. // import Foundation public let LinkContainerCellarDidLoadName = Notification.Name(rawValue: "LinkContainerCellarDidLoadName") class LinkContainerCellar { static let reloadIndicesKey = "ReloadIndices" static let insertIndicesKey = "InsertIndices" static let deleteIndicesKey = "DeleteIndices" static let errorKey = "Error" static let isAtTheBeginningKey = "atTheBeginning" static let providerKey = "Provider" var containers: [LinkContainable] = [] var thumbnails: [Thumbnail] { get { return containers.flatMap({$0.thumbnails}) } } func updateHidden() { for i in 0..<containers.count { containers[i].isHidden = containers[i].link.hidden } } var width = CGFloat(0) var fontSize = CGFloat(0) func layout(with width: CGFloat, fontSize: CGFloat) { self.width = width self.fontSize = fontSize self.containers.forEach({ $0.layout(with: width, fontSize: fontSize) }) } private(set) var isLoading: Bool = false func load(atTheBeginning: Bool) {} func tryLoadingMessage() -> String { return "" } func loadingMessage() -> String { return "" } }
mit
4d51f079c9a9402a98d77e5f7ec796bb
28.531915
105
0.634006
4.406349
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/Blog+HomepageSettings.swift
1
3395
import Foundation enum HomepageType: String { case page case posts var title: String { switch self { case .page: return NSLocalizedString("Static Homepage", comment: "Name of setting configured when a site uses a static page as its homepage") case .posts: return NSLocalizedString("Classic Blog", comment: "Name of setting configured when a site uses a list of blog posts as its homepage") } } var remoteType: RemoteHomepageType { switch self { case .page: return .page case .posts: return .posts } } } extension Blog { private enum OptionsKeys { static let homepageType = "show_on_front" static let homepageID = "page_on_front" static let postsPageID = "page_for_posts" } /// The type of homepage used for the site: blog posts, or static pages /// var homepageType: HomepageType? { get { guard let options = options, !options.isEmpty, let type = getOptionString(name: OptionsKeys.homepageType) else { return nil } return HomepageType(rawValue: type) } set { if let value = newValue?.rawValue { setValue(value, forOption: OptionsKeys.homepageType) } } } /// The ID of the page to use for the site's 'posts' page, /// if `homepageType` is set to `.posts` /// var homepagePostsPageID: Int? { get { guard let options = options, !options.isEmpty, let pageID = getOptionNumeric(name: OptionsKeys.postsPageID) else { return nil } return pageID.intValue } set { let number: NSNumber? if let newValue = newValue { number = NSNumber(integerLiteral: newValue) } else { number = nil } setValue(number as Any, forOption: OptionsKeys.postsPageID) } } /// The ID of the page to use for the site's homepage, /// if `homepageType` is set to `.page` /// var homepagePageID: Int? { get { guard let options = options, !options.isEmpty, let pageID = getOptionNumeric(name: OptionsKeys.homepageID) else { return nil } return pageID.intValue } set { let number: NSNumber? if let newValue = newValue { number = NSNumber(integerLiteral: newValue) } else { number = nil } setValue(number as Any, forOption: OptionsKeys.homepageID) } } /// Getter which returns the current homepage (or nil) /// Note: It seems to be necessary to first sync pages (otherwise the `findPost` result fails to cast to `Page`) var homepage: Page? { guard let pageID = homepageType == .page ? homepagePageID : homepageType == .posts ? homepagePostsPageID : nil else { return nil } let context = ContextManager.sharedInstance().mainContext return lookupPost(withID: Int64(pageID), in: context) as? Page } }
gpl-2.0
0c38d6d046a55b925dd5e5afeb838ca4
29.3125
145
0.538439
4.891931
false
false
false
false
jay0420/jigsaw
JKPinTu-Swift/ViewControllers/Huaban/Model/JKHBTagInfo.swift
1
852
// // JKHBTagInfo.swift // PingTu-swift // // Created by bingjie-macbookpro on 15/12/10. // Copyright © 2015年 Bingjie. All rights reserved. // import UIKit class JKHBTagInfo: NSObject { var tag_name:String! var pin_count:Int! convenience init(name: String, count:Int) { self.init() self.tag_name = name self.pin_count = count } class func parseDataFromHuaban(_ responseArray:Array<AnyObject>) -> Array<JKHBTagInfo> { var objs = [JKHBTagInfo]() for item in responseArray{ let name = (item as! NSDictionary)["tag_name"] as! String let count = (item as! NSDictionary)["pin_count"] as! Int let tag = JKHBTagInfo(name: name, count: count) objs.append(tag) } return objs } }
mit
56c5cb9af7ef933c0ff0bdf4528aa57c
23.257143
92
0.57126
3.824324
false
false
false
false
atljeremy/JFCardSelectionViewController
JFCardSelectionViewController/JFCardSelectionViewController.swift
1
25430
/* * JFCardSelectionViewController * * Created by Jeremy Fox on 3/1/16. * Copyright (c) 2016 Jeremy Fox. 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 public struct CardAction { public let title: String public init?(title: String) { self.title = title } } public protocol CardPresentable { var imageURLString: String { get } var placeholderImage: UIImage? { get } var titleText: String { get } var dialLabel: String { get } var detailTextLineOne: String { get } var detailTextLineTwo: String { get } var actionOne: CardAction? { get } var actionTwo: CardAction? { get } } public enum JFCardSelectionViewSelectionAnimationStyle { case fade, slide } public protocol JFCardSelectionViewControllerDelegate { func cardSelectionViewController(_ cardSelectionViewController: JFCardSelectionViewController, didSelectCardAction cardAction: CardAction, forCardAtIndexPath indexPath: IndexPath) -> Void func cardSelectionViewController(_ cardSelectionViewController: JFCardSelectionViewController, didSelectDetailActionForCardAtIndexPath indexPath: IndexPath) -> Void } public protocol JFCardSelectionViewControllerDataSource { func numberOfCardsForCardSelectionViewController(_ cardSelectionViewController: JFCardSelectionViewController) -> Int func cardSelectionViewController(_ cardSelectionViewController: JFCardSelectionViewController, cardForItemAtIndexPath indexPath: IndexPath) -> CardPresentable } open class JFCardSelectionViewController: UIViewController { /// This will be the UIImage behind a UIVisualEffects view that will be used to add a blur effect to the background. If this isn't set, the photo of the selected CardPresentable will be used. open var backgroundImage: UIImage? { didSet { bgImageView.image = backgroundImage UIView.animate(withDuration: 0.3, animations: { self.bgImageView.alpha = 1 self.bgImageViewTwo.alpha = 0 }, completion: { (finished) -> Void in if finished { self.bgImageViewTwo.image = nil self.showingImageViewOne = true } }) } } open var delegate: JFCardSelectionViewControllerDelegate? open var dataSource: JFCardSelectionViewControllerDataSource? open var selectionAnimationStyle: JFCardSelectionViewSelectionAnimationStyle = .fade var previouslySelectedIndexPath: IndexPath? let focusedView = JFFocusedCardView.loadFromNib() let focusedViewTwo = JFFocusedCardView.loadFromNib() let dialView = DialView() let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: JFCardSelectionViewFlowLayout()) fileprivate var bgImageView = UIImageView() fileprivate var bgImageViewTwo = UIImageView() fileprivate var showingImageViewOne = true fileprivate var focusedViewHConstraints = [NSLayoutConstraint]() fileprivate var focusedViewTwoHConstraints = [NSLayoutConstraint]() fileprivate let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) fileprivate let blurEffectViewTwo = UIVisualEffectView(effect: UIBlurEffect(style: .light)) fileprivate let bottomCircleView = UIView() fileprivate let bottomCircleOutlineView = UIView() fileprivate let topSpace: CGFloat = 74 fileprivate let bottomSpace: CGFloat = 20 fileprivate let horizontalSpace: CGFloat = 75 fileprivate var focusedViewMetrics: [String: CGFloat] { let width = view.frame.width - (horizontalSpace * 2) return [ "maxX": view.frame.maxX, "minX": view.frame.minX - (width), "width": width, "topSpace": topSpace, "bottomSpace": bottomSpace, "horizontalSpace": horizontalSpace ] } fileprivate var focusedViewViews: [String: UIView] { return [ "focusedView": focusedView, "focusedViewTwo": focusedViewTwo, "collectionView": collectionView ] } deinit { collectionView.removeObserver(self, forKeyPath: "contentOffset") } open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white buildBGUI() buildCardSelectionUI() buildFocusedCardUI() if backgroundImage == nil { let indexPath = IndexPath(row: 0, section: 0) guard let card = dataSource?.cardSelectionViewController(self, cardForItemAtIndexPath: indexPath) else { return } bgImageView.loadImageAtURL(card.imageURLString, withDefaultImage: card.placeholderImage) } } open override var shouldAutorotate : Bool { return false } open func reloadData() { collectionView.reloadData() } fileprivate func buildBGUI() { bgImageView.image = backgroundImage ?? nil bgImageView.translatesAutoresizingMaskIntoConstraints = false blurEffectView.translatesAutoresizingMaskIntoConstraints = false bgImageView.addSubview(blurEffectView) view.addSubview(bgImageView) bgImageViewTwo.translatesAutoresizingMaskIntoConstraints = false blurEffectViewTwo.translatesAutoresizingMaskIntoConstraints = false bgImageViewTwo.addSubview(blurEffectViewTwo) bgImageViewTwo.alpha = 0 view.insertSubview(bgImageViewTwo, belowSubview: bgImageView) let views = ["bgImageView": bgImageView, "blurEffectView": blurEffectView, "bgImageViewTwo": bgImageViewTwo, "blurEffectViewTwo": blurEffectViewTwo] as [String : Any] for val in ["V", "H"] { view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "\(val):|[bgImageView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "\(val):|[bgImageViewTwo]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) bgImageView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "\(val):|[blurEffectView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) bgImageViewTwo.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "\(val):|[blurEffectViewTwo]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) } view.layoutIfNeeded() } fileprivate func buildCardSelectionUI() { collectionView.dataSource = self collectionView.delegate = self collectionView.showsHorizontalScrollIndicator = false let bundle = Bundle(for: JFCardSelectionCell.self) collectionView.register(UINib(nibName: JFCardSelectionCell.reuseIdentifier, bundle: bundle), forCellWithReuseIdentifier: JFCardSelectionCell.reuseIdentifier) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear view.addSubview(collectionView) let height = UIScreen.main.bounds.height / 3 var metrics = ["height": height] let views = ["collectionView": collectionView] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[collectionView(==height)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[collectionView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) view.layoutIfNeeded() var width = view.frame.width var y = view.frame.maxY - 40 dialView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(dialView, belowSubview: collectionView) metrics = ["width": view.frame.width, "y": view.frame.maxY - 60] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(y)-[dialView(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["dialView": dialView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[dialView(==width)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["dialView": dialView])) view.layoutIfNeeded() bottomCircleOutlineView.backgroundColor = UIColor.clear view.insertSubview(bottomCircleOutlineView, belowSubview: dialView) width += 15 y -= 27.5 bottomCircleOutlineView.frame = CGRect(x: 0, y: y, width: width, height: width) let trackingLine = UIView(frame: CGRect(x: 0, y: 0, width: width, height: width)) trackingLine.makeRoundWithBorder(width: 2, color: UIColor.white.withAlphaComponent(0.5)) bottomCircleOutlineView.addSubview(trackingLine) bottomCircleOutlineView.center.x = view.center.x var x = (bottomCircleOutlineView.frame.width / CGFloat(M_PI * 2)) - 9.5 y = x let trackingIndicatorInner = UIView(frame: CGRect(x: x, y: y, width: 10, height: 10)) trackingIndicatorInner.makeRound() trackingIndicatorInner.backgroundColor = UIColor.white x -= 2.5 y -= 2.5 let trackingIndicatorOuter = UIView(frame: CGRect(x: x, y: y, width: 15, height: 15)) trackingIndicatorOuter.makeRound() trackingIndicatorOuter.backgroundColor = UIColor.black.withAlphaComponent(0.2) bottomCircleOutlineView.addSubview(trackingIndicatorOuter) bottomCircleOutlineView.addSubview(trackingIndicatorInner) collectionView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) } fileprivate func buildFocusedCardUI() { focusedView.delegate = self focusedViewTwo.delegate = self focusedView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(focusedView) focusedViewTwo.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(focusedViewTwo, belowSubview: focusedView) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topSpace)-[focusedView]-(bottomSpace)-[collectionView]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews)) focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(horizontalSpace)-[focusedView]-(horizontalSpace)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) view.addConstraints(focusedViewHConstraints) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topSpace)-[focusedViewTwo]-(bottomSpace)-[collectionView]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews)) switch selectionAnimationStyle { case .fade: focusedViewTwo.alpha = 0 focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(horizontalSpace)-[focusedViewTwo]-(horizontalSpace)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) view.addConstraints(focusedViewTwoHConstraints) case .slide: focusedViewTwo.isHidden = true focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(maxX)-[focusedViewTwo]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) view.addConstraints(focusedViewTwoHConstraints) } view.layoutIfNeeded() let color = UIColor.black.withAlphaComponent(0.4) let h = 64 let w = 44 let metrics = ["w": w, "h": h] var acc = AccessoryIndicator.withColor(color, facing: .left, size: CGSize(width: w, height: h)) acc.addTarget(self, action: #selector(previousCard), for: .touchUpInside) acc.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(acc, belowSubview: focusedView) view.addConstraint(NSLayoutConstraint(item: acc, attribute: .centerY, relatedBy: .equal, toItem: focusedView, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[acc(==h)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["acc": acc])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[acc(==w)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["acc": acc])) acc = AccessoryIndicator.withColor(color, facing: .right, size: CGSize(width: w, height: h)) acc.translatesAutoresizingMaskIntoConstraints = false acc.addTarget(self, action: #selector(nextCard), for: .touchUpInside) view.insertSubview(acc, belowSubview: focusedView) view.addConstraint(NSLayoutConstraint(item: acc, attribute: .centerY, relatedBy: .equal, toItem: focusedView, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[acc(==h)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["acc": acc])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[acc(==w)]-(0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: ["acc": acc])) view.layoutIfNeeded() } func updateUIForCard(_ card: CardPresentable, atIndexPath indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) if !showingImageViewOne { if backgroundImage == nil { bgImageView.loadImageAtURL(card.imageURLString, withDefaultImage: card.placeholderImage) } focusedView.configureForCard(card) } else { if backgroundImage == nil { bgImageViewTwo.loadImageAtURL(card.imageURLString, withDefaultImage: card.placeholderImage) } focusedViewTwo.configureForCard(card) } switch selectionAnimationStyle { case .fade: fade() case .slide: slideToIndexPath(indexPath) } showingImageViewOne = !showingImageViewOne } func previousCard() { let count = dataSource?.numberOfCardsForCardSelectionViewController(self) ?? 0 let row = (previouslySelectedIndexPath?.row ?? 0) - 1 let section = previouslySelectedIndexPath?.section ?? 0 if row >= 0 && row < count { let indexPath = IndexPath(row: row, section: section) guard let card = dataSource?.cardSelectionViewController(self, cardForItemAtIndexPath: indexPath) else { return } collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition()) updateUIForCard(card, atIndexPath: indexPath) previouslySelectedIndexPath = indexPath } } func nextCard() { let count = dataSource?.numberOfCardsForCardSelectionViewController(self) ?? 0 let row = (previouslySelectedIndexPath?.row ?? 0) + 1 let section = previouslySelectedIndexPath?.section ?? 0 if row < count { let indexPath = IndexPath(row: row, section: section) guard let card = dataSource?.cardSelectionViewController(self, cardForItemAtIndexPath: indexPath) else { return } collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition()) updateUIForCard(card, atIndexPath: indexPath) previouslySelectedIndexPath = indexPath } } func fade() { UIView.animate(withDuration: 0.5, animations: { () -> Void in if self.backgroundImage == nil { self.bgImageView.alpha = !self.showingImageViewOne ? 1 : 0 self.bgImageViewTwo.alpha = self.showingImageViewOne ? 1 : 0 } self.focusedView.alpha = !self.showingImageViewOne ? 1 : 0 self.focusedViewTwo.alpha = self.showingImageViewOne ? 1 : 0 }, completion: { finished in self.finishAnimations() }) } func finishAnimations() { if self.showingImageViewOne { if self.backgroundImage == nil { self.bgImageViewTwo.image = nil } self.focusedViewTwo.configureForCard(nil) } else { if self.backgroundImage == nil { self.bgImageView.image = nil } self.focusedView.configureForCard(nil) } } func shake() { var startX: CGFloat if self.showingImageViewOne { startX = self.focusedView.center.x } else { startX = self.focusedViewTwo.center.x } UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { () -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.125) { if self.showingImageViewOne { self.focusedView.center.x += 10 } else { self.focusedViewTwo.center.x += 10 } } UIView.addKeyframe(withRelativeStartTime: 0.125, relativeDuration: 0.125) { if self.showingImageViewOne { self.focusedView.center.x -= 10 } else { self.focusedViewTwo.center.x -= 10 } } UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.125) { if self.showingImageViewOne { self.focusedView.center.x -= 10 } else { self.focusedViewTwo.center.x -= 10 } } UIView.addKeyframe(withRelativeStartTime: 0.375, relativeDuration: 0.125) { if self.showingImageViewOne { self.focusedView.center.x = startX } else { self.focusedViewTwo.center.x = startX } } }) { (finished) -> Void in } } func slideToIndexPath(_ indexPath: IndexPath) { var scrollLeft = true if let _previousIndexPath = previouslySelectedIndexPath { scrollLeft = indexPath.row > _previousIndexPath.row } // Moves views into starting position if showingImageViewOne { focusedViewTwo.isHidden = true view.removeConstraints(focusedViewTwoHConstraints) if scrollLeft { focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(maxX)-[focusedViewTwo(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } else { focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(minX)-[focusedViewTwo(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } view.addConstraints(focusedViewTwoHConstraints) view.layoutIfNeeded() focusedViewTwo.isHidden = false view.removeConstraints(focusedViewHConstraints) view.removeConstraints(focusedViewTwoHConstraints) focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(horizontalSpace)-[focusedViewTwo]-(horizontalSpace)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) if scrollLeft { focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(minX)-[focusedView(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } else { focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(maxX)-[focusedView(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } view.addConstraints(focusedViewHConstraints) view.addConstraints(focusedViewTwoHConstraints) } else { focusedView.isHidden = true view.removeConstraints(focusedViewHConstraints) if scrollLeft { focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(maxX)-[focusedView(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } else { focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(minX)-[focusedView(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } view.addConstraints(focusedViewHConstraints) view.layoutIfNeeded() focusedView.isHidden = false view.removeConstraints(focusedViewHConstraints) view.removeConstraints(focusedViewTwoHConstraints) focusedViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(horizontalSpace)-[focusedView]-(horizontalSpace)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) if scrollLeft { focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(minX)-[focusedViewTwo(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } else { focusedViewTwoHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(maxX)-[focusedViewTwo(==width)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: focusedViewMetrics, views: focusedViewViews) } view.addConstraints(focusedViewHConstraints) view.addConstraints(focusedViewTwoHConstraints) } // Animates views into final position UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.9, options: UIViewAnimationOptions(), animations: { () -> Void in self.view.layoutIfNeeded() if self.backgroundImage == nil { self.bgImageView.alpha = !self.showingImageViewOne ? 1 : 0 self.bgImageViewTwo.alpha = self.showingImageViewOne ? 1 : 0 } }) { finished in self.finishAnimations() } } var rotation: CGFloat = 0 open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let offset = (change?[NSKeyValueChangeKey.newKey] as AnyObject).cgPointValue else { return } guard let flowLayout = collectionView.collectionViewLayout as? JFCardSelectionViewFlowLayout else { return } let w = ((collectionView.contentSize.width - (flowLayout.sectionInset.left + flowLayout.sectionInset.right))) / CGFloat(M_PI_2) rotation = (offset.x / w) bottomCircleOutlineView.transform = CGAffineTransform(rotationAngle: rotation) let collectionViewCenterX = collectionView.center.x for item in collectionView.visibleCells { guard let cardCell = item as? JFCardSelectionCell else { return } let cardPosition = view.convert(cardCell.center, from: collectionView) if cardPosition.x <= collectionViewCenterX + 20 && cardPosition.x >= collectionViewCenterX - 20 { guard let label = cardCell.card?.dialLabel else { return } dialView.rotatePointerToLabel(label) } } } }
mit
4d5409689419f2e54aeba9bcae93dc8d
51.217659
250
0.674322
5.312304
false
false
false
false
google/android-auto-companion-app
ios/Runner/TrustedDeviceConstants.swift
1
1912
// Copyright 2022 Google LLC // // 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. /// Constants for mapping methods across the flutter `MethodChannel`. /// /// This file is auto-generated. enum TrustedDeviceConstants { static let channel = "google.gas.batmobile.trusteddevice/method" static let openSecuritySettings = "openSecuritySettings" static let onUnlockStatusChanged = "onUnlockStatusChanged" static let onTrustAgentEnrollmentCompleted = "onTrustAgentEnrollmentCompleted" static let onTrustAgentUnenrolled = "onTrustAgentUnenrolled" static let onTrustAgentEnrollmentError = "onTrustAgentEnrollmentError" static let enrollTrustAgent = "enrollTrustAgent" static let stopTrustAgentEnrollment = "stopTrustAgentEnrollment" static let trustAgentEnrollmentErrorKey = "trustAgentEnrollmentErrorKey" static let unlockStatusKey = "unlockStatusKey" static let getUnlockHistory = "getUnlockHistory" static let isTrustedDeviceEnrolled = "isTrustedDeviceEnrolled" static let setDeviceUnlockRequired = "setDeviceUnlockRequired" static let isDeviceUnlockRequired = "isDeviceUnlockRequired" static let isDeviceUnlockRequiredKey = "isDeviceUnlockRequiredKey" static let shouldShowUnlockNotification = "shouldShowUnlockNotification" static let shouldShowUnlockNotificationKey = "shouldShowUnlockNotificationKey" static let setShowUnlockNotification = "setShowUnlockNotification" }
apache-2.0
788ef9a01e7f34957b8c6bc58c316f5a
50.675676
80
0.806485
4.563246
false
false
false
false
rdlester/simply-giphy
Pods/Nimble/Sources/Lib/CwlPreconditionTesting/CwlPreconditionTesting/CwlBadInstructionException.swift
1
3750
// // CwlBadInstructionException.swift // CwlPreconditionTesting // // Created by Matt Gallagher on 2016/01/10. // Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation #if SWIFT_PACKAGE import CwlMachBadInstructionHandler #endif private func raiseBadInstructionException() { BadInstructionException().raise() } /// A simple NSException subclass. It's not required to subclass NSException (since the exception type is represented in the name) but this helps for identifying the exception through runtime type. @objc(BadInstructionException) public class BadInstructionException: NSException { static var name: String = "com.cocoawithlove.BadInstruction" init() { super.init(name: NSExceptionName(rawValue: BadInstructionException.name), reason: nil, userInfo: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// An Objective-C callable function, invoked from the `mach_exc_server` callback function `catch_mach_exception_raise_state` to push the `raiseBadInstructionException` function onto the stack. @objc(receiveReply:) public class func receiveReply(_ value: NSValue) -> NSNumber { #if arch(x86_64) var reply = bad_instruction_exception_reply_t(exception_port: 0, exception: 0, code: nil, codeCnt: 0, flavor: nil, old_state: nil, old_stateCnt: 0, new_state: nil, new_stateCnt: nil) withUnsafeMutablePointer(to: &reply) { value.getValue(UnsafeMutableRawPointer($0)) } let old_state: UnsafePointer<natural_t> = reply.old_state! let old_stateCnt: mach_msg_type_number_t = reply.old_stateCnt let new_state: thread_state_t = reply.new_state! let new_stateCnt: UnsafeMutablePointer<mach_msg_type_number_t> = reply.new_stateCnt! // Make sure we've been given enough memory if old_stateCnt != x86_THREAD_STATE64_COUNT || new_stateCnt.pointee < x86_THREAD_STATE64_COUNT { return NSNumber(value: KERN_INVALID_ARGUMENT) } // Read the old thread state var state = old_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { return $0.pointee } // 1. Decrement the stack pointer state.__rsp -= __uint64_t(MemoryLayout<Int>.size) // 2. Save the old Instruction Pointer to the stack. if let pointer = UnsafeMutablePointer<__uint64_t>(bitPattern: UInt(state.__rsp)) { pointer.pointee = state.__rip } else { return NSNumber(value: KERN_INVALID_ARGUMENT) } // 3. Set the Instruction Pointer to the new function's address var f: @convention(c) () -> Void = raiseBadInstructionException withUnsafePointer(to: &f) { state.__rip = $0.withMemoryRebound(to: __uint64_t.self, capacity: 1) { return $0.pointee } } // Write the new thread state new_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { $0.pointee = state } new_stateCnt.pointee = x86_THREAD_STATE64_COUNT return NSNumber(value: KERN_SUCCESS) #else fatalError("Unavailable for this CPU architecture") #endif } }
apache-2.0
d208bded505669a7696162ae07599878
41.123596
197
0.737797
3.730348
false
false
false
false
openHPI/xikolo-ios
iOS/Helpers/PersistenceManager/StreamPersistenceManager.swift
1
11045
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import AVFoundation import BrightFutures import Common import CoreData final class StreamPersistenceManager: PersistenceManager<StreamPersistenceManager.Configuration> { enum Configuration: PersistenceManagerConfiguration { // swiftlint:disable nesting typealias Resource = Video typealias Session = AVAssetDownloadURLSession // swiftlint:enable nesting static let keyPath = \Video.localFileBookmark static let downloadType = "stream" static let titleForFailedDownloadAlert = NSLocalizedString("alert.download-error.stream.title", comment: "title of alert for stream download errors") static func newFetchRequest() -> NSFetchRequest<Video> { return Video.fetchRequest() } } static let shared = StreamPersistenceManager() var backgroundCompletionHandler: (() -> Void)? private var assetTitlesForRecourseIdentifiers: [String: String] = [:] private var mediaSelectionForDownloadTask: [AVAssetDownloadTask: AVMediaSelection] = [:] override func newDownloadSession() -> AVAssetDownloadURLSession { let sessionIdentifier = "asset-download" let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: sessionIdentifier) return AVAssetDownloadURLSession(configuration: backgroundConfiguration, assetDownloadDelegate: self, delegateQueue: OperationQueue.main) } override func downloadTask(with url: URL, for resource: Video, on session: AVAssetDownloadURLSession) -> URLSessionTask? { let assetTitleCourse = resource.item?.section?.course?.slug ?? "Unknown course" let assetTitleItem = resource.item?.title ?? "Untitled video" let assetTitle = "\(assetTitleItem) (\(assetTitleCourse))".safeAsciiString() ?? "Untitled video" let asset = AVURLAsset(url: url) let options = [AVAssetDownloadTaskMinimumRequiredMediaBitrateKey: UserDefaults.standard.videoQualityForDownload.rawValue] // Supplementary downloads (likes subtitles) must have the same asset title when creating the download tasks. // Therefore, we store the used title for later usage. self.assetTitlesForRecourseIdentifiers[resource.id] = assetTitle // Using `aggregateAssetDownloadTask(with:mediaSelections:assetTitle:assetArtworkData:options:)` results in downloaded assets // that fail to start the playback without an Internet connection. So we are using the consecutive approach introduced in iOS 10. return session.makeAssetDownloadTask(asset: asset, assetTitle: assetTitle, assetArtworkData: resource.posterImageData, options: options) } override func startSupplementaryDownloads(for task: URLSessionTask, with resourceIdentifier: String) -> Bool { guard let assetDownloadTask = task as? AVAssetDownloadTask else { return false } guard let (mediaSelectionGroup, mediaSelectionOption) = self.nextMediaSelection(assetDownloadTask.urlAsset) else { return false } guard let originalMediaSelection = self.mediaSelectionForDownloadTask[assetDownloadTask] else { return false } guard let assetTitle = self.assetTitlesForRecourseIdentifiers[resourceIdentifier] else { return false } guard let mediaSelection = originalMediaSelection.mutableCopy() as? AVMutableMediaSelection else { return false } mediaSelection.select(mediaSelectionOption, in: mediaSelectionGroup) // Must have the same asset title as the original download task. guard let task = self.session.makeAssetDownloadTask(asset: assetDownloadTask.urlAsset, assetTitle: assetTitle, assetArtworkData: nil, options: [AVAssetDownloadTaskMediaSelectionKey: mediaSelection]) else { return false } task.taskDescription = resourceIdentifier self.activeDownloads[task] = resourceIdentifier task.resume() return true } override func resourceModificationAfterStartingDownload(for resource: Video) { resource.downloadDate = Date() } override func resourceModificationAfterDeletingDownload(for resource: Video) { resource.downloadDate = nil } private func trackingContext(for video: Video, options: [Option]) -> [String: String?] { var context = [ "section_id": video.item?.section?.id, "course_id": video.item?.section?.course?.id, "video_download_pref": String(describing: UserDefaults.standard.videoQualityForDownload.rawValue), "free_space": String(describing: StreamPersistenceManager.systemFreeSize), "total_space": String(describing: StreamPersistenceManager.systemSize), ] for case let .trackingContext(additionalContext) in options { context.merge(additionalContext) { $1 } } return context } override func didStartDownload(for resource: Video, options: [Option]) { let trackingContext = self.trackingContext(for: resource, options: options) TrackingHelper.createEvent(.videoDownloadStart, resourceType: .video, resourceId: resource.id, on: nil, context: trackingContext) } override func didCancelDownload(for resource: Video, options: [Option]) { let trackingContext = self.trackingContext(for: resource, options: options) TrackingHelper.createEvent(.videoDownloadCanceled, resourceType: .video, resourceId: resource.id, on: nil, context: trackingContext) } override func didFinishDownload(for resource: Video, options: [Option]) { let trackingContext = self.trackingContext(for: resource, options: options) TrackingHelper.createEvent(.videoDownloadFinished, resourceType: .video, resourceId: resource.id, on: nil, context: trackingContext) } private func nextMediaSelection(_ asset: AVURLAsset) -> (mediaSelectionGroup: AVMediaSelectionGroup, mediaSelectionOption: AVMediaSelectionOption)? { guard let assetCache = asset.assetCache else { return nil } let mediaCharacteristics = [AVMediaCharacteristic.audible, AVMediaCharacteristic.legible] for mediaCharacteristic in mediaCharacteristics { if let mediaSelectionGroup = asset.mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic) { let savedOptions = assetCache.mediaSelectionOptions(in: mediaSelectionGroup) if savedOptions.count < mediaSelectionGroup.options.count { // There are still media options left to download. for option in mediaSelectionGroup.options { if !savedOptions.contains(option) && option.mediaType != AVMediaType.closedCaption { // This option has not been download. return (mediaSelectionGroup, option) } } } } } // At this point all media options have been downloaded. return nil } override func fileSize(for resource: Video) -> UInt64? { guard let url = self.localFileLocation(for: resource) else { return nil } return try? FileManager.default.allocatedSizeOfDirectory(at: url) } } extension StreamPersistenceManager { @discardableResult func startDownload(for video: Video, options: [StreamPersistenceManager.Option] = []) -> Future<Void, XikoloError> { guard let url = video.streamURLForDownload else { return Future(error: .totallyUnknownError) } return self.startDownload(with: url, for: video, options: options) } @discardableResult func startDownloads(for section: CourseSection, options: [StreamPersistenceManager.Option] = []) -> Future<Void, XikoloError> { let sectionDownloadFuture = section.items.compactMap { item in return item.content as? Video }.filter { video in return self.downloadState(for: video) == .notDownloaded }.map { video in self.startDownload(for: video, options: options) }.sequence().asVoid() return sectionDownloadFuture } @discardableResult func deleteDownloads(for section: CourseSection) -> Future<Void, XikoloError> { let sectionDeleteFuture = section.items.compactMap { item in return item.content as? Video }.map { video in self.deleteDownload(for: video) }.sequence().asVoid() return sectionDeleteFuture } func cancelDownloads(for section: CourseSection) { section.items.compactMap { item in return item.content as? Video }.filter { video in return [.pending, .downloading].contains(StreamPersistenceManager.shared.downloadState(for: video)) }.forEach { video in self.cancelDownload(for: video) } } } extension StreamPersistenceManager: AVAssetDownloadDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { self.didCompleteDownloadTask(task, with: error) } func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) { self.didFinishDownloadTask(assetDownloadTask, to: location) } func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didLoad timeRange: CMTimeRange, totalTimeRangesLoaded loadedTimeRanges: [NSValue], timeRangeExpectedToLoad: CMTimeRange) { guard let videoId = self.activeDownloads[assetDownloadTask] else { return } var percentComplete = 0.0 for value in loadedTimeRanges { let loadedTimeRange: CMTimeRange = value.timeRangeValue percentComplete += CMTimeGetSeconds(loadedTimeRange.duration) / CMTimeGetSeconds(timeRangeExpectedToLoad.duration) } var userInfo: [String: Any] = [:] userInfo[DownloadNotificationKey.downloadType] = StreamPersistenceManager.Configuration.downloadType userInfo[DownloadNotificationKey.resourceId] = videoId userInfo[DownloadNotificationKey.downloadProgress] = percentComplete NotificationCenter.default.post(name: DownloadProgress.didChangeNotification, object: nil, userInfo: userInfo) } func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didResolve resolvedMediaSelection: AVMediaSelection) { self.mediaSelectionForDownloadTask[assetDownloadTask] = resolvedMediaSelection } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { self.backgroundCompletionHandler?() } }
gpl-3.0
57deb28ad3abd6c5ef7bca620ff8aefe
45.79661
153
0.691326
5.32241
false
false
false
false
onevcat/Hedwig
Sources/SMTP.swift
1
16540
// // SMTP.swift // Hedwig // // Created by WANG WEI on 16/12/27. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import TLS import Socks private func logError(_ error: SMTP.SMTPError, message: String? = nil) { let message = message ?? "" print("[Hedwig] SMTP Error: \(error). \(message)") } private func logWarning(message: String? = nil) { let message = message ?? "" print("[Hedwig] SMTP Warning: \(message)") } /// SMTP Port number public typealias Port = UInt16 /// Represents an remote SMTP. Do not use this type directly. Use `Hedwig` to /// send mails instead. public class SMTP { let hostName: String fileprivate let port: Port fileprivate let user: String? fileprivate let password: String? fileprivate let preferredAuthMethods: [AuthMethod] fileprivate let domainName: String fileprivate let secure: Secure fileprivate var socket: SMTPSocket fileprivate(set) var state: State fileprivate(set) var loggedIn: Bool fileprivate var features: Feature? fileprivate let validation: Validation fileprivate var secureConnected = false struct Feature { let data: [String: Any] init(_ data: [String: Any]) { self.data = data } } init(hostName: String, user: String?, password: String?, port: Port? = nil, secure: Secure = .tls, validation: Validation = .default, domainName: String = "localhost", authMethods: [AuthMethod] = [.plain, .cramMD5, .login, .xOauth2]) throws { self.hostName = hostName self.user = user self.password = password self.preferredAuthMethods = authMethods self.domainName = domainName self.port = port ?? secure.port self.secure = secure self.loggedIn = (user != nil && password != nil) ? false : true self.state = .notConnected self.validation = validation if secure == .plain || secure == .tls { let sock = try TCPClient(hostName: hostName, port: self.port) self.socket = SMTPSocket(sock: sock) } else { let sock = try TLS.Socket(mode: .client, hostname: hostName, port: self.port, certificates: validation.certificate, cipher: validation.cipher, proto: validation.protocols) self.socket = SMTPSocket(sock: sock) } } deinit { if state != .notConnected { try? close() } } func updateFeatures(_ s: String) { features = s.featureDictionary() } } extension SMTP { /// Represents SMTP validation methods. public struct Validation { /// Certificate used when connecting to /// SMTP server through a secure layer. public let certificate: Certificates /// Cipher used when connecting to SMTP. public let cipher: Config.Cipher /// Protocols supported when connecting to SMTP. public let protocols: [Config.TLSProtocol] /// Initilize a validation instance. /// /// - Parameters: /// - certificate: Certificate used when connecting to /// SMTP server through a secure layer. /// - cipher: Cipher used when connecting to SMTP. /// - protocols: Protocols supported when connecting to SMTP. public init(certificate: Certificates, cipher: Config.Cipher, protocols: [Config.TLSProtocol]) { self.certificate = certificate self.cipher = cipher self.protocols = protocols } /// Default `Validation` instance, with default certificate, /// compat cipher and all protocols supporting. public static let `default` = Validation(certificate: .defaults, cipher: .compat, protocols: [.all]) } } extension SMTP { /// Error while SMTP connecting and communicating. public enum SMTPError: Error, CustomStringConvertible { /// Could not connect to remote server. case couldNotConnect /// Connecting to SMTP server time out case timeOut /// The response of SMTP server is bad and not expected. case badResponse /// No connection has been established case noConnection /// Authorization failed case authFailed /// Can not authorizate since target server not support EHLO case authNotSupported /// No form of authorization methos supported case authUnadvertised /// Connection is closed by remote case connectionClosed /// Connection is already ended case connectionEnded /// Connection auth failed case connectionAuth /// Unknown error case unknown /// A human-readable description of SMTP error. public var description: String { let message: String switch self { case .couldNotConnect: message = "could not connect to SMTP server" case .timeOut: message = "connecting to SMTP server time out" case .badResponse: message = "bad response" case .noConnection: message = "no connection has been established" case .authFailed: message = "authorization failed" case .authUnadvertised: message = "can not authorizate since target server not support EHLO" case .authNotSupported: message = "no form of authorization supported" case .connectionClosed: message = "connection is closed by remote" case .connectionEnded: message = "connection is ended" case .connectionAuth: message = "connection auth failed" case .unknown: message = "unknown error" } return message } } } extension SMTP { /// Secrity layer used when connencting an SMTP server. public enum Secure { /// No encryped. If the server supports STARTTLS, the layer will be /// upgraded automatically. case plain /// Secure Sockets Layer. case ssl /// Transport Layer Security. If the server supports STARTTLS, the /// layer will be upgraded automatically. case tls var port: Port { switch self { case .plain: return 25 case .ssl: return 465 case .tls: return 587 } } } } extension SMTP { enum State { case notConnected case connecting case connected } } extension SMTP { /// Auth method to an SMTP server. /// /// - plain: Plain authorization. /// - cramMD5: CRAM-MD5 authorization. /// - login: Login authorization. /// - xOauth2: xOauth2 authorization. public enum AuthMethod: String { /// Plain authorization. case plain = "PLAIN" /// CRAM-MD5 authorization. case cramMD5 = "CRAM-MD5" /// Login authorization. case login = "LOGIN" /// xOauth2 authorization. case xOauth2 = "XOAUTH2" } } /// SMTP Operation extension SMTP { func connect() throws -> SMTPResponse { guard state == .notConnected else { _ = try quit() return try connect() } self.state = .connecting let response = try socket.connect(servername: hostName) guard response.code == .serviceReady else { let error = SMTPError.badResponse logError(error, message: "\(error.description) on connecting: \(response.message)") throw error } self.state = .connected if secure == .ssl { secureConnected = true } return response } func send(_ string: String, expectedCodes: [SMTPReplyCode]) throws -> SMTPResponse { guard state == .connected else { try close() let error = SMTPError.noConnection logError(error, message: "no connection has been established") throw error } let response = try socket.send(string) guard expectedCodes.contains(response.code) else { let error = SMTPError.badResponse logError(error, message: "\(error.description) on command: \(string), response: \(response.message)") throw error } return response } func send(_ command: SMTPCommand) throws -> SMTPResponse { return try send(command.text, expectedCodes: command.expectedCodes) } func login() throws { try sayHello() guard let features = features else { let error = SMTPError.unknown logError(error, message: "\(error.description) Unknown error happens when login. EHLO and HELO failed.") throw error } guard let user = user, let password = password else { let error = SMTPError.authFailed logError(error, message: "\(error.description) User name or password is not supplied.") throw error } guard let method = (preferredAuthMethods.first { features.supported(auth: $0) }) else { let error = SMTPError.authNotSupported logError(error, message: "\(error.description)") throw error } let loginResult: SMTPResponse switch method { case .cramMD5: let response = try send(.auth(.cramMD5, "")) let challenge = response.message let responseToChallenge = try CryptoEncoder.cramMD5(challenge: challenge, user: user, password: password) loginResult = try send(.authResponse(.cramMD5, responseToChallenge)) case .login: _ = try send(.auth(.login, "")) let identify = CryptoEncoder.login(user: user, password: password) _ = try send(.authUser(identify.encodedUser)) loginResult = try send(.authResponse(.login, identify.encodedPassword)) case .plain: loginResult = try send(.auth(.plain, CryptoEncoder.plain(user: user, password: password))) case .xOauth2: loginResult = try send(.auth(.xOauth2, CryptoEncoder.xOauth2(user: user, password: password))) } if loginResult.code == .authSucceeded { loggedIn = true } else if loginResult.code == .authFailed { let error = SMTPError.authFailed logError(error, message: "\(error.description)") throw error } else { let error = SMTPError.authUnadvertised logError(error, message: "\(error.description)") throw error } } func sayHello() throws { if features != nil { return } // First, try ehlo to see whether it is supported. do { _ = try ehlo() } // If not, try helo catch { _ = try helo() } } func message(bytes: [UInt8]) throws { try socket.sock.send(bytes: bytes) } func close() throws { try socket.close() state = .notConnected loggedIn = (user != nil && password != nil) ? false : true secureConnected = false } } /// SMTP Commands extension SMTP { func helo() throws -> SMTPResponse { let response = try send(.helo(domainName)) updateFeatures(response.data) return response } func ehlo() throws -> SMTPResponse { let response = try send(.ehlo(domainName)) updateFeatures(response.data) if !secureConnected { if features?.canStartTLS ?? false { try starttls() secureConnected = true return try ehlo() } else { logWarning(message: "Using plain SMTP and server does not support STARTTLS command. It is not recommended to submit information to this server!") } } return response } func starttls() throws { _ = try send(.starttls) let sock = try TLS.Socket(existing: socket.sock.internalSocket, certificates: validation.certificate, cipher: validation.cipher, proto: validation.protocols, hostName: hostName) socket = SMTPSocket(sock: sock) secureConnected = true } func help(args: String? = nil) throws -> SMTPResponse { return try send(.help(args)) } func rset() throws -> SMTPResponse { return try send(.rset) } func noop() throws -> SMTPResponse { return try send(.noop) } func mail(from: String) throws -> SMTPResponse { return try send(.mail(from)) } func rcpt(to: String) throws -> SMTPResponse { return try send(.rcpt(to)) } func data() throws -> SMTPResponse { return try send(.data) } func dataEnd() throws -> SMTPResponse { return try send(.dataEnd) } func vrfy(address: String) throws -> SMTPResponse { return try send(.vrfy(address)) } func expn(address: String) throws -> SMTPResponse { return try send(.expn(address)) } func quit() throws -> SMTPResponse { defer { try? close() } let response = try send(.quit) return response } } extension String { static let featureMather = try! Regex(pattern: "^(?:\\d+[\\-=]?)\\s*?([^\\s]+)(?:\\s+(.*)\\s*?)?$", options: []) func featureDictionary() -> SMTP.Feature { var feature = [String: Any]() // Linux replacingOccurrences will fail when there is \r in string. let entries = replacingOccurrences(of: "\r", with: "").components(separatedBy: "\n") entries.forEach {entry in let match = String.featureMather.groups(in: entry) if match.count == 2 { feature[match[0].lowercased()] = match[1].uppercased() } else if match.count == 1 { feature[match[0].lowercased()] = true } } return SMTP.Feature(feature) } } extension SMTP.Feature { func supported(auth: SMTP.AuthMethod) -> Bool { if let supported = data["auth"] as? String { return supported.contains(auth.rawValue) } return false } func supported(_ key: String) -> Bool { guard let result = data[key.lowercased()] else { return false } return result as? Bool ?? false } func value(for key: String) -> String? { return data[key.lowercased()] as? String } var canStartTLS: Bool { return supported("STARTTLS") } }
mit
88885c4b3f69599f2d229f13537b7ffb
32.013972
161
0.571644
4.772072
false
false
false
false
larryhou/swift
VisionPower/VisionPower/PhotoSelectViewController.swift
1
5702
// // ImagePickViewController.swift // VisionPower // // Created by larryhou on 15/09/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import Photos import UIKit class PhotoCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var requestID: PHImageRequestID = -1 } class AlbumPreviewViewLayout: UICollectionViewFlowLayout { var grid:(size: CGFloat, spacing: CGFloat, column: Int) = (CGFloat.nan, CGFloat.nan, 0) private func fitgrid(dimension: CGFloat, rangeSize:(min: CGFloat, max: CGFloat) = (50, 100), rangeSpacing:(min: CGFloat, max: CGFloat) = (1, 5)) -> (size: CGFloat, spacing: CGFloat, column: Int) { var size = rangeSize.max var spacing = rangeSpacing.min while true { let num = floor(dimension / size) let remain = dimension - num * size - (num + 1) * spacing if remain < 0 { size -= 1 } else if remain > 0 { let value = (dimension - num * size) / (num + 1) if value < rangeSpacing.max { spacing = value break } size -= 1 } else { break } } let column = (dimension - spacing) / (spacing + size) return (size, spacing, Int(column)) } override func prepare() { super.prepare() grid = fitgrid(dimension: collectionView!.frame.width) print("grid", grid) self.itemSize = CGSize(width: grid.size, height: grid.size) self.sectionInset = UIEdgeInsets(top: grid.spacing, left: grid.spacing, bottom: grid.spacing, right: grid.spacing) self.minimumInteritemSpacing = 0 self.minimumLineSpacing = grid.spacing } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if var elements = super.layoutAttributesForElements(in: rect), elements.count >= 1 { for i in 1..<elements.count { let item = elements[i] let prev = elements[i - 1] let start = prev.frame.maxX if start + grid.spacing + item.frame.size.width < collectionViewContentSize.width { var frame = item.frame frame.origin.x = start + grid.spacing item.frame = frame } } return elements } return nil } } protocol PhotoSelectViewControllerDelegate { func didSelectPhoto(_ asset: PHAsset) } class PhotoSelectViewController: UIViewController { private static var shared: PhotoSelectViewController! public static func instantiate(from storyboard: UIStoryboard, delegate: PhotoSelectViewControllerDelegate? = nil) -> PhotoSelectViewController { if shared == nil { shared = (storyboard.instantiateViewController(withIdentifier: "PhotoSelectViewController") as? PhotoSelectViewController)! shared.delegate = delegate } return shared } var assets: [PHAsset] = [] var imageManager: PHCachingImageManager! var delegate: PhotoSelectViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() imageManager = PHCachingImageManager() let fetchOptions = PHFetchOptions() fetchOptions.includeAssetSourceTypes = .typeUserLibrary fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] fetchOptions.includeAllBurstAssets = false let result = PHAsset.fetchAssets(with: .image, options: fetchOptions) for n in 0..<result.count { assets.append(result.object(at: n)) } let cachingOptions = PHImageRequestOptions() cachingOptions.deliveryMode = .fastFormat cachingOptions.isNetworkAccessAllowed = false cachingOptions.resizeMode = .fast cachingOptions.version = .original cachingOptions.isSynchronous = false imageManager.startCachingImages(for: assets, targetSize: CGSize(width: 320, height: 320), contentMode: .default, options: cachingOptions) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } } extension PhotoSelectViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.didSelectPhoto(assets[indexPath.row]) dismiss(animated: true, completion: nil) } } extension PhotoSelectViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return assets.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell // if cell.requestID != -1 // { // imageManager.cancelImageRequest(cell.requestID) // cell.requestID = -1 // } let data = assets[indexPath.row] let options = PHImageRequestOptions() cell.requestID = imageManager.requestImage(for: data, targetSize: CGSize(width: 300, height: 300), contentMode: .default, options: options) { (image, _) in cell.imageView.image = image cell.requestID = -1 } return cell } }
mit
09b6a245f06ac859b1efca9fdcd305e7
33.97546
163
0.63638
5.063055
false
false
false
false
marty-suzuki/QiitaApiClient
QiitaApiClient/Model/QiitaItem.swift
1
2186
// // QiitaItem.swift // QiitaApiClient // // Created by Taiki Suzuki on 2016/08/21. // // import Foundation public class QiitaItem: QiitaModel { public let renderedBody: String public let body: String public let coediting: Bool public let createdAt: NSDate public let group: QiitaGroup? public let id: String public let `private`: Bool public let tags: [QiitaTagging] public let title: String public let updatedAt: NSDate public let url: NSURL public let user: QiitaUser public required init?(dictionary: [String : NSObject]) { guard let renderedBody = dictionary["rendered_body"] as? String, let body = dictionary["body"] as? String, let coediting = dictionary["coediting"] as? Bool, let rawCreatedAt = dictionary["created_at"] as? String, let createdAt = NSDate.dateFromISO8601String(rawCreatedAt), let id = dictionary["id"] as? String, let `private` = dictionary["private"] as? Bool, let rawTags = dictionary["tags"] as? [[String : NSObject]], let title = dictionary["title"] as? String, let rawUpdatedAt = dictionary["updated_at"] as? String, let updatedAt = NSDate.dateFromISO8601String(rawUpdatedAt), let rawUrl = dictionary["url"] as? String, let url = NSURL(string: rawUrl), let rawUser = dictionary["user"] as? [String : NSObject], let user = QiitaUser(dictionary: rawUser) else { return nil } self.renderedBody = renderedBody self.body = body self.coediting = coediting self.createdAt = createdAt if let rawGroup = dictionary["group"] as? [String : NSObject] { self.group = QiitaGroup(dictionary: rawGroup) } else { self.group = nil } self.id = id self.`private` = `private` let tags: [QiitaTagging] = rawTags.flatMap { QiitaTagging(dictionary: $0) } self.tags = tags self.title = title self.updatedAt = updatedAt self.url = url self.user = user } }
mit
350feb7cbd9dcd09a656e180e4437890
33.714286
83
0.599268
4.39839
false
false
false
false
riasuta/CustomCollecionViewFlowLayout
CustomCollecionViewFlowLayout/CustomCollectionViewFlowLayout.swift
1
3985
// // CustomCollectionViewFlowLayout.swift // CustomCollecionViewFlowLayout // // Created by amitan on 2015/06/20. // Copyright (c) 2015年 amitan. All rights reserved. // import UIKit public class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout { private static let kMaxRow = 3 var maxColumn = kMaxRow var cellPattern:[(sideLength: CGFloat, heightLength:CGFloat, column:CGFloat, row:CGFloat)] = [] private var sectionCells = [[CGRect]]() private var contentSize = CGSizeZero override public func prepareLayout() { super.prepareLayout() sectionCells = [[CGRect]]() if let collectionView = self.collectionView { contentSize = CGSize(width: collectionView.bounds.width - collectionView.contentInset.left - collectionView.contentInset.right, height: 0) let smallCellSideLength: CGFloat = (contentSize.width - super.sectionInset.left - super.sectionInset.right - (super.minimumInteritemSpacing * (CGFloat(maxColumn) - 1.0))) / CGFloat(maxColumn) for section in (0..<collectionView.numberOfSections()) { var cells = [CGRect]() var numberOfCellsInSection = collectionView.numberOfItemsInSection(section); var height = contentSize.height for i in (0..<numberOfCellsInSection) { let position = i % (numberOfCellsInSection) let cellPosition = position % cellPattern.count let cell = cellPattern[cellPosition] let x = (cell.column * (smallCellSideLength + super.minimumInteritemSpacing)) + super.sectionInset.left let y = (cell.row * (smallCellSideLength + super.minimumLineSpacing)) + contentSize.height + super.sectionInset.top let cellwidth = (cell.sideLength * smallCellSideLength) + ((cell.sideLength-1) * super.minimumInteritemSpacing) let cellheight = (cell.heightLength * smallCellSideLength) + ((cell.heightLength-1) * super.minimumLineSpacing) let cellRect = CGRectMake(x, y, cellwidth, cellheight) cells.append(cellRect) if (height < cellRect.origin.y + cellRect.height) { height = cellRect.origin.y + cellRect.height } } contentSize = CGSize(width: contentSize.width, height: height) sectionCells.append(cells) } } } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() if let collectionView = self.collectionView { for (var i = 0 ;i<collectionView.numberOfSections(); i++) { var sectionIndexPath = NSIndexPath(forItem: 0, inSection: i) var numberOfCellsInSection = collectionView.numberOfItemsInSection(i); for (var j = 0; j<numberOfCellsInSection; j++) { let indexPath = NSIndexPath(forRow:j, inSection:i) if let attributes = layoutAttributesForItemAtIndexPath(indexPath) { if (CGRectIntersectsRect(rect, attributes.frame)) { layoutAttributes.append(attributes) } } } } } return layoutAttributes } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var attributes = super.layoutAttributesForItemAtIndexPath(indexPath) attributes.frame = sectionCells[indexPath.section][indexPath.row] return attributes } override public func collectionViewContentSize() -> CGSize { return contentSize } }
apache-2.0
1bf3ddff78ba12ec25d3cf6e13f93f29
45.858824
203
0.607833
5.617772
false
false
false
false
shajrawi/swift
test/Constraints/keyword_arguments.swift
1
14476
// RUN: %target-typecheck-verify-swift // Single extraneous keyword argument (tuple-to-scalar) func f1(_ a: Int) { } f1(a: 5) // expected-error{{extraneous argument label 'a:' in call}}{{4-7=}} struct X1 { init(_ a: Int) { } func f1(_ a: Int) {} } X1(a: 5).f1(b: 5) // expected-error@-1 {{extraneous argument label 'a:' in call}} {{4-7=}} // expected-error@-2 {{extraneous argument label 'b:' in call}} {{13-16=}} // <rdar://problem/16801056> enum Policy { case Head(Int) } func extra2(x: Int, y: Int) { } func testExtra2(_ policy : Policy) { switch (policy) { case .Head(let count): extra2(x: 0, y: count) } } // Single missing keyword argument (scalar-to-tuple) func f2(a: Int) { } f2(5) // expected-error{{missing argument label 'a:' in call}}{{4-4=a: }} struct X2 { init(a: Int) { } func f2(b: Int) { } } X2(5).f2(5) // expected-error@-1 {{missing argument label 'a:' in call}} {{4-4=a: }} // expected-error@-2 {{missing argument label 'b:' in call}} {{10-10=b: }} // ------------------------------------------- // Missing keywords // ------------------------------------------- func allkeywords1(x: Int, y: Int) { } // Missing keywords. allkeywords1(1, 2) // expected-error{{missing argument labels}} {{14-14=x: }} {{17-17=y: }} allkeywords1(x: 1, 2) // expected-error{{missing argument label 'y:' in call}} {{20-20=y: }} allkeywords1(1, y: 2) // expected-error{{missing argument label 'x:' in call}} {{14-14=x: }} // If keyword is reserved, make sure to quote it. rdar://problem/21392294 func reservedLabel(_ x: Int, `repeat`: Bool) {} reservedLabel(1, true) // expected-error{{missing argument label 'repeat:' in call}}{{18-18=repeat: }} // Insert missing keyword before initial backtick. rdar://problem/21392294 part 2 func reservedExpr(_ x: Int, y: Int) {} let `do` = 2 reservedExpr(1, `do`) // expected-error{{missing argument label 'y:' in call}}{{17-17=y: }} reservedExpr(1, y: `do`) class GenericCtor<U> { init<T>(t : T) {} // expected-note {{'init(t:)' declared here}} } GenericCtor<Int>() // expected-error{{missing argument for parameter 't' in call}} // ------------------------------------------- // Extraneous keywords // ------------------------------------------- func nokeywords1(_ x: Int, _ y: Int) { } nokeywords1(x: 1, y: 1) // expected-error{{extraneous argument labels 'x:y:' in call}}{{13-16=}}{{19-22=}} // ------------------------------------------- // Some missing, some extraneous keywords // ------------------------------------------- func somekeywords1(_ x: Int, y: Int, z: Int) { } somekeywords1(x: 1, y: 2, z: 3) // expected-error{{extraneous argument label 'x:' in call}}{{15-18=}} somekeywords1(1, 2, 3) // expected-error{{missing argument labels 'y:z:' in call}}{{18-18=y: }}{{21-21=z: }} somekeywords1(x: 1, 2, z: 3) // expected-error{{incorrect argument labels in call (have 'x:_:z:', expected '_:y:z:')}}{{15-18=}}{{21-21=y: }} // ------------------------------------------- // Out-of-order keywords // ------------------------------------------- allkeywords1(y: 1, x: 2) // expected-error{{argument 'x' must precede argument 'y'}} {{14-14=x: 2, }} {{18-24=}} // ------------------------------------------- // Default arguments // ------------------------------------------- func defargs1(x: Int = 1, y: Int = 2, z: Int = 3) {} // Using defaults (in-order) defargs1() defargs1(x: 1) defargs1(x: 1, y: 2) // Using defaults (in-order, some missing) defargs1(y: 2) defargs1(y: 2, z: 3) defargs1(z: 3) defargs1(x: 1, z: 3) // Using defaults (out-of-order, error by SE-0060) defargs1(z: 3, y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{10-10=x: 1, }} {{20-26=}} defargs1(x: 1, z: 3, y: 2) // expected-error{{argument 'y' must precede argument 'z'}} {{16-16=y: 2, }} {{20-26=}} defargs1(y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'y'}} {{10-10=x: 1, }} {{14-20=}} // Default arguments "boxed in". func defargs2(first: Int, x: Int = 1, y: Int = 2, z: Int = 3, last: Int) { } // Using defaults in the middle (in-order, some missing) defargs2(first: 1, x: 1, z: 3, last: 4) defargs2(first: 1, x: 1, last: 4) defargs2(first: 1, y: 2, z: 3, last: 4) defargs2(first: 1, last: 4) // Using defaults in the middle (out-of-order, error by SE-0060) defargs2(first: 1, z: 3, x: 1, last: 4) // expected-error{{argument 'x' must precede argument 'z'}} {{20-20=x: 1, }} {{24-30=}} defargs2(first: 1, z: 3, y: 2, last: 4) // expected-error{{argument 'y' must precede argument 'z'}} {{20-20=y: 2, }} {{24-30=}} // Using defaults that have moved past a non-defaulted parameter defargs2(x: 1, first: 1, last: 4) // expected-error{{argument 'first' must precede argument 'x'}} {{10-10=first: 1, }} {{14-24=}} defargs2(first: 1, last: 4, x: 1) // expected-error{{argument 'x' must precede argument 'last'}} {{20-20=x: 1, }} {{27-33=}} // ------------------------------------------- // Variadics // ------------------------------------------- func variadics1(x: Int, y: Int, _ z: Int...) { } // Using variadics (in-order, complete) variadics1(x: 1, y: 2) variadics1(x: 1, y: 2, 1) variadics1(x: 1, y: 2, 1, 2) variadics1(x: 1, y: 2, 1, 2, 3) // Using various (out-of-order) variadics1(1, 2, 3, 4, 5, x: 6, y: 7) // expected-error {{incorrect argument labels in call (have '_:_:_:_:_:x:y:', expected 'x:y:_:')}} {{12-12=x: }} {{15-15=y: }} {{27-30=}} {{33-36=}} func variadics2(x: Int, y: Int = 2, z: Int...) { } // expected-note {{'variadics2(x:y:z:)' declared here}} // Using variadics (in-order, complete) variadics2(x: 1, y: 2, z: 1) variadics2(x: 1, y: 2, z: 1, 2) variadics2(x: 1, y: 2, z: 1, 2, 3) // Using variadics (in-order, some missing) variadics2(x: 1, z: 1, 2, 3) variadics2(x: 1) // Using variadics (out-of-order) variadics2(z: 1, 2, 3, y: 2) // expected-error{{missing argument for parameter 'x' in call}} variadics2(z: 1, 2, 3, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{22-28=}} func variadics3(_ x: Int..., y: Int = 2, z: Int = 3) { } // Using variadics (in-order, complete) variadics3(1, 2, 3, y: 0, z: 1) variadics3(1, y: 0, z: 1) variadics3(y: 0, z: 1) // Using variadics (in-order, some missing) variadics3(1, 2, 3, y: 0) variadics3(1, z: 1) variadics3(z: 1) variadics3(1, 2, 3, z: 1) variadics3(1, z: 1) variadics3(z: 1) variadics3(1, 2, 3) variadics3(1) variadics3() // Using variadics (out-of-order) variadics3(y: 0, 1, 2, 3) // expected-error{{unnamed argument #2 must precede argument 'y'}} {{12-12=1, 2, 3, }} {{16-25=}} variadics3(z: 1, 1) // expected-error{{unnamed argument #2 must precede argument 'z'}} {{12-12=1, }} {{16-19=}} func variadics4(x: Int..., y: Int = 2, z: Int = 3) { } // Using variadics (in-order, complete) variadics4(x: 1, 2, 3, y: 0, z: 1) variadics4(x: 1, y: 0, z: 1) variadics4(y: 0, z: 1) // Using variadics (in-order, some missing) variadics4(x: 1, 2, 3, y: 0) variadics4(x: 1, z: 1) variadics4(z: 1) variadics4(x: 1, 2, 3, z: 1) variadics4(x: 1, z: 1) variadics4(z: 1) variadics4(x: 1, 2, 3) variadics4(x: 1) variadics4() // Using variadics (in-order, some missing) variadics4(y: 0, x: 1, 2, 3) // expected-error{{argument 'x' must precede argument 'y'}} {{12-12=x: 1, 2, 3, }} {{16-28=}} variadics4(z: 1, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{16-22=}} func variadics5(_ x: Int, y: Int, _ z: Int...) { } // expected-note {{declared here}} // Using variadics (in-order, complete) variadics5(1, y: 2) variadics5(1, y: 2, 1) variadics5(1, y: 2, 1, 2) variadics5(1, y: 2, 1, 2, 3) // Using various (out-of-order) variadics5(1, 2, 3, 4, 5, 6, y: 7) // expected-error{{argument 'y' must precede unnamed argument #2}} {{15-15=y: 7, }} {{28-34=}} variadics5(y: 1, 2, 3, 4, 5, 6, 7) // expected-error{{missing argument for parameter #1 in call}} func variadics6(x: Int..., y: Int = 2, z: Int) { } // expected-note 4 {{'variadics6(x:y:z:)' declared here}} // Using variadics (in-order, complete) variadics6(x: 1, 2, 3, y: 0, z: 1) variadics6(x: 1, y: 0, z: 1) variadics6(y: 0, z: 1) // Using variadics (in-order, some missing) variadics6(x: 1, 2, 3, y: 0) // expected-error{{missing argument for parameter 'z' in call}} variadics6(x: 1, z: 1) variadics6(z: 1) variadics6(x: 1, 2, 3, z: 1) variadics6(x: 1, z: 1) variadics6(z: 1) variadics6(x: 1, 2, 3) // expected-error{{missing argument for parameter 'z' in call}} variadics6(x: 1) // expected-error{{missing argument for parameter 'z' in call}} variadics6() // expected-error{{missing argument for parameter 'z' in call}} func outOfOrder(_ a : Int, b: Int) { outOfOrder(b: 42, 52) // expected-error {{unnamed argument #2 must precede argument 'b'}} {{14-14=52, }} {{19-23=}} } // ------------------------------------------- // Missing arguments // ------------------------------------------- // FIXME: Diagnostics could be improved with all missing names, or // simply # of arguments required. func missingargs1(x: Int, y: Int, z: Int) {} // expected-note {{'missingargs1(x:y:z:)' declared here}} missingargs1(x: 1, y: 2) // expected-error{{missing argument for parameter 'z' in call}} func missingargs2(x: Int, y: Int, _ z: Int) {} // expected-note {{'missingargs2(x:y:_:)' declared here}} missingargs2(x: 1, y: 2) // expected-error{{missing argument for parameter #3 in call}} // ------------------------------------------- // Extra arguments // ------------------------------------------- // FIXME: Diagnostics could be improved with all extra arguments and // note pointing to the declaration being called. func extraargs1(x: Int) {} extraargs1(x: 1, y: 2) // expected-error{{extra argument 'y' in call}} extraargs1(x: 1, 2, 3) // expected-error{{extra argument in call}} // ------------------------------------------- // Argument name mismatch // ------------------------------------------- func mismatch1(thisFoo: Int = 0, bar: Int = 0, wibble: Int = 0) { } mismatch1(foo: 5) // expected-error {{extra argument 'foo' in call}} mismatch1(baz: 1, wobble: 2) // expected-error{{incorrect argument labels in call (have 'baz:wobble:', expected 'bar:wibble:')}} {{11-14=bar}} {{19-25=wibble}} mismatch1(food: 1, zap: 2) // expected-error{{extra argument 'food' in call}} // ------------------------------------------- // Subscript keyword arguments // ------------------------------------------- struct Sub1 { subscript (i: Int) -> Int { get { return i } } } var sub1 = Sub1() var i: Int = 0 i = sub1[i] i = sub1[i: i] // expected-error{{extraneous argument label 'i:' in subscript}} {{10-13=}} struct Sub2 { subscript (d d: Double) -> Double { get { return d } } } var sub2 = Sub2() var d: Double = 0.0 d = sub2[d] // expected-error{{missing argument label 'd:' in subscript}} {{10-10=d: }} d = sub2[d: d] d = sub2[f: d] // expected-error{{incorrect argument label in subscript (have 'f:', expected 'd:')}} {{10-11=d}} // ------------------------------------------- // Closures // ------------------------------------------- func intToInt(_ i: Int) -> Int { return i } func testClosures() { let c0 = { (x: Int, y: Int) in x + y } _ = c0(1, 2) let c1 = { x, y in intToInt(x + y) } _ = c1(1, 2) let c2 = { intToInt($0 + $1) } _ = c2(1, 2) } func acceptAutoclosure(f: @autoclosure () -> Int) { } func produceInt() -> Int { } acceptAutoclosure(f: produceInt) // expected-error{{add () to forward @autoclosure parameter}} {{32-32=()}} // ------------------------------------------- // Trailing closures // ------------------------------------------- func trailingclosure1(x: Int, f: () -> Int) {} trailingclosure1(x: 1) { return 5 } trailingclosure1(1) { return 5 } // expected-error{{missing argument label 'x:' in call}}{{18-18=x: }} trailingclosure1(x: 1, { return 5 }) // expected-error{{missing argument label 'f:' in call}} {{24-24=f: }} func trailingclosure2(x: Int, f: (() -> Int)?...) {} trailingclosure2(x: 5) { return 5 } func trailingclosure3(x: Int, f: (() -> Int)!) { var f = f f = nil _ = f } trailingclosure3(x: 5) { return 5 } func trailingclosure4(f: () -> Int) {} trailingclosure4 { 5 } func trailingClosure5<T>(_ file: String = #file, line: UInt = #line, expression: () -> T?) { } func trailingClosure6<T>(value: Int, expression: () -> T?) { } trailingClosure5(file: "hello", line: 17) { return Optional.Some(5) } // expected-error{{extraneous argument label 'file:' in call}}{{18-24=}} trailingClosure6(5) { return Optional.Some(5) } // expected-error{{missing argument label 'value:' in call}}{{18-18=value: }} class MismatchOverloaded1 { func method1(_ x: Int!, arg: ((Int) -> Int)!) { } func method1(_ x: Int!, secondArg: ((Int) -> Int)!) { } @available(*, unavailable) func method2(_ x: Int!, arg: ((Int) -> Int)!) { } func method2(_ x: Int!, secondArg: ((Int) -> Int)!) { } } var mismatchOverloaded1 = MismatchOverloaded1() mismatchOverloaded1.method1(5, arg: nil) mismatchOverloaded1.method1(5, secondArg: nil) // Prefer available to unavailable declaration, if it comes up. mismatchOverloaded1.method2(5) { $0 } // ------------------------------------------- // Values of function type // ------------------------------------------- func testValuesOfFunctionType(_ f1: (_: Int, _ arg: Int) -> () ) { f1(3, arg: 5) // expected-error{{extraneous argument label 'arg:' in call}}{{9-14=}} f1(x: 3, 5) // expected-error{{extraneous argument label 'x:' in call}} {{6-9=}} f1(3, 5) } // ------------------------------------------- // Literals // ------------------------------------------- func string_literals1(x: String) { } string_literals1(x: "hello") func int_literals1(x: Int) { } int_literals1(x: 1) func float_literals1(x: Double) { } float_literals1(x: 5) // ------------------------------------------- // Tuples as arguments // ------------------------------------------- func produceTuple1() -> (Int, Bool) { return (1, true) } func acceptTuple1<T>(_ x: (T, Bool)) { } acceptTuple1(produceTuple1()) acceptTuple1((1, false)) acceptTuple1(1, false) // expected-error {{global function 'acceptTuple1' expects a single parameter of type '(T, Bool)'}} {{14-14=(}} {{22-22=)}} func acceptTuple2<T>(_ input : T) -> T { return input } var tuple1 = (1, "hello") _ = acceptTuple2(tuple1) _ = acceptTuple2((1, "hello", 3.14159)) func generic_and_missing_label(x: Int) {} func generic_and_missing_label<T>(x: T) {} generic_and_missing_label(42) // expected-error@-1 {{missing argument label 'x:' in call}} {{27-27=x: }}
apache-2.0
a8a39bfcfec9419da77ae033f7fb938e
34.135922
186
0.569494
2.919726
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/BeLogical.swift
56
3472
import Foundation internal func matcherWithFailureMessage<T>(matcher: NonNilMatcherFunc<T>, postprocessor: (FailureMessage) -> Void) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in defer { postprocessor(failureMessage) } return try matcher.matcher(actualExpression, failureMessage) } } // MARK: beTrue() / beFalse() /// A Nimble matcher that succeeds when the actual value is exactly true. /// This matcher will not match against nils. public func beTrue() -> NonNilMatcherFunc<Bool> { return matcherWithFailureMessage(equal(true)) { failureMessage in failureMessage.postfixMessage = "be true" } } /// A Nimble matcher that succeeds when the actual value is exactly false. /// This matcher will not match against nils. public func beFalse() -> NonNilMatcherFunc<Bool> { return matcherWithFailureMessage(equal(false)) { failureMessage in failureMessage.postfixMessage = "be false" } } // MARK: beTruthy() / beFalsy() /// A Nimble matcher that succeeds when the actual value is not logically false. public func beTruthy<T>() -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be truthy" let actualValue = try actualExpression.evaluate() if let actualValue = actualValue { if let actualValue = actualValue as? BooleanType { return actualValue.boolValue == true } } return actualValue != nil } } /// A Nimble matcher that succeeds when the actual value is logically false. /// This matcher will match against nils. public func beFalsy<T>() -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be falsy" let actualValue = try actualExpression.evaluate() if let actualValue = actualValue { if let actualValue = actualValue as? BooleanType { return actualValue.boolValue != true } } return actualValue == nil } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func beTruthyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualExpression, failureMessage in let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? } return try! beTruthy().matches(expr, failureMessage: failureMessage) } } public class func beFalsyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualExpression, failureMessage in let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? } return try! beFalsy().matches(expr, failureMessage: failureMessage) } } public class func beTrueMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualExpression, failureMessage in let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? } return try! beTrue().matches(expr, failureMessage: failureMessage) } } public class func beFalseMatcher() -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? } return try! beFalse().matches(expr, failureMessage: failureMessage) } } } #endif
apache-2.0
8c448b8a119917ecc01b6a0c23717e56
38.011236
140
0.675979
5.244713
false
false
false
false
quadro5/swift3_L
swift_question.playground/Pages/let8 String to Integer (atoi) .xcplaygroundpage/Contents.swift
1
3768
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) // Int overflow /* when you specifically want an overflow condition to truncate the number of available bits, you can opt in to this behavior rather than triggering an error. Swift provides three arithmetic overflow operators that opt in to the overflow behavior for integer calculations. These operators all begin with an ampersand (&): Overflow addition (&+) Overflow subtraction (&-) Overflow multiplication (&*) https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID37 */ class Solution { func myAtoi(_ str: String) -> Int { if str.isEmpty { return 0 } var res: Int = 0 let s = "0" let base = Array(s.utf8)[0] let array = Array(str.utf8) //let len = array.count for ch in array { let digit = Int(ch - base) res = res &* 10 if (res == 0) { return res } res = res &+ digit if (res < 0) { return 0 } } return res } } let input = "123333333333333333333333333333333333333333" let res = Solution().myAtoi(input) // leetcode version class Solution2 { func myAtoi(_ str: String) -> Int { if str.isEmpty { return 0 } var res: Int64 = 0 let s = "09+- " let base = Array(s.utf8) let array = Array(str.utf8) let len = array.count var start = 0 var isPositive: Bool = true // trim space while start < len && array[start] == base[4] { start += 1 } // validate start if start >= len { return 0 } // validate sign if array[start] == base[2] { isPositive = true start += 1 } else if array[start] == base[3] { isPositive = false start += 1 } // searching for pure num for index in start..<len { let cur = array[index] // validate utf8 num if cur < base[0] || cur > base[1] { break } // get digit let digit = Int(cur - base[0]) // validate with overflow // res = res * 10 + digit res = res * 10 + Int64(digit) if res > Int64(Int32.max), isPositive { return Int(Int32.max) } if res > Int64(Int32.max), isPositive == false { return Int(Int32.min) } } if isPositive == false { return Int(-res) } return Int(res) } } // Roman to Integer func romanToInteger(str: String) -> Int { let nums = str.characters.map { String($0) } let len = nums.count if nums.isEmpty { return 0 } var res = 0 var prev = 0 var cur = mapRomanToInt(nums[0]) res += cur var index = 1 while index < len { prev = cur cur = mapRomanToInt(nums[index]) if prev < cur { res += (cur - prev - prev) // minus prev one twice, // one time has been add to res // one time has contained by cur } else { res += cur } index += 1 } return res } private func mapRomanToInt(_ s: String) -> Int { switch s { case "I": return 1 case "V": return 5 case "X": return 10 default: return 0 } } let roman = "IV" let resRoman = romanToInteger(str: roman)
unlicense
d29be890be4c73eef135223b782cc871
22.698113
321
0.506635
4.154355
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Playback.playground/Pages/Sequencer.xcplaygroundpage/Contents.swift
2
3432
//: ## Sequencer //: import XCPlayground import AudioKit //: Create some samplers, load different sounds, and connect it to a mixer and the output var fmPianoSampler = AKSampler() fmPianoSampler.loadWav("FM Piano") var bellSampler = AKSampler() bellSampler.loadWav("Bell") var mixer = AKMixer(fmPianoSampler, bellSampler) let reverb = AKCostelloReverb(mixer) let dryWetmixer = AKDryWetMixer(mixer, reverb, balance: 0.2) AudioKit.output = dryWetmixer //: Create the sequencer after AudioKit's output has been set //: Load in a midi file, and set the sequencer to the main audiokit engine var sequencer = AKSequencer(filename: "4tracks", engine: AudioKit.engine) //: Do some basic setup to make the sequence loop correctly sequencer.setLength(AKDuration(beats: 4)) sequencer.enableLooping() AudioKit.start() sequencer.play() //: Set up a basic UI for setting outputs of tracks class PlaygroundView: AKPlaygroundView { var button1: AKButton? var button2: AKButton? var button3: AKButton? var button4: AKButton? override func setup() { addTitle("Sequencer") addLabel("Set the global output for the sequencer:") addSubview(AKButton(title: "Use FM Piano As Global Output") { sequencer.stop() sequencer.setGlobalAVAudioUnitOutput(fmPianoSampler.samplerUnit) self.updateButtons() sequencer.play() return "" }) addSubview(AKButton(title: "Use Bell As Global Output", color: AKColor.redColor()) { sequencer.stop() sequencer.setGlobalAVAudioUnitOutput(bellSampler.samplerUnit) self.updateButtons() sequencer.play() return "" }) addLabel("Or set the tracks individually:") button1 = AKButton(title: "Track 1: FM Piano") { self.toggleTrack(1) return "" } button2 = AKButton(title: "Track 2: FM Piano") { self.toggleTrack(2) return "" } button3 = AKButton(title: "Track 3: FM Piano") { self.toggleTrack(3) return "" } button4 = AKButton(title: "Track 4: FM Piano") { self.toggleTrack(4) return "" } addSubview(button1!) addSubview(button2!) addSubview(button3!) addSubview(button4!) } func toggleTrack(trackNumber: Int) { sequencer.stop() if sequencer.avTracks[trackNumber].destinationAudioUnit == bellSampler.samplerUnit { sequencer.avTracks[trackNumber].destinationAudioUnit = fmPianoSampler.samplerUnit } else { sequencer.avTracks[trackNumber].destinationAudioUnit = bellSampler.samplerUnit } updateButtons() } func updateButtons() { let buttons = [button1!, button2!, button3!, button4!] for i in 0 ..< buttons.count { if sequencer.avTracks[i + 1].destinationAudioUnit == bellSampler.samplerUnit { buttons[i].title = "Track \(i + 1): Bell" buttons[i].color = AKColor.redColor() } else { buttons[i].title = "Track \(i + 1): FM Piano" buttons[i].color = AKColor.greenColor() } } sequencer.play() } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
a25064e43b71f4019db3fd11e1833f28
30.486239
93
0.626457
4.34981
false
false
false
false
AChildFromBUAA/PracticePlace
TestPractice/PageViewController.swift
1
2667
// // PageViewController.swift // TestPractice // // Created by kyz on 15/10/13. // Copyright © 2015年 BUAA.Software. All rights reserved. // import UIKit enum DirectionForward : Int { case Before = 1 case After = 2 } class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var pageIndex = 0 var directionForward = DirectionForward.After override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.dataSource = self let mainStoryBoard = self.storyboard! let pageViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("page1") as UIViewController let viewControllers: NSArray = [pageViewController] self.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil) self.view.addSubview(pageViewController.view) } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { pageIndex-- if pageIndex < 0 { pageIndex = 0 return nil } directionForward = DirectionForward.Before let mainStoryBoard = self.storyboard! let pageId = NSString(format: "page%i", pageIndex + 1) let pvController = mainStoryBoard.instantiateViewControllerWithIdentifier(pageId as String) as UIViewController return pvController } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { pageIndex++ if pageIndex > 2 { pageIndex = 2 return nil } directionForward = DirectionForward.After let mainStoryBoard = self.storyboard! let pageId = NSString(format: "page%i", pageIndex + 1) let pvController = mainStoryBoard.instantiateViewControllerWithIdentifier(pageId as String) as UIViewController return pvController } func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if completed == false { if directionForward == DirectionForward.After { pageIndex-- } if directionForward == DirectionForward.Before { pageIndex++ } } } }
mit
0dd23f0e34e7248549195bbcd743a365
32.3125
188
0.664039
6.20979
false
false
false
false
roambotics/swift
test/Constraints/patterns.swift
4
13895
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{cannot find 'a' in scope}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'any HairType'}} () case Watch.Edition: // expected-warning {{cast from 'any HairType' to unrelated type 'Watch' always fails}} () case .HairForceOne: // expected-error{{type 'any HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{10-11=_}} case nil: break } // https://github.com/apple/swift/issues/44675 func f_44675(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { let _ = a.map { let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { let _ = a.map { switch $0 { case .A: return 1 default: return 2 } } } // https://github.com/apple/swift/issues/44666 do { enum E { case foo } let x: E? if case .foo = x { } // Ok } // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{cannot find type 'AlsoDoesNotExist' in scope}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } static func method(withLabel: Int) -> StaticMembers { return prop } static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} case .prop: break case .optProp: break case .method: break // expected-error{{member 'method' expects argument of type 'Int'}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}} case .optMethod(0): break } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}} case .foo: // Ok break; case .bar: // Ok break; } } // https://github.com/apple/swift/issues/48655 struct One<Two> { // expected-note{{'Two' declared as parameter to type 'One'}} public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic parameter 'Two' could not be inferred}} } } // https://github.com/apple/swift/issues/50875 // Constrain initializer expressions of optional some pattern bindings to // be optional. func test_50875() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { return "" } func h() -> Double { return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } } // https://github.com/apple/swift/issues/50338 do { enum E { case baz case bar } let oe: E? = .bar switch oe { case .bar?: break // Ok case .baz: break // Ok default: break } let ooe: E?? = .baz switch ooe { case .bar?: break // Ok case .baz: break // Ok default: break } if case .baz = ooe {} // Ok if case .bar? = ooe {} // Ok } // rdar://problem/60048356 - `if case` fails when `_` pattern doesn't have a label func rdar_60048356() { typealias Info = (code: ErrorCode, reason: String) enum ErrorCode { case normalClosure } enum Failure { case closed(Info) // expected-note {{'closed' declared here}} } enum Reason { case close(Failure) } func test(_ reason: Reason) { if case .close(.closed((code: .normalClosure, _))) = reason { // Ok } } // rdar://problem/60061646 func test(e: Failure) { if case .closed(code: .normalClosure, _) = e { // Ok // expected-warning@-1 {{enum case 'closed' has one associated value that is a tuple of 2 elements}} } } enum E { case foo((x: Int, y: Int)) // expected-note {{declared here}} case bar(x: Int, y: Int) // expected-note {{declared here}} } func test_destructing(e: E) { if case .foo(let x, let y) = e { // Ok (destructring) // expected-warning@-1 {{enum case 'foo' has one associated value that is a tuple of 2 elements}} _ = x == y } if case .bar(let tuple) = e { // Ok (matching via tuple) // expected-warning@-1 {{enum case 'bar' has 2 associated values; matching them as a tuple is deprecated}} _ = tuple.0 == tuple.1 } } } // rdar://problem/63510989 - valid pattern doesn't type-check func rdar63510989() { enum Value : P { func p() {} } enum E { case single(P?) case double(P??) case triple(P???) } func test(e: E) { if case .single(_) = e {} // Ok if case .single(_ as Value) = e {} // Ok if case .single(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .double(_ as Value) = e {} // Ok if case .double(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .double(let v as Value?) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(_ as Value) = e {} // Ok if case .triple(let v as Value) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(let v as Value?) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} if case .triple(let v as Value??) = e {} // Ok // expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}} } } // rdar://problem/64157451 - compiler crash when using undefined type in pattern func rdar64157451() { enum E { case foo(Int) } func test(e: E) { if case .foo(let v as DoeNotExist) = e {} // expected-error {{cannot find type 'DoeNotExist' in scope}} } } // rdar://80797176 - circular reference incorrectly diagnosed while reaching for a type of a pattern. func rdar80797176 () { for x: Int in [1, 2] where x.bitWidth == 32 { // Ok } } // https://github.com/apple/swift/issues/60029 for (key, values) in oldName { // expected-error{{cannot find 'oldName' in scope}} for (idx, value) in values.enumerated() { print(key, idx, value) } } // https://github.com/apple/swift/issues/60503 func f60503() { let (key, _) = settings.enumerate() // expected-error{{cannot find 'settings' in scope}} let (_, _) = settings.enumerate() // expected-error{{cannot find 'settings' in scope}} }
apache-2.0
2175d9c9ad300e38390888b4a68f6066
24.636531
208
0.624685
3.525755
false
false
false
false
mxcl/swift-package-manager
Tests/BuildTests/DescribeTests.swift
1
3148
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic @testable import Build import PackageDescription import PackageGraph import PackageModel import Utility final class DescribeTests: XCTestCase { let dummyPackage = Package(manifest: Manifest(path: AbsolutePath("/"), url: "/", package: PackageDescription.Package(name: "Foo"), products: [], version: nil), path: AbsolutePath("/"), modules: [], testModules: [], products: []) struct InvalidToolchain: Toolchain { var platformArgsClang: [String] { fatalError() } var platformArgsSwiftc: [String] { fatalError() } var sysroot: String? { fatalError() } var SWIFT_EXEC: String { fatalError() } var clang: String { fatalError() } } func testDescribingNoModulesThrows() { do { let tempDir = try TemporaryDirectory(removeTreeOnDeinit: true) let graph = PackageGraph(rootPackage: dummyPackage, modules: [], externalModules: []) _ = try describe(tempDir.path.appending(component: "foo"), .debug, graph, flags: BuildFlags(), toolchain: InvalidToolchain()) XCTFail("This call should throw") } catch Build.Error.noModules { XCTAssert(true, "This error should be thrown") } catch { XCTFail("No other error should be thrown") } } func testDescribingCModuleThrows() { do { let tempDir = try TemporaryDirectory(removeTreeOnDeinit: true) let graph = PackageGraph(rootPackage: dummyPackage, modules: [try CModule(name: "MyCModule", sources: Sources(paths: [], root: AbsolutePath("/")), path: AbsolutePath("/"))], externalModules: []) _ = try describe(tempDir.path.appending(component: "foo"), .debug, graph, flags: BuildFlags(), toolchain: InvalidToolchain()) XCTFail("This call should throw") } catch Build.Error.onlyCModule (let name) { XCTAssert(true, "This error should be thrown") XCTAssertEqual(name, "MyCModule") } catch { XCTFail("No other error should be thrown") } } func testClangModuleCanHaveSwiftDep() throws { let clangModule = try ClangModule(name: "ClangModule", sources: Sources(paths: [], root: .root)) let swiftModule = try SwiftModule(name: "SwiftModule", sources: Sources(paths: [], root: .root)) clangModule.dependencies = [swiftModule] let buildMeta = ClangModuleBuildMetadata(module: clangModule, prefix: .root, otherArgs: []) XCTAssertEqual(buildMeta.inputs, ["<SwiftModule.module>"]) } static var allTests = [ ("testDescribingNoModulesThrows", testDescribingNoModulesThrows), ("testDescribingCModuleThrows", testDescribingCModuleThrows), ("testClangModuleCanHaveSwiftDep", testClangModuleCanHaveSwiftDep), ] }
apache-2.0
0a9632045911be8df2e63b565b4f32c1
43.338028
232
0.669949
4.698507
false
true
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/NSURL.swift
1
892
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module extension NSURL : _CustomPlaygroundQuickLookable { @available(*, deprecated, message: "NSURL.customPlaygroundQuickLook will be removed in a future Swift version") public var customPlaygroundQuickLook: PlaygroundQuickLook { guard let str = absoluteString else { return .text("Unknown URL") } return .url(str) } }
apache-2.0
6449fac67facd10dba383ba789d16298
41.47619
113
0.61435
5.439024
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPShopRecommendView.swift
1
2858
// // KPShopRecommendView.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/4/18. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPShopRecommendView: UIView { static let KPShopRecommendViewCellReuseIdentifier = "cell" weak open var informationController: KPInformationViewController? var tableView: UITableView! var displayDataModels: [KPDataModel]! { didSet { self.tableView.reloadData() } } override init(frame: CGRect) { super.init(frame: frame) // calls designated initializer self.tableView = UITableView() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.isScrollEnabled = false tableView.separatorColor = UIColor.clear self.addSubview(self.tableView) self.tableView.addConstraints(fromStringArray: ["V:|[$self(420)]|", "H:|[$self]|"]) self.tableView.register(KPMainListTableViewCell.self, forCellReuseIdentifier: KPShopRecommendView.KPShopRecommendViewCellReuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension KPShopRecommendView: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier:KPShopRecommendView.KPShopRecommendViewCellReuseIdentifier, for: indexPath) as! KPMainListTableViewCell cell.selectionStyle = .none cell.dataModel = self.displayDataModels[indexPath.row] return cell } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.displayDataModels.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { KPAnalyticManager.sendCellClickEvent(self.displayDataModels[indexPath.row].name, self.displayDataModels[indexPath.row].rateCount?.stringValue, KPAnalyticsEventValue.source.source_recommend) let controller = KPInformationViewController() controller.informationDataModel = self.displayDataModels[indexPath.row] informationController?.navigationController?.pushViewController(controller, animated: true) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
mit
b1c77f9d139d80fce51b3c3568efc08d
36.077922
123
0.650088
5.631164
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/More Tab/Profile Page/Networking/ProfilePageNetworkManager.swift
1
1951
// // ProfilePageNetworkManager.swift // PennMobile // // Created by Andrew Antenberg on 10/10/21. // Copyright © 2021 PennLabs. All rights reserved. // import Foundation import SwiftyJSON class ProfilePageNetworkManager: NSObject, Requestable { static let instance = ProfilePageNetworkManager() let schoolsURL = "https://platform.pennlabs.org/accounts/schools/" let majorsURL = "https://platform.pennlabs.org/accounts/majors/" func getSchools (completion: @escaping (Result<[School], NetworkingError>) -> Void) { let url = URL(string: self.schoolsURL)! let task = URLSession.shared.dataTask(with: url) { (data, response, _) in if let httpResponse = response as? HTTPURLResponse, let data = data, httpResponse.statusCode == 200 { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase do { let schools = try decoder.decode([School].self, from: data) completion(.success(schools)) } catch { completion(.failure(.parsingError)) } } } task.resume() } func getMajors (completion: @escaping (Result<[Major], NetworkingError>) -> Void) { let url = URL(string: self.majorsURL)! let task = URLSession.shared.dataTask(with: url) { (data, response, _) in if let httpResponse = response as? HTTPURLResponse, let data = data, httpResponse.statusCode == 200 { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase do { let majors = try decoder.decode([Major].self, from: data) completion(.success(majors)) } catch { completion(.failure(.parsingError)) } } } task.resume() } }
mit
32d4753e4e7164f781baceebf5d1d9a0
32.62069
113
0.582051
4.802956
false
false
false
false
XenonXYZ/Swift-Rain
Swift-Rain/WaterController.swift
2
4211
// // WaterController.swift // Physics // // Created by Kiran Kunigiri on 7/18/15. // Copyright (c) 2015 Kiran Kunigiri. All rights reserved. // import Foundation import UIKit class WaterController { // MARK: - Properties // MARK: Views var view: UIView! private var drops: [UIView] = [] private var dropColor = UIColor(red:0.56, green:0.76, blue:0.85, alpha:1.0) // MARK: Drop positions private var startX: CGFloat! private var startY: CGFloat! private var distanceBetweenEachDrop: CGFloat! private var distanceBetweenSameRow: CGFloat! // MARK: Drop behaviors private var animator: UIDynamicAnimator! private var gravityBehavior = UIGravityBehavior() private var timer1 = NSTimer() private var timer2 = NSTimer() // MARK: State var isAnimating = false // MARK: - Methods init(view: UIView) { // Get main view self.view = view let width = self.view.frame.width // Initialize Values for position of raindrops and space between them startX = 20 startY = -60 distanceBetweenEachDrop = width * 0.048 distanceBetweenSameRow = distanceBetweenEachDrop * 2 // Initialize animator animator = UIDynamicAnimator(referenceView: self.view) gravityBehavior.gravityDirection.dy = 2 animator.addBehavior(gravityBehavior) } /** Starts the rain animation */ func start() { isAnimating = true // Timer that calls spawnFirst method every 0.2 second. Produces rain drops every .2 second in 1st and 2rd row timer1 = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(spawnFirst), userInfo: nil, repeats: true) // Timer that calls startSecond method after .1 seconds. Creates a slight delay for 2nd and 4th rows NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(spawnFirst), userInfo: nil, repeats: false) } /** Starts second timer */ private func startSecond() { timer2 = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(spawnFirst), userInfo: nil, repeats: true) } // MARK: - Helper Methods /** Manages all drops in rain */ private func addGravity(array: [UIView]) { // Adds gravity to every drop in array for drop in array { gravityBehavior.addItem(drop) } // Checks if each drop is below the bottom of screen. Then removes its gravity, hides it, and removes from array for var i = 0; i < drops.count; i += 1 { if drops[i].frame.origin.y > self.view.frame.height { gravityBehavior.removeItem(drops[i]) drops[i].removeFromSuperview() drops.removeAtIndex(i) } } } /** Spawns water drops */ @objc private func spawnFirst() { //creates array of UIViews (drops) var thisArray: [UIView] = [] //number of col of drops let numberOfDrops = 3 //for each drop in a row for _ in 0 ..< numberOfDrops { // Create a UIView (a drop). Then set the size, color, and remove border of drop let newY = CGFloat(-200 + Int(arc4random_uniform(UInt32(150)))) let newX = CGFloat(10 + Int(arc4random_uniform(UInt32(350)))) let drop = UIView() drop.frame = CGRectMake(newX, newY, 1.0, 50.0) drop.backgroundColor = dropColor drop.layer.borderWidth = 0.0 // Add the drop to main view self.view.addSubview(drop) // Add the drop to the drops array self.drops.append(drop) // Add the drop to thisArray thisArray.append(drop) } // Adds gravity to the drops that were just created addGravity(thisArray) } /** Stops the water animation */ func stop() { isAnimating = false // Remove all objects from drops array drops.removeAll() // Stop all timers timer1.invalidate() timer2.invalidate() } }
mit
7b1b6b06b8f393bb758c5a10c4e34422
32.967742
137
0.607932
4.484558
false
false
false
false
railsdog/CleanroomLogger
Code/Implementation/DailyRotatingLogFileRecorder.swift
3
7079
// // DailyRotatingLogFileRecorder.swift // Cleanroom Project // // Created by Evan Maloney on 5/14/15. // Copyright (c) 2015 Gilt Groupe. All rights reserved. // import Foundation /** A `LogRecorder` implementation that maintains a set of daily rotating log files, kept for a user-specified number of days. **Important:** The `DailyRotatingLogFileRecorder` is expected to have full control over the `directoryPath` with which it was instantiated. Any file not explicitly known to be an active log file may be removed during the pruning process. Therefore, be careful not to store anything in the `directoryPath` that you wouldn't mind being deleted when pruning occurs. */ public class DailyRotatingLogFileRecorder: LogRecorderBase { /** The number of days for which the receiver will retain log files before they're eligible for pruning. */ public let daysToKeep: Int /** The filesystem path to a directory where the log files will be stored. */ public let directoryPath: String private static let filenameFormatter: NSDateFormatter = { let fmt = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd'.log'" return fmt }() private var mostRecentLogTime: NSDate? private var currentFileRecorder: FileLogRecorder? /** Attempts to initialize a new `DailyRotatingLogFileRecorder` instance. This may fail if the `directoryPath` doesn't already exist as a directory and could not be created. **Important:** The new `DailyRotatingLogFileRecorder` will take responsibility for managing the contents of the `directoryPath`. As part of the automatic pruning process, any file not explicitly known to be an active log file may be removed. Be careful not to put anything in this directory you might not want deleted when pruning occurs. :param: daysToKeep The number of days for which log files should be retained. :param: directoryPath The filesystem path of the directory where the log files will be stores. :param: formatters The `LogFormatter`s to use for the recorder. */ public init(daysToKeep: Int, directoryPath: String, formatters: [LogFormatter] = [DefaultLogFormatter()]) throws { self.daysToKeep = daysToKeep self.directoryPath = directoryPath super.init(name: "DailyRotatingLogFileRecorder[\(directoryPath)]", formatters: formatters) // try to create the directory that will contain the log files let url = NSURL(fileURLWithPath: directoryPath, isDirectory: true) try NSFileManager.defaultManager().createDirectoryAtURL(url, withIntermediateDirectories: true, attributes: nil) } /** Returns a string representing the filename that will be used to store logs recorded on the given date. :param: date The `NSDate` for which the log file name is desired. :returns: The filename. */ public class func logFilenameForDate(date: NSDate) -> String { return filenameFormatter.stringFromDate(date) } private class func fileLogRecorderForDate(date: NSDate, directoryPath: String, formatters: [LogFormatter]) -> FileLogRecorder? { let fileName = self.logFilenameForDate(date) let filePath = directoryPath.stringByAppendingPathComponent(fileName) return FileLogRecorder(filePath: filePath, formatters: formatters) } private func fileLogRecorderForDate(date: NSDate) -> FileLogRecorder? { return self.dynamicType.fileLogRecorderForDate(date, directoryPath: directoryPath, formatters: formatters) } private func isDate(firstDate: NSDate, onSameDayAs secondDate: NSDate) -> Bool { let firstDateStr = self.dynamicType.logFilenameForDate(firstDate) let secondDateStr = self.dynamicType.logFilenameForDate(secondDate) return firstDateStr == secondDateStr } /** Called by the `LogReceptacle` to record the specified log message. **Note:** This function is only called if one of the `formatters` associated with the receiver returned a non-`nil` string. :param: message The message to record. :param: entry The `LogEntry` for which `message` was created. :param: currentQueue The GCD queue on which the function is being executed. :param: synchronousMode If `true`, the receiver should record the log entry synchronously. Synchronous mode is used during debugging to help ensure that logs reflect the latest state when debug breakpoints are hit. It is not recommended for production code. */ public override func recordFormattedMessage(message: String, forLogEntry entry: LogEntry, currentQueue: dispatch_queue_t, synchronousMode: Bool) { if mostRecentLogTime == nil || !self.isDate(entry.timestamp, onSameDayAs: mostRecentLogTime!) { prune() currentFileRecorder = fileLogRecorderForDate(entry.timestamp) } mostRecentLogTime = entry.timestamp currentFileRecorder?.recordFormattedMessage(message, forLogEntry: entry, currentQueue: queue, synchronousMode: synchronousMode) } /** Deletes any expired log files (and any other detritus that may be hanging around inside our `directoryPath`). **Important:** The `DailyRotatingLogFileRecorder` is expected to have full ownership over its `directoryPath`. Any file not explicitly known to be an active log file may be removed during the pruning process. Therefore, be careful not to store anything in this directory that you wouldn't mind being deleted when pruning occurs. */ public func prune() { // figure out what files we'd want to keep, then nuke everything else let cal = NSCalendar.currentCalendar() var date = NSDate() var filesToKeep = Set<String>() for _ in 0..<daysToKeep { let filename = self.dynamicType.logFilenameForDate(date) filesToKeep.insert(filename) date = cal.dateByAddingUnit(.Day, value: -1, toDate: date, options: .WrapComponents)! } do { let fileMgr = NSFileManager.defaultManager() let filenames = try fileMgr.contentsOfDirectoryAtPath(directoryPath) let pathsToRemove = filenames .filter { return !$0.hasPrefix(".") } .filter { return !filesToKeep.contains($0) } .map { return self.directoryPath.stringByAppendingPathComponent($0) } for path in pathsToRemove { do { try fileMgr.removeItemAtPath(path) } catch { print("Error attempting to delete the unneeded file <\(path)>: \(error)") } } } catch { print("Error attempting to read directory at path <\(directoryPath)>: \(error)") } } }
mit
af162c43c1384f18edcaf9783641144c
37.472826
148
0.674248
5.060043
false
false
false
false
jopamer/swift
stdlib/public/core/SliceBuffer.swift
1
13238
//===--- SliceBuffer.swift - Backing storage for ArraySlice<Element> ------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Buffer type for `ArraySlice<Element>`. @_fixed_layout @usableFromInline internal struct _SliceBuffer<Element> : _ArrayBufferProtocol, RandomAccessCollection { internal typealias NativeStorage = _ContiguousArrayStorage<Element> @usableFromInline internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @inlinable internal init( owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>, indices: Range<Int>, hasNativeBuffer: Bool ) { self.owner = owner self.subscriptBaseAddress = subscriptBaseAddress self.startIndex = indices.lowerBound let bufferFlag = UInt(hasNativeBuffer ? 1 : 0) self.endIndexAndFlags = (UInt(indices.upperBound) << 1) | bufferFlag _invariantCheck() } @inlinable internal init() { let empty = _ContiguousArrayBuffer<Element>() self.owner = empty.owner self.subscriptBaseAddress = empty.firstElementAddress self.startIndex = empty.startIndex self.endIndexAndFlags = 1 _invariantCheck() } @inlinable internal init(_buffer buffer: NativeBuffer, shiftedToStartIndex: Int) { let shift = buffer.startIndex - shiftedToStartIndex self.init( owner: buffer.owner, subscriptBaseAddress: buffer.subscriptBaseAddress + shift, indices: shiftedToStartIndex..<shiftedToStartIndex + buffer.count, hasNativeBuffer: true) } @inlinable // FIXME(sil-serialize-all) internal func _invariantCheck() { let isNative = _hasNativeBuffer let isNativeStorage: Bool = owner is _ContiguousArrayStorageBase _sanityCheck(isNativeStorage == isNative) if isNative { _sanityCheck(count <= nativeBuffer.count) } } @inlinable // FIXME(sil-serialize-all) internal var _hasNativeBuffer: Bool { return (endIndexAndFlags & 1) != 0 } @inlinable // FIXME(sil-serialize-all) internal var nativeBuffer: NativeBuffer { _sanityCheck(_hasNativeBuffer) return NativeBuffer( owner as? _ContiguousArrayStorageBase ?? _emptyArrayStorage) } @inlinable // FIXME(sil-serialize-all) internal var nativeOwner: AnyObject { _sanityCheck(_hasNativeBuffer, "Expect a native array") return owner } /// Replace the given subRange with the first newCount elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer` and /// `insertCount <= numericCast(newValues.count)`. @inlinable // FIXME(sil-serialize-all) internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with insertCount: Int, elementsOf newValues: C ) where C : Collection, C.Element == Element { _invariantCheck() _sanityCheck(insertCount <= numericCast(newValues.count)) _sanityCheck(_hasNativeBuffer) _sanityCheck(isUniquelyReferenced()) let eraseCount = subrange.count let growth = insertCount - eraseCount let oldCount = count var native = nativeBuffer let hiddenElementCount = firstElementAddress - native.firstElementAddress _sanityCheck(native.count + growth <= native.capacity) let start = subrange.lowerBound - startIndex + hiddenElementCount let end = subrange.upperBound - startIndex + hiddenElementCount native.replaceSubrange( start..<end, with: insertCount, elementsOf: newValues) self.endIndex = self.startIndex + oldCount + growth _invariantCheck() } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @inlinable // FIXME(sil-serialize-all) internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// An object that keeps the elements stored in this buffer alive. @usableFromInline internal var owner: AnyObject @usableFromInline internal let subscriptBaseAddress: UnsafeMutablePointer<Element> @inlinable // FIXME(sil-serialize-all) internal var firstElementAddress: UnsafeMutablePointer<Element> { return subscriptBaseAddress + startIndex } @inlinable // FIXME(sil-serialize-all) internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// [63:1: 63-bit index][0: has a native buffer] @usableFromInline internal var endIndexAndFlags: UInt //===--- Non-essential bits ---------------------------------------------===// @inlinable // FIXME(sil-serialize-all) internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> NativeBuffer? { _invariantCheck() // This is a performance optimization that was put in to ensure that at // -Onone, copy of self we make to call _hasNativeBuffer is destroyed before // we call isUniquelyReferenced. Otherwise, isUniquelyReferenced will always // fail causing us to always copy. // // if _fastPath(_hasNativeBuffer && isUniquelyReferenced) { // // SR-6437 let native = _hasNativeBuffer let unique = isUniquelyReferenced() if _fastPath(native && unique) { if capacity >= minimumCapacity { // Since we have the last reference, drop any inaccessible // trailing elements in the underlying storage. That will // tend to reduce shuffling of later elements. Since this // function isn't called for subscripting, this won't slow // down that case. var native = nativeBuffer let offset = self.firstElementAddress - native.firstElementAddress let backingCount = native.count let myCount = count if _slowPath(backingCount > myCount + offset) { native.replaceSubrange( (myCount+offset)..<backingCount, with: 0, elementsOf: EmptyCollection()) } _invariantCheck() return native } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { // This is a performance optimization that ensures that the copy of self // that occurs at -Onone is destroyed before we call // isUniquelyReferencedOrPinned. This code used to be: // // return _hasNativeBuffer && isUniquelyReferenced() // // SR-6437 if !_hasNativeBuffer { return false } return isUniquelyReferenced() } @inlinable internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { // This is a performance optimization that ensures that the copy of self // that occurs at -Onone is destroyed before we call // isUniquelyReferencedOrPinned. This code used to be: // // return _hasNativeBuffer && isUniquelyReferencedOrPinned() // // SR-6437 if !_hasNativeBuffer { return false } return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable // FIXME(sil-serialize-all) internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { _invariantCheck() if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) { return nativeBuffer } return nil } @inlinable // FIXME(sil-serialize-all) @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _invariantCheck() _sanityCheck(bounds.lowerBound >= startIndex) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= endIndex) let c = bounds.count target.initialize(from: subscriptBaseAddress + bounds.lowerBound, count: c) return target + c } /// True, if the array is native and does not need a deferred type check. @inlinable // FIXME(sil-serialize-all) internal var arrayPropertyIsNativeTypeChecked: Bool { return _hasNativeBuffer } @inlinable // FIXME(sil-serialize-all) internal var count: Int { get { return endIndex - startIndex } set { let growth = newValue - count if growth != 0 { nativeBuffer.count += growth self.endIndex += growth } _invariantCheck() } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `startIndex ≤ index < endIndex` @inlinable // FIXME(sil-serialize-all) internal func _checkValidSubscript(_ index : Int) { _precondition( index >= startIndex && index < endIndex, "Index out of bounds") } @inlinable // FIXME(sil-serialize-all) internal var capacity: Int { let count = self.count if _slowPath(!_hasNativeBuffer) { return count } let n = nativeBuffer let nativeEnd = n.firstElementAddress + n.count if (firstElementAddress + count) == nativeEnd { return count + (n.capacity - n.count) } return count } @inlinable // FIXME(sil-serialize-all) internal mutating func isUniquelyReferenced() -> Bool { return isKnownUniquelyReferenced(&owner) } @inlinable // FIXME(sil-serialize-all) internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isKnownUniquelyReferencedOrPinned(&owner) } @inlinable // FIXME(sil-serialize-all) internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= startIndex, "slice index is out of range (before startIndex)") _sanityCheck(i < endIndex, "slice index is out of range") return subscriptBaseAddress[i] } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable // FIXME(sil-serialize-all) internal subscript(position: Int) -> Element { get { return getElement(position) } nonmutating set { _sanityCheck(position >= startIndex, "slice index is out of range (before startIndex)") _sanityCheck(position < endIndex, "slice index is out of range") subscriptBaseAddress[position] = newValue } } @inlinable // FIXME(sil-serialize-all) internal subscript(bounds: Range<Int>) -> _SliceBuffer { get { _sanityCheck(bounds.lowerBound >= startIndex) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= endIndex) return _SliceBuffer( owner: owner, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: _hasNativeBuffer) } set { fatalError("not implemented") } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @usableFromInline internal var startIndex: Int /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @inlinable // FIXME(sil-serialize-all) internal var endIndex: Int { get { return Int(endIndexAndFlags >> 1) } set { endIndexAndFlags = (UInt(newValue) << 1) | (_hasNativeBuffer ? 1 : 0) } } internal typealias Indices = Range<Int> //===--- misc -----------------------------------------------------------===// /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } } extension _SliceBuffer { @inlinable // FIXME(sil-serialize-all) internal func _copyToContiguousArray() -> ContiguousArray<Element> { if _hasNativeBuffer { let n = nativeBuffer if count == n.count { return ContiguousArray(_buffer: n) } } let result = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: 0) result.firstElementAddress.initialize( from: firstElementAddress, count: count) return ContiguousArray(_buffer: result) } }
apache-2.0
dc9c44b75c7bb7ff01d04d1866ac8685
31.282927
93
0.675582
4.869757
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletRecovery/AccountRecovery/AccountRecoveryService.swift
1
2928
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit final class AccountRecoveryService: AccountRecoveryServiceAPI { // MARK: - Properties private let jwtService: JWTServiceAPI private let accountRecoveryRepository: AccountRecoveryRepositoryAPI private let credentialsRepository: NabuOfflineTokenRepositoryAPI // MARK: - Setup init( jwtService: JWTServiceAPI = resolve(), accountRecoveryRepository: AccountRecoveryRepositoryAPI = resolve(), credentialsRepository: NabuOfflineTokenRepositoryAPI = resolve() ) { self.jwtService = jwtService self.accountRecoveryRepository = accountRecoveryRepository self.credentialsRepository = credentialsRepository } // MARK: - API func resetVerificationStatus( guid: String, sharedKey: String ) -> AnyPublisher<Void, AccountRecoveryServiceError> { jwtService .fetchToken(guid: guid, sharedKey: sharedKey) .mapError(AccountRecoveryServiceError.jwtService) .flatMap { [accountRecoveryRepository] jwtToken -> AnyPublisher<(NabuOfflineToken, jwtToken: String), AccountRecoveryServiceError> in accountRecoveryRepository .createOrGetNabuUser(jwtToken: jwtToken) } .flatMap { [accountRecoveryRepository] offlineToken, jwtToken -> AnyPublisher<Void, AccountRecoveryServiceError> in if let created = offlineToken.created, !created { return accountRecoveryRepository .resetUser(offlineToken: offlineToken, jwtToken: jwtToken) } return .just(()) } .eraseToAnyPublisher() } func recoverUser( guid: String, sharedKey: String, userId: String, recoveryToken: String ) -> AnyPublisher<NabuOfflineToken, AccountRecoveryServiceError> { jwtService .fetchToken(guid: guid, sharedKey: sharedKey) .mapError(AccountRecoveryServiceError.jwtService) .flatMap { [accountRecoveryRepository] jwtToken -> AnyPublisher<NabuOfflineToken, AccountRecoveryServiceError> in accountRecoveryRepository .recoverUser( jwtToken: jwtToken, userId: userId, recoveryToken: recoveryToken ) .eraseToAnyPublisher() } .eraseToAnyPublisher() } func store( offlineToken: NabuOfflineToken ) -> AnyPublisher<Void, AccountRecoveryServiceError> { credentialsRepository .set(offlineToken: offlineToken) .mapError(AccountRecoveryServiceError.failedToSaveOfflineToken) .eraseToAnyPublisher() } }
lgpl-3.0
6af9d21f12caa6532c682c3eb63803d4
35.135802
101
0.628288
5.913131
false
false
false
false
alimysoyang/CommunicationDebugger
CommunicationDebugger/AYHClientManage.swift
1
13278
// // AYHClientManage.swift // CommunicationDebugger // // Created by alimysoyang on 15/11/23. // Copyright © 2015年 alimysoyang. All rights reserved. // import Foundation @objc protocol AYHClientManageDelegate { func udpClientManage(clientManage:AYHClientManage, didConnected info:String); func udpClientManage(clientManage:AYHClientManage, receivedThenSaveSuccess success:Bool); func tcpClientManage(clientManage:AYHClientManage, didNotConnected error:String); func tcpClientManageDidConnecting(clientManage:AYHClientManage); func tcpClientManage(clientManage:AYHClientManage, didConnected connectInfo:String); func tcpClientManage(clientManage:AYHClientManage, didDisConnected error:String); func tcpClientManage(clientManage:AYHClientManage, receivedThenSaveSuccess success:Bool); func clientManage(clientManage:AYHClientManage, sendedThenSaveSuccess success:Bool); } /** * 客户端管理对象 */ class AYHClientManage: NSObject { // MARK: - properties weak var delegate:AYHClientManageDelegate?; private var udpClientSocket:GCDAsyncUdpSocket?; private var tcpClientSocket:GCDAsyncSocket?; private var sendTag:Int = 0; private var sendedData:AYHSendedData?; // MARK: - life cycle override init() { super.init(); if (AYHCMParams.sharedInstance.socketType == .kCMSTUDP) { self.udpClientSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()); } else { self.tcpClientSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue()); } } convenience init(delegate:AYHClientManageDelegate?) { self.init(); self.delegate = delegate; } deinit { self.clientClosedThenNil(); self.delegate = nil; } // MARK: - public methods func clientConnecting() { if (AYHCMParams.sharedInstance.socketType == .kCMSTUDP) { self.udpClientConnecting(); } else { self.tcpClientConnecting(); } } func clientClosed() { if (AYHCMParams.sharedInstance.socketType == .kCMSTUDP) { self.udpClientClosed(); } else { self.tcpClientClosed(); } } func clientSendData(sendData:String) { func sendedToUdpServer(data:NSData) { self.udpClientSocket?.sendData(data, toHost: AYHCMParams.sharedInstance.remoteIP, port: UInt16(AYHCMParams.sharedInstance.remotePort), withTimeout: 5, tag: self.sendTag); self.sendTag++; } func sendedToTcpServer(data:NSData) { self.tcpClientSocket?.writeData(data, withTimeout: 5, tag: self.sendTag); self.tcpClientSocket?.readDataWithTimeout(-1, tag: self.sendTag); self.sendTag++; } defer { if (self.sendedData?.sendedDataResultType != .kCMMSuccess) { let msgID:Int = self.sendedToNewMessage(AYHCMParams.sharedInstance.socketType); } } self.sendedData = AYHSendedData(); self.sendedData?.sendedMsg = sendData; self.sendedData?.sendedTag = self.sendTag; let streamData:NSData? = sendData.toNSData(AYHCMParams.sharedInstance.sHexData, characterSetType: AYHCMParams.sharedInstance.sCharacterSet.rawValue); if let data = streamData { if (AYHCMParams.sharedInstance.socketType == .kCMSTUDP) { sendedToUdpServer(data); } else { sendedToTcpServer(data); } } else { self.sendedData?.sendedDataResultType = .kCMMSErrorData; self.sendedData?.sendedMsg = String(format: "%@:\n%@", NSLocalizedString("SendedDataError", comment: ""), sendData); } } // MARK: - event response // MARK: - delegate // MARK: - private methods private func udpClientConnecting() { var info:String = ""; defer { self.delegate?.udpClientManage(self, didConnected: info) } do { try self.udpClientSocket?.bindToPort(0); do { try self.udpClientSocket?.beginReceiving(); info = String(format: NSLocalizedString("ClientStartedSuccess", comment: ""), "UDP", AYHCMParams.sharedInstance.remoteAddress()); self.notificationToNewMessage(.kCMSTUDP, notificationType: .kCMSMTNotification, notificationInfo: info); } catch let error as NSError { info = String(format: NSLocalizedString("BeginReceivedError", comment: ""), NSLocalizedString("Client", comment: ""), error.localizedDescription); self.notificationToNewMessage(.kCMSTUDP, notificationType: .kCMSMTErrorNotification, notificationInfo: info); } } catch let error as NSError { info = String(format: NSLocalizedString("PortBingError", comment: ""), NSLocalizedString("Client", comment: ""), error.localizedDescription); self.notificationToNewMessage(.kCMSTUDP, notificationType: .kCMSMTErrorNotification, notificationInfo: info); } } private func tcpClientConnecting() { do { try self.tcpClientSocket?.connectToHost(AYHCMParams.sharedInstance.remoteIP, onPort: UInt16(AYHCMParams.sharedInstance.remotePort), withTimeout: 10); guard let _ = self.delegate?.tcpClientManageDidConnecting(self) else { return; } } catch let error as NSError { let errorInfo:String = String(format: NSLocalizedString("TcpConnectedFailed", comment: ""), AYHCMParams.sharedInstance.remoteAddress(), error.localizedDescription); self.notificationToNewMessage(.kCMSTTCP, notificationType: .kCMSMTErrorNotification, notificationInfo: errorInfo); guard let _ = self.delegate?.tcpClientManage(self, didNotConnected: errorInfo) else { return; } } } private func udpClientClosed() { if let lUdpClientSocket = self.udpClientSocket { lUdpClientSocket.closeAfterSending(); } } private func tcpClientClosed() { if let lTcpClientSocket = self.tcpClientSocket { lTcpClientSocket.disconnectAfterReadingAndWriting(); } } private func clientClosedThenNil() { if (AYHCMParams.sharedInstance.socketType == .kCMSTUDP) { self.udpClientClosed(); self.udpClientSocket = nil; } else { self.tcpClientClosed(); self.tcpClientSocket = nil; } } private func receivedToNewMessage(socketType:SocketType, received:AYHReceivedData)->Int { let message:AYHMessage = AYHMessage(); message.msgTime = NSDate(); message.serviceType = .kCMSTClient; message.msgType = .kCMSMTReceived; message.msgStatus = received.receivedDataResultType; message.msgContent = received.receivedMsg; message.msgAddress = received.receivedAddress; message.calculateCellHeight(); AYHDBHelper.sharedInstance.saveMessage(socketType, message: message); return (message.msgID ?? -1); } private func sendedToNewMessage(socketType:SocketType)->Int { let message:AYHMessage = AYHMessage(); message.msgTime = NSDate(); message.serviceType = .kCMSTClient; message.msgType = .kCMSMTSend; message.msgStatus = self.sendedData?.sendedDataResultType message.msgContent = self.sendedData?.sendedMsg; message.msgAddress = ""; message.calculateCellHeight(); AYHDBHelper.sharedInstance.saveMessage(socketType, message: message); return (message.msgID ?? -1); } private func notificationToNewMessage(socketType:SocketType, notificationType:SocketMessageType, notificationInfo:String)->Int { let message:AYHMessage = AYHMessage(); message.msgTime = NSDate(); message.serviceType = .kCMSTClient; message.msgType = notificationType; message.msgStatus = .kCMMSuccess; message.msgContent = notificationInfo; message.msgAddress = ""; message.calculateCellHeight(); AYHDBHelper.sharedInstance.saveMessage(socketType, message: message); return (message.msgID ?? -1); } } // MARK: - UDP Delegate extension AYHClientManage : GCDAsyncUdpSocketDelegate { func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) { if let _ = self.sendedData { if let sendedTag = self.sendedData!.sendedTag { if (sendedTag == tag) { self.sendedData?.sendedDataResultType = .kCMMSuccess; let msgID:Int = self.sendedToNewMessage(.kCMSTUDP); guard let _ = self.delegate?.clientManage(self, sendedThenSaveSuccess: (msgID != -1)) else { return; } } } } } func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) { } func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) { } func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) { let received:AYHReceivedData = AYHelper.parseReceivedData(data); received.receivedAddress = AYHCMParams.sharedInstance.remoteAddress(); let msgID:Int = self.receivedToNewMessage(.kCMSTUDP, received: received); guard let _ = self.delegate?.udpClientManage(self, receivedThenSaveSuccess: (msgID != -1)) else { return; } } } // MARK: - TCP Delegate extension AYHClientManage : GCDAsyncSocketDelegate { func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) { sock.readDataWithTimeout(-1, tag: 0); let connectedInfo:String = String(format: NSLocalizedString("TcpConnectedSuccess", comment: ""), AYHCMParams.sharedInstance.remoteAddress()); self.notificationToNewMessage(.kCMSTTCP, notificationType: .kCMSMTNotification, notificationInfo: connectedInfo); guard let _ = self.delegate?.tcpClientManage(self, didConnected: connectedInfo) else { return; } } func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) { if let _ = err { if (err.code == 61) { let errorInfo:String = String(format: NSLocalizedString("TcpConnectedFailed", comment: ""), AYHCMParams.sharedInstance.remoteAddress(), err.localizedDescription); self.notificationToNewMessage(.kCMSTTCP, notificationType: .kCMSMTErrorNotification, notificationInfo: errorInfo); guard let _ = self.delegate?.tcpClientManage(self, didNotConnected: errorInfo) else { return; } } else { let errorInfo:String = String(format: NSLocalizedString("TcpConnectionInterrupted", comment: ""), AYHCMParams.sharedInstance.remoteAddress(), err.localizedDescription); self.notificationToNewMessage(.kCMSTTCP, notificationType: .kCMSMTErrorNotification, notificationInfo: errorInfo); guard let _ = self.delegate?.tcpClientManage(self, didDisConnected: errorInfo) else { return; } } } } func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { let received:AYHReceivedData = AYHelper.parseReceivedData(data); received.receivedAddress = AYHCMParams.sharedInstance.remoteAddress(); sock.readDataWithTimeout(-1, tag: 0); let msgID:Int = self.receivedToNewMessage(.kCMSTTCP, received: received); guard let _ = self.delegate?.tcpClientManage(self, receivedThenSaveSuccess: (msgID != -1)) else { return; } } func socket(sock: GCDAsyncSocket!, didWriteDataWithTag tag: Int) { if let _ = self.sendedData { if let sendedTag = self.sendedData!.sendedTag { if (sendedTag == tag) { self.sendedData?.sendedDataResultType = .kCMMSuccess; let msgID:Int = self.sendedToNewMessage(.kCMSTTCP); guard let _ = self.delegate?.clientManage(self, sendedThenSaveSuccess: (msgID != -1)) else { return; } } } } } }
mit
868e43cfff0900e013b39d517a9c83eb
34.55496
184
0.612171
4.722578
false
false
false
false
huonw/swift
stdlib/public/SDK/Foundation/JSONEncoder.swift
2
110195
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. open class JSONEncoder { // MARK: Options /// The formatting of the output JSON data. public struct OutputFormatting : OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable JSON with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce JSON with dictionary keys sorted in lexicographic order. @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words : [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Data { let encoder = _JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } if topLevel is NSNull { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment.")) } else if topLevel is NSNumber { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment.")) } else if topLevel is NSString { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment.")) } let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue) do { return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions) } catch { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error)) } } } // MARK: - _JSONEncoder fileprivate class _JSONEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _JSONEncodingStorage /// Options set on the top-level encoder. fileprivate let options: JSONEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _JSONEncodingStorage() self.codingPath = codingPath } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _JSONEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations private func _converted(_ key: CodingKey) -> CodingKey { switch encoder.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _JSONKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } self.container[_converted(key).stringValue] = try self.encoder.box(value) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() self.container[_converted(key).stringValue] = dictionary self.codingPath.append(key) defer { self.codingPath.removeLast() } let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() self.container[_converted(key).stringValue] = array self.codingPath.append(key) defer { self.codingPath.removeLast() } return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container) } } fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _JSONEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } } // MARK: - Concrete Value Representations extension _JSONEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count do { try closure(date, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. let depth = self.storage.count do { try data.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count do { try closure(data, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want. fileprivate func box_<T : Encodable>(_ value: T) throws -> NSObject? { if T.self == Date.self || T.self == NSDate.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if T.self == Data.self || T.self == NSData.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if T.self == URL.self || T.self == NSURL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if T.self == Decimal.self || T.self == NSDecimalNumber.self { // JSONSerialization can natively handle NSDecimalNumber. return (value as! NSDecimalNumber) } // The value should request a container from the _JSONEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } } // MARK: - _JSONReferencingEncoder /// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _JSONReferencingEncoder : _JSONEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: _JSONEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_JSONKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, key: CodingKey, convertedKey: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, convertedKey.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // JSON Decoder //===----------------------------------------------------------------------===// /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types. open class JSONDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a JSON number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.index(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore) } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex var components = stringKey[keyRange].split(separator: "_") let joinedString : String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result : String if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) { result = joinedString } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if (!leadingUnderscoreRange.isEmpty) { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given JSON representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { let topLevel: Any do { topLevel = try JSONSerialization.jsonObject(with: data) } catch { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error)) } let decoder = _JSONDecoder(referencing: topLevel, options: self.options) guard let value = try decoder.unbox(topLevel, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.")) } return value } } // MARK: - _JSONDecoder fileprivate class _JSONDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _JSONDecodingStorage /// Options set on the top-level decoder. fileprivate let options: JSONDecoder._Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) { self.storage = _JSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _JSONDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(!self.containers.isEmpty, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) { self.decoder = decoder switch decoder.options.keyDecodingStrategy { case .useDefaultKeys: self.container = container case .convertFromSnakeCase: // Convert the snake case keys in the container to camel case. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries. self.container = Dictionary(container.map { key, value in (JSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value) }, uniquingKeysWith: { (first, _) in first }) case .custom(let converter): self.container = Dictionary(container.map { key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value) }, uniquingKeysWith: { (first, _) in first }) } self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } private func _errorDescription(of key: CodingKey) -> String { switch decoder.options.keyDecodingStrategy { case .convertFromSnakeCase: // In this case we can attempt to recover the original value by reversing the transform let original = key.stringValue let converted = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(original) if converted == original { return "\(key) (\"\(original)\")" } else { return "\(key) (\"\(original)\"), converted to \(converted)" } default: // Otherwise, just report the converted string return "\(key) (\"\(key.stringValue)\")" } } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = self.container[key.stringValue] ?? NSNull() return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _JSONKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } extension _JSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(type) return try self.unbox(self.storage.topContainer, as: type)! } } // MARK: - Concrete Value Representations extension _JSONDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) defer { self.storage.popContainer() } return try Date(from: self) case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) defer { self.storage.popContainer() } return try Data(from: self) case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // Attempt to bridge from NSDecimalNumber. if let decimal = value as? Decimal { return decimal } else { let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { if type == Date.self || type == NSDate.self { return try self.unbox(value, as: Date.self) as? T } else if type == Data.self || type == NSData.self { return try self.unbox(value, as: Data.self) as? T } else if type == URL.self || type == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return (url as! T) } else if type == Decimal.self || type == NSDecimalNumber.self { return try self.unbox(value, as: Decimal.self) as? T } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _JSONKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// fileprivate extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
apache-2.0
5987531f9f901661d5ce7624d8bd60a4
43.885947
323
0.646245
5.043711
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/Gen3SetupSelectWifiNetworkViewController.swift
1
3692
// // Created by Raimundas Sakalauskas on 9/20/18. // Copyright (c) 2018 Particle. All rights reserved. // import UIKit class Gen3SetupSelectWifiNetworkViewController: Gen3SetupNetworkListViewController { private var networks:[Gen3SetupNewWifiNetworkInfo]? private var callback: ((Gen3SetupNewWifiNetworkInfo) -> ())! func setup(didSelectNetwork: @escaping (Gen3SetupNewWifiNetworkInfo) -> ()) { self.callback = didSelectNetwork } override func setContent() { titleLabel.text = Gen3SetupStrings.SelectWifiNetwork.Title } func setNetworks(networks: [Gen3SetupNewWifiNetworkInfo]) { var networks = networks for i in (0 ..< networks.count).reversed() { if networks[i].ssid.count == 0 { networks.remove(at: i) } } networks.sort { info, info2 in return info.ssid.localizedCaseInsensitiveCompare(info2.ssid) == .orderedAscending } self.networks = networks self.stopScanning() } override func resume(animated: Bool) { super.resume(animated: true) self.networks = [] self.networksTableView.reloadData() self.startScanning() self.networksTableView.isUserInteractionEnabled = true self.isBusy = false } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return networks?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupWifiNetworkCell") as! Gen3SetupCell cell.cellTitleLabel.text = networks![indexPath.row].ssid cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.LargeSize, color: ParticleStyle.PrimaryTextColor) if (networks![indexPath.row].rssi > -56) { cell.cellAccessoryImageView.image = UIImage.init(named: "Gen3SetupWifiStrongIcon") } else if (networks![indexPath.row].rssi > -71) { cell.cellAccessoryImageView.image = UIImage.init(named: "Gen3SetupWifiMediumIcon") } else { cell.cellAccessoryImageView.image = UIImage.init(named: "Gen3SetupWifiWeakIcon") } if networks![indexPath.row].security == .noSecurity { cell.cellSecondaryAccessoryImageView.image = nil } else { cell.cellSecondaryAccessoryImageView.image = UIImage.init(named: "Gen3SetupWifiProtectedIcon") } cell.cellSecondaryAccessoryImageView.isHidden = (cell.cellSecondaryAccessoryImageView.image == nil) let cellHighlight = UIView() cellHighlight.backgroundColor = ParticleStyle.CellHighlightColor cell.selectedBackgroundView = cellHighlight cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) cell.accessoryView = nil cell.accessoryType = .disclosureIndicator return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.isBusy = true tableView.deselectRow(at: indexPath, animated: true) tableView.isUserInteractionEnabled = false if let cell = tableView.cellForRow(at: indexPath) { let activityIndicator = UIActivityIndicatorView(style: .white) activityIndicator.color = ParticleStyle.NetworkJoinActivityIndicatorColor activityIndicator.startAnimating() cell.accessoryView = activityIndicator } callback(networks![indexPath.row]) } }
apache-2.0
453d9282198ecc8fac976f1509b74df7
34.5
139
0.678765
4.955705
false
false
false
false
AboutObjectsTraining/swift-ios-2015-07-kop
Coolness/Coolness/CoolViewController.swift
1
2845
import UIKit let AccessoryHeight: CGFloat = 66 class CoolViewController: UIViewController { var textField: UITextField! var coolView: UIView! func addCoolView() { println("\(textField.text)") let newCell = CoolViewCell(frame: CGRect.zeroRect) newCell.text = textField.text newCell.sizeToFit() coolView.addSubview(newCell) } override func loadView() { let bounds = UIScreen.mainScreen().bounds let backgroundView = UIView(frame: bounds) view = backgroundView backgroundView.backgroundColor = UIColor.brownColor() let accessoryView = UIView(frame: CGRect( origin: bounds.origin, size: CGSize( width: bounds.width, height: AccessoryHeight))) backgroundView.addSubview(accessoryView) accessoryView.backgroundColor = UIColor(white: 1.0, alpha: 0.5) coolView = UIView(frame: CGRect( x: bounds.origin.x, y: AccessoryHeight, width: bounds.width, height: bounds.height - AccessoryHeight)) backgroundView.addSubview(coolView) coolView.backgroundColor = UIColor(white: 1.0, alpha: 0.7) coolView.clipsToBounds = true // self.coolView = coolView // Controls textField = UITextField(frame: CGRect(x: 8, y: 28, width: 280, height: 30)) accessoryView.addSubview(textField) textField.borderStyle = .RoundedRect textField.placeholder = "Enter some text" textField.delegate = self let button = UIButton.buttonWithType(.System) as! UIButton button.setTitle("Add", forState: .Normal) button.sizeToFit() accessoryView.addSubview(button) button.frame.offset(dx: 300.0, dy: 28.0) button.addTarget(self, action: Selector("addCoolView"), forControlEvents: .TouchUpInside) // Cool View Cells let cell1 = CoolViewCell(frame: CGRect(x: 20, y: 40, width: 80, height: 30)) coolView.addSubview(cell1) cell1.backgroundColor = UIColor.purpleColor() let cell2 = CoolViewCell(frame: CGRect(x: 60, y: 100, width: 80, height: 30)) coolView.addSubview(cell2) cell2.backgroundColor = UIColor.orangeColor() cell1.text = "The race is to the Swift?" cell2.text = "Hello World!" cell1.sizeToFit() cell2.sizeToFit() } } extension CoolViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
2e70f1be616c7d188720015e1bf0377e
26.892157
97
0.58594
4.913644
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Healthcare
iOS/Healthcare-Tests/SidePanelTests.swift
1
2489
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit import XCTest @testable import Healthcare /** * A unit test class for the SidePanelViewController. */ class SidePanelTests: XCTestCase { var vc: SidePanelViewController! override func setUp() { super.setUp() let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType)) vc = storyboard.instantiateViewControllerWithIdentifier("LeftViewController") as! SidePanelViewController vc.loadView() } override func tearDown() { super.tearDown() vc = nil } /** Method verifies UITableView datasource protocol is working properly. */ func testTableViewDatasource() { XCTAssertTrue(vc.conformsToProtocol(UITableViewDataSource), "View does not conform to UITableView datasource protocol") XCTAssertNotNil(vc.menuTableView.dataSource, "TableView datasource is nil") } /** Method verifies UITableView delegate protocol is working properly. */ func testTableViewDelegate() { XCTAssertTrue(vc.conformsToProtocol(UITableViewDelegate), "View does not conform to UITableView delegate protocol") XCTAssertNotNil(vc.menuTableView.delegate, "TableView delegate is nil") } /** This method verifies the UITableView has the correct amount of rows. */ func testTableViewNumberOfRows() { let expectedNumber = 6 XCTAssertTrue(vc.tableView(vc.menuTableView, numberOfRowsInSection: 0) == expectedNumber, "TableView has \(vc.tableView(vc.menuTableView, numberOfRowsInSection: 0)) rows, but it should have \(expectedNumber)") } /** Method to ensure row height in UITableView is correct. */ func testTableViewCellHeight() { let expectedHeight = (vc.view.frame.size.height/2)/6 for index in 0...6 { let actualHeight = vc.tableView(vc.menuTableView, heightForRowAtIndexPath: NSIndexPath(forRow: index, inSection: 0)) XCTAssertEqual(expectedHeight, actualHeight, "Cell should have height of \(expectedHeight), but they have a height of \(actualHeight)") } } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
epl-1.0
eb38b3686357b51d446dedefb33c18ff
34.042254
217
0.67926
5.248945
false
true
false
false
restlet/httpsnippet
test/fixtures/output/swift/nsurlsession/custom-method.swift
2
579
import Foundation var request = NSMutableURLRequest(URL: NSURL(string: "http://mockbin.com/har")!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0) request.HTTPMethod = "PROPFIND" let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if (error != nil) { println(error) } else { let httpResponse = response as? NSHTTPURLResponse println(httpResponse) } }) dataTask.resume()
mit
0d86728ab45b21bada68e32a0a6edd5d
31.166667
107
0.642487
4.865546
false
false
false
false
defual/FlashBar
Sample/Sample/ViewController.swift
1
860
// // ViewController.swift // Sample // // Created by Damian Rzeszot on 17/02/16. // Copyright © 2016 Damian Rzeszot. All rights reserved. // import UIKit import FlashBar class ViewController: UIViewController { let colors: [UIColor] = [ .redColor(), .greenColor(), .yellowColor() ] var flash: FlashBar { return navigationController!.flashBar } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() flash.messageLabel.text = "hello world" flash.messageLabel.font = .systemFontOfSize(11) flash.messageLabel.textColor = .whiteColor() flash.backgroundColor = .greenColor() } // MARK: - Actions @IBAction func toogle(sender: AnyObject) { flash.setHidden(!flash.hidden, animated: true) } }
mit
81951eec98a624bfe4dc70a3356264c1
19.452381
74
0.61234
4.521053
false
false
false
false
mcjcloud/Show-And-Sell
Show And Sell/ManageGroupTableViewController.swift
1
12647
// // ManageGroupTableViewController.swift // Show And Sell // // Created by Brayden Cloud on 11/28/16. // Copyright © 2016 Brayden Cloud. All rights reserved. // import UIKit extension Array { func elements(where predicate: (Element) -> Bool) -> Array { var list = [Element]() for elem in self { if predicate(elem) { list.append(elem) } } return list } } class ManageGroupTableViewController: UITableViewController, UISearchResultsUpdating { var searchController: UISearchController! // properties var items = [Item]() var filteredItems = [Item]() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Manage Group" // setup search bar searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar // refresh control self.refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: #selector(handleRefresh(_:)), for: .valueChanged) // load all items. refreshControl?.beginRefreshing() self.refreshControl?.backgroundColor = UIColor(colorLiteralRed: 0.871, green: 0.788, blue: 0.380, alpha: 1.0) // Gold handleRefresh(self.refreshControl!) } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // 1 for unapproved items, the other for approved items. return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Unapproved" : "Approved" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.count : items.count let approved = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.elements(where: { e in e.approved == true }) : items.elements(where: { e in e.approved == true }) let unapproved = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.elements(where: { e in e.approved == false }) : items.elements(where: { e in e.approved == false }) // if it's the top section, and there are 2 sections if section == 0 { return unapproved.count } else { // if section == 1 return approved.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Configure the cell... let cell = tableView.dequeueReusableCell(withIdentifier: "manageCell") as! ItemTableViewCell let approved = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.elements(where: { e in e.approved == true }) : items.elements(where: { e in e.approved == true }) let unapproved = (searchController.isActive && searchController.searchBar.text != "") ? filteredItems.elements(where: { e in e.approved == false }) : items.elements(where: { e in e.approved == false }) let item = indexPath.section == 0 ? unapproved[indexPath.row] : approved[indexPath.row] // assign data cell.item = item cell.itemTitle.adjustsFontSizeToFitWidth = true cell.itemTitle.textAlignment = .left cell.itemPrice.adjustsFontSizeToFitWidth = true cell.itemPrice.textAlignment = .right cell.itemTitle.text = item.name cell.itemPrice.text = String(format: "$%.02f", Double(item.price) ?? 0.0) // cast the string to double, and format. cell.itemCondition.text = item.condition // convert the image from encoded string to an image. let imageData = Data(base64Encoded: item.thumbnail) if let data = imageData { cell.itemImage.image = UIImage(data: data) } else { cell.itemImage.image = UIImage(named: "noimage") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // segue to the view displaying the item. searchController.resignFirstResponder() let cell = tableView.cellForRow(at: indexPath) performSegue(withIdentifier: "manageToEdit", sender: cell) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // Implement actions. let section = indexPath.section var actions = [UITableViewRowAction]() if section == 0 { // unapproved let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete") { action, indexPath in // get the Item selected let cell = tableView.cellForRow(at: indexPath) as! ItemTableViewCell let item = self.items.first(where: { e in e.name == cell.itemTitle.text }) // remove item from array if let item = item { if let i = self.items.index(of: item) { self.items.remove(at: i) } } // delete the Item HttpRequestManager.delete(itemWithId: item?.itemId ?? "", password: AppData.user?.password ?? "") { item, response, error in print("Item delete response: \((response as? HTTPURLResponse)?.statusCode)") } tableView.reloadData() } let approveAction = UITableViewRowAction(style: .normal, title: "Approve") { action, indexPath in // get the Item selected let cell = tableView.cellForRow(at: indexPath) as! ItemTableViewCell print("cell: \(cell.itemTitle.text)") let item = self.items.first(where: { e in e.itemId == cell.item.itemId }) // PUT the item with approved: true if let i = item { i.approved = true HttpRequestManager.put(item: i, itemId: i.itemId, adminPassword: AppData.user?.password ?? "") { item, response, error in print("Item update response: \((response as? HTTPURLResponse)?.statusCode)") } } tableView.reloadData() } actions.append(approveAction) actions.append(deleteAction) } else { // approved let unapproveAction = UITableViewRowAction(style: .destructive, title: "Unapprove") { action, indexPath in // get the Item selected let cell = tableView.cellForRow(at: indexPath) as! ItemTableViewCell let item = self.items.first(where: { e in e.name == cell.itemTitle.text }) // PUT the item with approved: false if let i = item { i.approved = false HttpRequestManager.put(item: i, itemId: i.itemId, adminPassword: AppData.user?.password ?? "") { item, response, error in print("Item update response: \((response as? HTTPURLResponse)?.statusCode)") } } tableView.reloadData() } actions.append(unapproveAction) } // return the array return actions } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let source = sender as! ItemTableViewCell let item = items.first(where: { e in e.name == source.itemTitle.text }) let destination = segue.destination as! DonateItemViewController // assign data from cell. destination.item = item destination.groupId = item?.groupId } @IBAction func updateItem(segue: UIStoryboardSegue) { // send update request to server // all fields filled out, donate item. let source = segue.source as! DonateItemViewController // force unwrap data because they all have to be filled to click done. let item = source.item! item.name = source.itemNameField.text! item.price = source.itemPriceField.text! item.condition = source.itemConditionField.text! item.itemDescription = source.itemDescription.text! let imageData = UIImagePNGRepresentation(resizeImage(image: source.imageButton.currentBackgroundImage!, targetSize: CGSize(width: 250, height: 250))) item.thumbnail = imageData!.base64EncodedString() // make a post request to add the item to the appropriate group HttpRequestManager.put(item: item, itemId: item.itemId, adminPassword: AppData.user?.password ?? "") { item, response, error in print("ITEM PUT COMPLETION") if error != nil { print("ERROR: \(error)") } else { if let _ = item { print("Item successfully updated") } } } } @IBAction func cancelUpdate(segue: UIStoryboardSegue) { // Do nothing. } // MARK: Refresh func handleRefresh(_ refreshControl: UIRefreshControl) { print() print("refreshing") // get a list of all items (for now) // TODO: get items based on owned group. HttpRequestManager.items(withGroupId: AppData.myGroup!.groupId) { itemsArray, response, error in print("DATA RETURNED") // set current items to requested items self.items = itemsArray // reload data on the main thread. DispatchQueue.main.async { self.tableView.reloadData() self.refreshControl?.endRefreshing() } print("refresh ending") } } // MARK: SearchBar func updateSearchResults(for searchController: UISearchController) { filterItems(for: searchController.searchBar.text!) tableView.reloadData() } func filterItems(for searchText: String) { filteredItems = items.filter { return $0.name.lowercased().contains(searchText.lowercased()) } } // resize image func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size print("resizing image") print("old size: \(size)") let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() print("new size: \(newImage!.size)") return newImage! } }
apache-2.0
d223ed355c74e2b8f5724fefdc2b57a6
39.925566
209
0.593626
5.232106
false
false
false
false
Antondomashnev/Sourcery
Sourcery/Generating/Template/Stencil/StencilTemplate.swift
1
15218
import Foundation import Stencil import PathKit import StencilSwiftKit import SourceryRuntime final class StencilTemplate: StencilSwiftKit.StencilSwiftTemplate, Template { private(set) var sourcePath: Path = "" convenience init(path: Path) throws { self.init(templateString: try path.read(), environment: StencilTemplate.sourceryEnvironment(templatePath: path)) sourcePath = path } convenience init(templateString: String) { self.init(templateString: templateString, environment: StencilTemplate.sourceryEnvironment()) } func render(types: Types, arguments: [String: NSObject]) throws -> String { let context = TemplateContext(types: types, arguments: arguments) do { return try super.render(context.stencilContext) } catch { throw "\(sourcePath): \(error)" } } private static func sourceryEnvironment(templatePath: Path? = nil) -> Stencil.Environment { let ext = Stencil.Extension() ext.registerStringFilters() ext.registerBoolFilter("definedInExtension", filter: { (t: Definition) in t.definedInType?.isExtension ?? false }) ext.registerBoolFilter("computed", filter: { (v: SourceryVariable) in v.isComputed && !v.isStatic }) ext.registerBoolFilter("stored", filter: { (v: SourceryVariable) in !v.isComputed && !v.isStatic }) ext.registerBoolFilter("tuple", filter: { (v: SourceryVariable) in v.isTuple }) ext.registerAccessLevelFilters(.open) ext.registerAccessLevelFilters(.public) ext.registerAccessLevelFilters(.private) ext.registerAccessLevelFilters(.fileprivate) ext.registerAccessLevelFilters(.internal) ext.registerBoolFilterOrWithArguments("based", filter: { (t: Type, name: String) in t.based[name] != nil }, other: { (t: Typed, name: String) in t.type?.based[name] != nil }) ext.registerBoolFilterOrWithArguments("implements", filter: { (t: Type, name: String) in t.implements[name] != nil }, other: { (t: Typed, name: String) in t.type?.implements[name] != nil }) ext.registerBoolFilterOrWithArguments("inherits", filter: { (t: Type, name: String) in t.inherits[name] != nil }, other: { (t: Typed, name: String) in t.type?.inherits[name] != nil }) ext.registerBoolFilterOrWithArguments("extends", filter: { (t: Type, name: String) in t.isExtension && t.name == name }, other: { (t: Typed, name: String) in guard let type = t.type else { return false }; return type.isExtension && type.name == name }) ext.registerBoolFilter("extension", filter: { (t: Type) in t.isExtension }) ext.registerBoolFilter("enum", filter: { (t: Type) in t is Enum }) ext.registerBoolFilter("struct", filter: { (t: Type) in t is Struct }) ext.registerBoolFilter("protocol", filter: { (t: Type) in t is SourceryProtocol }) ext.registerFilter("count", filter: count) ext.registerFilter("toArray", filter: toArray) ext.registerBoolFilter("initializer", filter: { (m: SourceryMethod) in m.isInitializer }) ext.registerBoolFilterOr("class", filter: { (t: Type) in t is Class }, other: { (m: SourceryMethod) in m.isClass }) ext.registerBoolFilterOr("static", filter: { (v: SourceryVariable) in v.isStatic }, other: { (m: SourceryMethod) in m.isStatic }) ext.registerBoolFilterOr("instance", filter: { (v: SourceryVariable) in !v.isStatic }, other: { (m: SourceryMethod) in !(m.isStatic || m.isClass) }) ext.registerBoolFilterWithArguments("annotated", filter: { (a: Annotated, annotation) in a.isAnnotated(with: annotation) }) var extensions = stencilSwiftEnvironment().extensions extensions.append(ext) let loader = templatePath.map({ FileSystemLoader(paths: [$0.parent()]) }) return Environment(loader: loader, extensions: extensions, templateClass: StencilTemplate.self) } } extension Annotated { func isAnnotated(with annotation: String) -> Bool { if annotation.contains("=") { let components = annotation.components(separatedBy: "=").map({ $0.trimmingCharacters(in: .whitespaces) }) return annotations[components[0]]?.description == components[1] } else { return annotations[annotation] != nil } } } extension Stencil.Extension { func registerStringFilters() { let upperFirst = FilterOr<String, TypeName>.make({ $0.upperFirst() }, other: { $0.name.upperFirst() }) registerFilter("upperFirst", filter: upperFirst) let lowerFirst = FilterOr<String, TypeName>.make({ $0.lowerFirst() }, other: { $0.name.lowerFirst() }) registerFilter("lowerFirst", filter: lowerFirst) let lowercase = FilterOr<String, TypeName>.make({ $0.lowercased() }, other: { $0.name.lowercased() }) registerFilter("lowercase", filter: lowercase) let uppercase = FilterOr<String, TypeName>.make({ $0.uppercased() }, other: { $0.name.uppercased() }) registerFilter("uppercase", filter: uppercase) let capitalise = FilterOr<String, TypeName>.make({ $0.capitalized }, other: { $0.name.capitalized }) registerFilter("capitalise", filter: capitalise) registerFilterOrWithTwoArguments("replace", filter: { (source: String, substring: String, replacement: String) -> Any? in return source.replacingOccurrences(of: substring, with: replacement) }, other: { (source: TypeName, substring: String, replacement: String) -> Any? in return source.name.replacingOccurrences(of: substring, with: replacement) }) registerBoolFilterOrWithArguments("contains", filter: { (s1: String, s2: String) in s1.contains(s2) }, other: { (t: TypeName, s2: String) in t.name.contains(s2) }) registerBoolFilterOrWithArguments("hasPrefix", filter: { (s1: String, s2) in s1.hasPrefix(s2) }, other: { (t: TypeName, s2) in t.name.hasPrefix(s2) }) registerBoolFilterOrWithArguments("hasSuffix", filter: { (s1: String, s2) in s1.hasSuffix(s2) }, other: { (t: TypeName, s2) in t.name.hasSuffix(s2) }) } func registerFilterWithTwoArguments<T, A, B>(_ name: String, filter: @escaping (T, A, B) throws -> Any?) { registerFilter(name) { (any, args) throws -> Any? in guard let type = any as? T else { return any } guard args.count == 2, let argA = args[0] as? A, let argB = args[1] as? B else { throw TemplateSyntaxError("'\(name)' filter takes two arguments: \(A.self) and \(B.self)") } return try filter(type, argA, argB) } } func registerFilterOrWithTwoArguments<T, Y, A, B>(_ name: String, filter: @escaping (T, A, B) throws -> Any?, other: @escaping (Y, A, B) throws -> Any?) { registerFilter(name) { (any, args) throws -> Any? in guard args.count == 2, let argA = args[0] as? A, let argB = args[1] as? B else { throw TemplateSyntaxError("'\(name)' filter takes two arguments: \(A.self) and \(B.self)") } if let type = any as? T { return try filter(type, argA, argB) } else if let type = any as? Y { return try other(type, argA, argB) } else { return any } } } func registerFilterWithArguments<A>(_ name: String, filter: @escaping (Any?, A) throws -> Any?) { registerFilter(name) { (any, args) throws -> Any? in guard args.count == 1, let arg = args.first as? A else { throw TemplateSyntaxError("'\(name)' filter takes a single \(A.self) argument") } return try filter(any, arg) } } func registerBoolFilterWithArguments<U, A>(_ name: String, filter: @escaping (U, A) -> Bool) { registerFilterWithArguments(name, filter: Filter.make(filter)) registerFilterWithArguments("!\(name)", filter: Filter.make({ !filter($0, $1) })) } func registerBoolFilter<U>(_ name: String, filter: @escaping (U) -> Bool) { registerFilter(name, filter: Filter.make(filter)) registerFilter("!\(name)", filter: Filter.make({ !filter($0) })) } func registerBoolFilterOrWithArguments<U, V, A>(_ name: String, filter: @escaping (U, A) -> Bool, other: @escaping (V, A) -> Bool) { registerFilterWithArguments(name, filter: FilterOr.make(filter, other: other)) registerFilterWithArguments("!\(name)", filter: FilterOr.make({ !filter($0, $1) }, other: { !other($0, $1) })) } func registerBoolFilterOr<U, V>(_ name: String, filter: @escaping (U) -> Bool, other: @escaping (V) -> Bool) { registerFilter(name, filter: FilterOr.make(filter, other: other)) registerFilter("!\(name)", filter: FilterOr.make({ !filter($0) }, other: { !other($0) })) } func registerAccessLevelFilters(_ accessLevel: AccessLevel) { registerBoolFilterOr(accessLevel.rawValue, filter: { (t: Type) in t.accessLevel == accessLevel.rawValue && t.accessLevel != AccessLevel.none.rawValue }, other: { (m: SourceryMethod) in m.accessLevel == accessLevel.rawValue && m.accessLevel != AccessLevel.none.rawValue } ) registerBoolFilterOr("!\(accessLevel.rawValue)", filter: { (t: Type) in t.accessLevel != accessLevel.rawValue && t.accessLevel != AccessLevel.none.rawValue }, other: { (m: SourceryMethod) in m.accessLevel != accessLevel.rawValue && m.accessLevel != AccessLevel.none.rawValue } ) registerBoolFilter("\(accessLevel.rawValue)Get", filter: { (v: SourceryVariable) in v.readAccess == accessLevel.rawValue && v.readAccess != AccessLevel.none.rawValue }) registerBoolFilter("!\(accessLevel.rawValue)Get", filter: { (v: SourceryVariable) in v.readAccess != accessLevel.rawValue && v.readAccess != AccessLevel.none.rawValue }) registerBoolFilter("\(accessLevel.rawValue)Set", filter: { (v: SourceryVariable) in v.writeAccess == accessLevel.rawValue && v.writeAccess != AccessLevel.none.rawValue }) registerBoolFilter("!\(accessLevel.rawValue)Set", filter: { (v: SourceryVariable) in v.writeAccess != accessLevel.rawValue && v.writeAccess != AccessLevel.none.rawValue }) } } private func toArray(_ value: Any?) -> Any? { switch value { case let array as NSArray: return array case .some(let something): return [something] default: return nil } } private func count(_ value: Any?) -> Any? { guard let array = value as? NSArray else { return value } return array.count } extension String { fileprivate func upperFirst() -> String { let first = String(self.prefix(1)).capitalized let other = dropFirst() return first + other } fileprivate func lowerFirst() -> String { let first = String(self.prefix(1)).lowercased() let other = dropFirst() return first + other } } private struct Filter<T> { static func make(_ filter: @escaping (T) -> Bool) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let array as NSArray: return array.flatMap { $0 as? T }.filter(filter) default: return any } } } static func make<U>(_ filter: @escaping (T) -> U?) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let array as NSArray: return array.flatMap { $0 as? T }.flatMap(filter) default: return any } } } static func make<A>(_ filter: @escaping (T, A) -> Bool) -> (Any?, A) throws -> Any? { return { (any, arg) throws -> Any? in switch any { case let type as T: return filter(type, arg) case let array as NSArray: return array.flatMap { $0 as? T }.filter({ filter($0, arg) }) default: return any } } } } private struct FilterOr<T, Y> { static func make(_ filter: @escaping (T) -> Bool, other: @escaping (Y) -> Bool) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let type as Y: return other(type) case let array as NSArray: if array.firstObject is T { return array.flatMap { $0 as? T }.filter(filter) } else { return array.flatMap { $0 as? Y }.filter(other) } default: return any } } } static func make<U>(_ filter: @escaping (T) -> U?, other: @escaping (Y) -> U?) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let type as Y: return other(type) case let array as NSArray: if array.firstObject is T { return array.flatMap { $0 as? T }.flatMap(filter) } else { return array.flatMap { $0 as? Y }.flatMap(other) } default: return any } } } static func make<A>(_ filter: @escaping (T, A) -> Bool, other: @escaping (Y, A) -> Bool) -> (Any?, A) throws -> Any? { return { (any, arg) throws -> Any? in switch any { case let type as T: return filter(type, arg) case let type as Y: return other(type, arg) case let array as NSArray: if array.firstObject is T { return array.flatMap { $0 as? T }.filter({ filter($0, arg) }) } else { return array.flatMap { $0 as? Y }.filter({ other($0, arg) }) } default: return any } } } }
mit
aa2f57e952c558b62c9faeccd3cdfadc
42.48
179
0.559469
4.334378
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Services/UserServices.swift
1
5912
// // UserServices.swift // FoodAndFitness // // Created by Mylo Ho on 4/11/17. // Copyright © 2017 SuHoVan. All rights reserved. // import Foundation import Alamofire import ObjectMapper import RealmSwift import RealmS import SwiftyJSON final class UserServices { @discardableResult func update(params: UpdateParams, completion: @escaping Completion) -> Request? { let path = ApiPath.Auth.auth var parameters: JSObject = [:] if let weight = params.weight { parameters = [ "weight": weight ] } if let height = params.height { parameters = [ "height": height ] } if let goalId = params.goalId { parameters = [ "goal_id": goalId ] } if let activeId = params.activeId { parameters = [ "active_id": activeId ] } return ApiManager.request(method: .put, urlString: path, parameters: parameters, completion: { (result) in Mapper<User>().map(result: result, type: .object, completion: completion) }) } @discardableResult class func signIn(params: SignInParams, completion: @escaping Completion) -> Request? { let path = ApiPath.Auth.signin let parameters: JSObject = [ "email": params.email, "password": params.password ] return ApiManager.request(method: .post, urlString: path, parameters: parameters, completion: { (result) in switch result { case .success(let json): guard let json = json["data"] as? JSObject else { completion(.failure(FFError.json)) return } let realm = RealmS() var userId: Int? realm.write { if let user = realm.map(User.self, json: json) { userId = user.id } } guard let id = userId else { completion(.failure(FFError.json)) return } api.session.userID = id api.session.credential = Session.Credential(username: params.email, password: params.password) case .failure(_): break } completion(result) }) } @discardableResult class func signUp(params: SignUpParams, completion: @escaping Completion) -> Request? { let path = ApiPath.Auth.auth var parameter: JSObject = [ "email": params.email.toString(), "password": params.password.toString(), "name": params.fullName.toString(), "birthday": params.birthday.toString(), "gender": params.gender, "height": params.height.toString(), "weight": params.weight.toString() ] if let goal = params.goal { parameter["goal_id"] = goal.id } if let active = params.active { parameter["active_id"] = active.id } return ApiManager.request(method: .post, urlString: path, parameters: parameter, completion: { (result) in switch result { case .success(let json): guard let json = json["data"] as? JSObject else { completion(.failure(FFError.json)) return } let realm = RealmS() var userId: Int? realm.write { if let user = realm.map(User.self, json: json) { userId = user.id } } guard let id = userId else { completion(.failure(FFError.json)) return } api.session.userID = id api.session.credential = Session.Credential(username: params.email.toString(), password: params.password.toString()) case .failure(_): break } completion(result) }) } class func upload(image: UIImage, completion: @escaping Completion) { let path = ApiPath.User.upload guard let url = URL(string: path) else { let error = NSError(message: Strings.Errors.urlError) completion(.failure(error)) return } guard let data = UIImageJPEGRepresentation(image, 1) else { let error = NSError(message: Strings.Errors.emptyImage) completion(.failure(error)) return } let request = NSMutableURLRequest(url: url) request.httpMethod = "PUT" let boundary = "Boundary-\(NSUUID().uuidString)" request.addHeaders(boundary: boundary) request.httpBody(key: "file", value: data, boundary: boundary) let queue = DispatchQueue(label: "uploadImage", qos: .background, attributes: .concurrent) queue.async { let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, _, error) -> Void in if let error = error { DispatchQueue.main.async { completion(.failure(error)) } return } guard let data = data else { return } guard let json = data.toJSON() as? JSObject else { DispatchQueue.main.async { completion(.failure(FFError.json)) } return } DispatchQueue.main.async { Mapper<User>().map(result: .success(json), type: .object, completion: completion) } }) task.resume() } } }
mit
594fa2497753fec74b66fea7e42c5581
35.042683
132
0.512773
5.017827
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLVUserFollowingSectionView.swift
1
2749
// // SLVUserFollowingSectionView.swift // selluv-ios // // Created by 조백근 on 2017. 2. 13.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit class SLVUserFollowingSectionView: UICollectionReusableView { @IBOutlet weak var sellerImageView: UIImageView! @IBOutlet weak var sellerNameLabel: UILabel! @IBOutlet weak var mannerLabel: UILabel! @IBOutlet weak var followerCountLabel: UILabel! @IBOutlet weak var sellingItemsCountLabel: UILabel! @IBOutlet weak var soldItemsCountLabel: UILabel! @IBOutlet weak var sellerImageButton: UIButton! @IBOutlet weak var sellerNameButton: UIButton! @IBOutlet weak var mannerButton: UIButton! //매너지수(하트) @IBOutlet weak var followerButton: UIButton! //팔로워 @IBOutlet weak var salesButton: UIButton! //판매중 @IBOutlet weak var soldButton: UIButton! //거래완료 @IBOutlet weak var followButton: UIButton! var followingInfo: SLVSellerFollowing? override public func awakeFromNib() { super.awakeFromNib() } func setupData(following: SLVSellerFollowing) { self.followingInfo = following if let user = self.followingInfo { let name = user.nickname ?? "" let thumb = user.avatar ?? "" let manners = user.mannerPoint ?? 0 let followers = user.followersCount ?? 0 let sales = user.onSaleCount ?? 0 let dones = user.completeSaleCount ?? 0 self.sellerNameLabel?.text = name if thumb != "" { let dnModel = SLVDnImageModel.shared let url = URL(string: "\(dnAvatar)\(thumb)") if let url = url { dnModel.setupImageView(view: self.sellerImageView, from: url) } } self.mannerLabel.text = "\(manners)" self.followerCountLabel.text = "\(followers)" self.sellingItemsCountLabel.text = "\(sales)" self.soldItemsCountLabel.text = "\(dones)" } } //MARK: Event @IBAction func touchSellerItem(_ sender: Any) { //UserPage 이동 } @IBAction func touchReviewsItem(_ sender: Any) { //구매후기 이동 } @IBAction func touchFollowItem(_ sender: Any) { //UserPage 팔로워 이동 } //TODO: FOLLOW 처리할 것 @IBAction func touchFollow(_ sender: Any) { let userId = self.followingInfo?.followingId if let userId = userId { MyInfoDataModel.shared.userFollowing(anyUserId: userId) { (success) in } } } }
mit
c3e6399d13f3cb2042609d7b7d76bc12
29.735632
82
0.592371
4.456667
false
false
false
false
amoghvs22/StoryFlip
StoryFlip/StoryFlip/VideoConversion.swift
1
2913
// // VideoConversion.swift // StoryFlip // // Created by Mac Mini on 09/10/17. // Copyright © 2017 Borqs. All rights reserved. // import UIKit import AVFoundation import CoreGraphics import CoreMedia import ImageIO import MobileCoreServices class VideoConversion: NSObject { var videoFrames = [UIImage]() var duration: Int? func getFrame(url: URL) -> (URL, Int){ let asset:AVAsset = AVAsset(url:(url as NSURL) as URL) let assetImgGenerate:AVAssetImageGenerator = AVAssetImageGenerator(asset:asset) assetImgGenerate.appliesPreferredTrackTransform = true let duration:Float64 = CMTimeGetSeconds(asset.duration) let durationInt:Int = Int(duration) self.duration = durationInt for index:Int in 0 ..< durationInt { generateFrames(assetImgGenerate: assetImgGenerate, fromTime: Float64(index)) } return (animatedGif(from: videoFrames), Int(duration)) } func generateFrames(assetImgGenerate:AVAssetImageGenerator, fromTime:Float64) { let time:CMTime = CMTimeMakeWithSeconds(fromTime, 600) let cgImage:CGImage? do { cgImage = try assetImgGenerate.copyCGImage(at: time, actualTime: nil) let frameImg:UIImage = UIImage(cgImage:cgImage!) videoFrames.append(frameImg) } catch let error as NSError { print("Found error in saving entity changes \(error)") } } func animatedGif(from images: [UIImage]) -> URL{ let fileProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: 0]] as CFDictionary let frameProperties: CFDictionary = [kCGImagePropertyGIFDictionary as String: [(kCGImagePropertyGIFDelayTime as String): 1.0]] as CFDictionary let documentsDirectoryURL: URL? = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let filename = UUID().uuidString let fileURL: URL? = documentsDirectoryURL?.appendingPathComponent("\(filename).gif") if let url = fileURL as CFURL? { if let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, images.count, nil) { CGImageDestinationSetProperties(destination, fileProperties) for image in images { if let cgImage = image.cgImage { CGImageDestinationAddImage(destination, cgImage, frameProperties) } } if !CGImageDestinationFinalize(destination) { print("Failed to finalize the image destination") } print("Url = \(fileURL)") return fileURL! } } return URL(string: "")! } }
mit
bb1e88f59be86f8a3f4f285533e88098
36.333333
151
0.629808
5.190731
false
false
false
false
hollance/swift-algorithm-club
Bloom Filter/BloomFilter.playground/Contents.swift
3
2114
//: Playground - noun: a place where people can play public class BloomFilter<T> { fileprivate var array: [Bool] private var hashFunctions: [(T) -> Int] public init(size: Int = 1024, hashFunctions: [(T) -> Int]) { self.array = [Bool](repeating: false, count: size) self.hashFunctions = hashFunctions } private func computeHashes(_ value: T) -> [Int] { return hashFunctions.map { hashFunc in abs(hashFunc(value) % array.count) } } public func insert(_ element: T) { for hashValue in computeHashes(element) { array[hashValue] = true } } public func insert(_ values: [T]) { for value in values { insert(value) } } public func query(_ value: T) -> Bool { let hashValues = computeHashes(value) // Map hashes to indices in the Bloom Filter let results = hashValues.map { hashValue in array[hashValue] } // All values must be 'true' for the query to return true // This does NOT imply that the value is in the Bloom filter, // only that it may be. If the query returns false, however, // you can be certain that the value was not added. let exists = results.reduce(true, { $0 && $1 }) return exists } public func isEmpty() -> Bool { // As soon as the reduction hits a 'true' value, the && condition will fail. return array.reduce(true) { prev, next in prev && !next } } } /* Two hash functions, adapted from http://www.cse.yorku.ca/~oz/hash.html */ func djb2(x: String) -> Int { var hash = 5381 for char in x { hash = ((hash << 5) &+ hash) &+ char.hashValue } return Int(hash) } func sdbm(x: String) -> Int { var hash = 0 for char in x { hash = char.hashValue &+ (hash << 6) &+ (hash << 16) &- hash } return Int(hash) } /* A simple test */ let bloom = BloomFilter<String>(size: 17, hashFunctions: [djb2, sdbm]) bloom.insert("Hello world!") print(bloom.array) bloom.query("Hello world!") // true bloom.query("Hello WORLD") // false bloom.insert("Bloom Filterz") print(bloom.array) bloom.query("Bloom Filterz") // true bloom.query("Hello WORLD") // true
mit
f11207a675d6673cf5a524bfade4fe38
24.780488
80
0.635289
3.505804
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/Galleries/model/GalleryArtwork.swift
2
747
// // GalleryArtwork.swift // byuSuite // // Created by Alex Boswell on 2/9/18. // Copyright © 2018 Brigham Young University. All rights reserved. // import UIKit class GalleryArtwork: GalleryImage, Comparable { var author: String? var artDescription: String? override init(dict: [String: Any]) throws { author = dict["author"] as? String artDescription = dict["description"] as? String try super.init(dict: dict) } //MARK: Comparable Protocol static func <(lhs: GalleryArtwork, rhs: GalleryArtwork) -> Bool { return lhs.name < rhs.name } static func ==(lhs: GalleryArtwork, rhs: GalleryArtwork) -> Bool { return lhs.name == rhs.name && lhs.author == rhs.author && lhs.artDescription == rhs.artDescription } }
apache-2.0
2b8e81c6493ba7323844ecff1adacd59
23.064516
101
0.693029
3.453704
false
false
false
false
brave/browser-ios
brave/src/frontend/sync/SyncCodewordsView.swift
1
2592
/* 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 Shared class SyncCodewordsView: UIView, UITextViewDelegate { lazy var field: UITextView = { let textView = UITextView() textView.autocapitalizationType = .none textView.autocorrectionType = .yes textView.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) textView.textColor = BraveUX.GreyJ return textView }() lazy var placeholder: UILabel = { let label = UILabel() label.text = Strings.CodeWordInputHelp label.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular) label.textColor = BraveUX.GreyE label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 return label }() var wordCountChangeCallback: ((_ count: Int) -> Void)? var currentWordCount = 0 convenience init(data: [String]) { self.init() translatesAutoresizingMaskIntoConstraints = false addSubview(field) addSubview(placeholder) setCodewords(data: data) field.snp.makeConstraints { (make) in make.edges.equalTo(self).inset(20) } placeholder.snp.makeConstraints { (make) in make.top.left.right.equalTo(field).inset(UIEdgeInsetsMake(8, 4, 0, 0)) } field.delegate = self } func setCodewords(data: [String]) { field.text = data.count > 0 ? data.joined(separator: " ") : "" updateWordCount() } func codeWords() -> [String] { return field.text.separatedBy(" ").filter { $0.count > 0 } } func wordCount() -> Int { return codeWords().count } func updateWordCount() { placeholder.isHidden = (field.text.count != 0) let wordCount = self.wordCount() if wordCount != currentWordCount { currentWordCount = wordCount wordCountChangeCallback?(wordCount) } } @discardableResult override func becomeFirstResponder() -> Bool { field.becomeFirstResponder() return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return text != "\n" } func textViewDidChange(_ textView: UITextView) { updateWordCount() } }
mpl-2.0
d72e86dbdf71b48caf77930ac6448eee
29.494118
198
0.602623
4.817844
false
false
false
false
Ju2ender/objective-c-e
iOS/2.0-HelloSwift/2.0-HelloSwift/controller/MapViewController.swift
2
1789
import UIKit class MapViewController : UIViewController, MAMapViewDelegate, AMapSearchDelegate { weak var mapView: MAMapView? weak var search: AMapSearchAPI? weak var locationManager: CLLocationManager? var isFirstAppear = true // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() isFirstAppear = true // initSearch() } // 2D 栅格地图 init override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) initMapView() if isFirstAppear { mapView?.visibleMapRect = MAMapRectMake(220880104, 101476980, 272496, 466656) isFirstAppear = false } mapView?.mapType = MAMapType.Standard } // MARK: - Init methods func initMapView() { mapView = MAMapView.init(frame: self.view.bounds) mapView?.delegate = self view.addSubview(mapView!) if Float(UIDevice.currentDevice().systemVersion) >= 8.0 { locationManager = CLLocationManager?.init() locationManager?.requestAlwaysAuthorization() } } func initSearch() { AMapSearchServices.sharedServices().apiKey = APIKey search = AMapSearchAPI?.init() search?.delegate = self } // MARK: - Map Delegate func mapView(mapView: MAMapView!, didSingleTappedAtCoordinate coordinate: CLLocationCoordinate2D) { print("tap: %f, %f", coordinate.longitude, coordinate.latitude) } func mapView(mapView: MAMapView!, didLongPressedAtCoordinate coordinate: CLLocationCoordinate2D) { print("long pressed: %f, %f", coordinate.longitude, coordinate.latitude) } }
gpl-3.0
4a1383d9d10f3932294ee76a585182ad
27.269841
103
0.617069
5.016901
false
false
false
false
shaps80/InkKit
Example/InkExampleOSX/ViewController.swift
1
4926
/* Copyright © 13/05/2016 Shaps 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 Cocoa import InkKit import GraphicsRenderer class ViewController: NSViewController { } final class CanvasView: NSView { override var isFlipped: Bool { return true } // Shadow -- add replaced with draw // Draw -- replaced with context instance override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let bgFrame = dirtyRect let titleBarHeight: CGFloat = 44 let margin: CGFloat = 0 let topGuide = titleBarHeight let barFrame = CGRect(x: 0, y: 0, width: bgFrame.width, height: topGuide) let tableFrame = CGRect(x: 0, y: barFrame.maxY + margin, width: bgFrame.width, height: bgFrame.maxY - barFrame.height) guard let context = CGContext.current else { return } context.fill(rect: bgFrame, color: Color(hex: "1c3d64")!) // Table let grid = InkKit.Grid(colCount: 6, rowCount: 9, bounds: tableFrame) let path = grid.path(include: [.columns, .rows]) context.stroke(path: path, startColor: Color(white: 1, alpha: 0.15), endColor: Color(white: 1, alpha: 0.05), angleInDegrees: 90) // Cell let rect = grid.boundsForRange(sourceColumn: 2, sourceRow: 3, destinationColumn: 4, destinationRow: 6) drawCell(in: rect, title: "4x6", includeBorder: true, includeShadow: true) // Navigation Bar context.draw(shadow: .outer, path: BezierPath(rect: barFrame), color: Color(white: 0, alpha: 0.4), radius: 5, offset: CGSize(width: 0, height: 1)) context.fill(rect: barFrame, color: Color(hex: "ff0083")!) "InkKit".drawAligned(to: barFrame, attributes: [ NSAttributedStringKey.foregroundColor: Color.white.nsColor, NSAttributedStringKey.font: Font(name: "Avenir-Book", size: 20)! ]) backIndicatorImage().draw(in: CGRect(x: 20, y: 11, width: 12, height: 22)) grid.enumerateCells { (index, col, row, bounds) in "\(index)".drawAligned(to: bounds, attributes: [ NSAttributedStringKey.font: Font(name: "Avenir-Book", size: 12)!, NSAttributedStringKey.foregroundColor: Color(white: 1, alpha: 0.5).nsColor ]) } drawInnerGrid(in: grid.boundsForRange(sourceColumn: 1, sourceRow: 1, destinationColumn: 1, destinationRow: 1)) } func drawInnerGrid(in bounds: CGRect) { let grid = InkKit.Grid(colCount: 3, rowCount: 3, bounds: bounds) let path = grid.path(include: [ .outline, .columns, .rows ]) Color.white.setStroke() path.stroke() } func drawCell(in bounds: CGRect, title: String, includeBorder: Bool = false, includeShadow: Bool = false) { guard let context = CGContext.current else { return } let path = BezierPath(roundedRect: bounds, cornerRadius: 4) context.fill(path: path, color: Color(hex: "ff0083")!.with(alpha: 0.3)) if includeShadow { context.draw(shadow: .inner, path: path, color: Color(white: 0, alpha: 0.3), radius: 20, offset: CGSize(width: 0, height: 5)) } if includeBorder { context.stroke(border: .inner, path: path, color: Color(hex: "ff0083")!, thickness: 2) } title.drawAligned(to: bounds, attributes: [ NSAttributedStringKey.foregroundColor: Color.white.nsColor, NSAttributedStringKey.font: Font(name: "Avenir-Medium", size: 15)! ]) } func backIndicatorImage() -> Image { return Image.draw(width: 12, height: 22, attributes: nil, drawing: { (context, rect, attributes) in attributes.lineWidth = 2 attributes.strokeColor = Color.white let bezierPath = BezierPath() bezierPath.move(to: CGPoint(x: rect.maxX, y: rect.minY)) bezierPath.addLine(to: CGPoint(x: rect.maxX - 10, y: rect.midY)) bezierPath.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) attributes.apply(to: bezierPath) bezierPath.stroke() }) } }
mit
997789a44179cdcf63ceb754405836a1
37.178295
150
0.684467
3.991086
false
false
false
false
quickthyme/PUTcat
PUTcat/Application/Data/Transaction/Entity/PCTransaction.swift
1
3991
import Foundation final class PCTransaction: PCItem, PCCopyable, PCLocal { var id: String var name: String var method: Method = .GET var delivery : Delivery = .form var parsing : Bool = false var urlBase : String? var urlRelative : String? var headers : PCList<PCHeader>? var parameters : PCList<PCParameter>? var parsers : PCList<PCParser>? var rawBody : String? enum Method : String { case GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, TRACE, CONNECT } static let Methods : [String] = [ "GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH", "TRACE", "CONNECT" ] enum Delivery : String { case form, json } init(id: String, name: String) { self.id = id self.name = name } convenience init(name: String) { self.init(id: UUID().uuidString, name: name) } convenience init() { self.init(name: "New Transaction") } init(id: String, name: String, method: Method, delivery: Delivery, parsing: Bool, urlBase: String?, urlRelative: String?, headers: PCList<PCHeader>?, parameters: PCList<PCParameter>?, parsers: PCList<PCParser>?, rawBody: String?) { self.id = id self.name = name self.method = method self.delivery = delivery self.parsing = parsing self.urlBase = urlBase self.urlRelative = urlRelative self.headers = headers self.parameters = parameters self.parsers = parsers self.rawBody = rawBody } required convenience init(copy: PCTransaction) { self.init( id: UUID().uuidString, name: copy.name, method: copy.method, delivery: copy.delivery, parsing: copy.parsing, urlBase: copy.urlBase, urlRelative: copy.urlRelative, headers: copy.headers?.copy(), parameters: copy.parameters?.copy(), parsers: copy.parsers?.copy(), rawBody: copy.rawBody) } required init(fromLocal: [String:Any]) { self.id = fromLocal["id"] as? String ?? "" self.name = fromLocal["name"] as? String ?? "" self.method = Method(rawValue: fromLocal["method"] as? String ?? "GET") ?? .GET self.delivery = Delivery(rawValue: fromLocal["delivery"] as? String ?? "form") ?? .form self.parsing = fromLocal["parsing"] as? Bool ?? false if let urlBase = fromLocal["urlBase"] as? String { self.urlBase = Base64.decode(urlBase) } if let urlRelative = fromLocal["urlRelative"] as? String { self.urlRelative = Base64.decode(urlRelative) } if let rawBody = fromLocal["rawBody"] as? String { self.rawBody = Base64.decode(rawBody) } } func toLocal() -> [String:Any] { var local : [String:Any] = [ "id" : self.id, "name" : self.name, "method" : self.method.rawValue, "delivery" : self.delivery.rawValue, "parsing" : self.parsing ] if let urlBase = self.urlBase { local["urlBase"] = Base64.encode(urlBase) } if let urlRelative = self.urlRelative { local["urlRelative"] = Base64.encode(urlRelative) } if let rawBody = self.rawBody { local["rawBody"] = Base64.encode(rawBody) } return local } } extension PCTransaction : PCLocalExport { func toLocalExport() -> [String:Any] { var local = self.toLocal() if let array = self.headers?.toLocalExport() { local["headers"] = array } if let array = self.parameters?.toLocalExport() { local["parameters"] = array } if let array = self.parsers?.toLocalExport() { local["parsers"] = array } return local } }
apache-2.0
023f9d9d3eec75963afa748a7e47632c
29.937984
99
0.557504
4.245745
false
false
false
false
brentdax/swift
validation-test/Reflection/reflect_UInt8.swift
1
1626
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_UInt8 // RUN: %target-codesign %t/reflect_UInt8 // RUN: %target-run %target-swift-reflection-test %t/reflect_UInt8 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest class TestClass { var t: UInt8 init(t: UInt8) { self.t = t } } var obj = TestClass(t: 123) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_UInt8.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=17 alignment=1 stride=17 num_extra_inhabitants=0 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_UInt8.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=9 alignment=1 stride=9 num_extra_inhabitants=0 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
bcec929c099b8d28b78bd9ae250d23b4
30.882353
119
0.682042
3.056391
false
true
false
false
tardieu/swift
benchmark/single-source/StrToInt.swift
10
1946
//===--- StrToInt.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of String to Int conversion. // It is reported to be very slow: <rdar://problem/17255477> import TestsUtils @inline(never) public func run_StrToInt(_ N: Int) { // 64 numbers from -500_000 to 500_000 generated randomly let input = ["-237392", "293715", "126809", "333779", "-362824", "144198", "-394973", "-163669", "-7236", "376965", "-400783", "-118670", "454728", "-38915", "136285", "-448481", "-499684", "68298", "382671", "105432", "-38385", "39422", "-267849", "-439886", "292690", "87017", "404692", "27692", "486408", "336482", "-67850", "56414", "-340902", "-391782", "414778", "-494338", "-413017", "-377452", "-300681", "170194", "428941", "-291665", "89331", "329496", "-364449", "272843", "-10688", "142542", "-417439", "167337", "96598", "-264104", "-186029", "98480", "-316727", "483808", "300149", "-405877", "-98938", "283685", "-247856", "-46975", "346060", "160085",] let ref_result = 517492 func DoOneIter(_ arr: [String]) -> Int { var r = 0 for n in arr { r += Int(n)! } if r < 0 { r = -r } return r } var res = Int.max for _ in 1...1000*N { res = res & DoOneIter(input) } CheckResults(res == ref_result, "IncorrectResults in StrToInt: \(res) != \(ref_result)") }
apache-2.0
96781db6bf13acef416221e765ef3d55
40.404255
90
0.52518
3.444248
false
false
false
false
HongliYu/firefox-ios
Shared/AsyncReducer.swift
1
4366
/* 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 Deferred public let DefaultDispatchQueue = DispatchQueue.global(qos: DispatchQoS.default.qosClass) public func asyncReducer<T, U>(_ initialValue: T, combine: @escaping (T, U) -> Deferred<Maybe<T>>) -> AsyncReducer<T, U> { return AsyncReducer(initialValue: initialValue, combine: combine) } /** * A appendable, async `reduce`. * * The reducer starts empty. New items need to be `append`ed. * * The constructor takes an `initialValue`, a `dispatch_queue_t`, and a `combine` function. * * The reduced value can be accessed via the `reducer.terminal` `Deferred<Maybe<T>>`, which is * run once all items have been combined. * * The terminal will never be filled if no items have been appended. * * Once the terminal has been filled, no more items can be appended, and `append` methods will error. */ open class AsyncReducer<T, U> { // T is the accumulator. U is the input value. The returned T is the new accumulated value. public typealias Combine = (T, U) -> Deferred<Maybe<T>> fileprivate let lock = NSRecursiveLock() private let dispatchQueue: DispatchQueue private let combine: Combine private let initialValueDeferred: Deferred<Maybe<T>> public let terminal: Deferred<Maybe<T>> = Deferred() private var queuedItems: [U] = [] private var isStarted: Bool = false /** * Has this task queue finished? * Once the task queue has finished, it cannot have more tasks appended. */ open var isFilled: Bool { lock.lock() defer { lock.unlock() } return terminal.isFilled } public convenience init(initialValue: T, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.init(initialValue: deferMaybe(initialValue), queue: queue, combine: combine) } public init(initialValue: Deferred<Maybe<T>>, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) { self.dispatchQueue = queue self.combine = combine self.initialValueDeferred = initialValue } // This is always protected by a lock, so we don't need to // take another one. fileprivate func ensureStarted() { if self.isStarted { return } func queueNext(_ deferredValue: Deferred<Maybe<T>>) { deferredValue.uponQueue(dispatchQueue, block: continueMaybe) } func nextItem() -> U? { // Because popFirst is only available on array slices. // removeFirst is fine for range-replaceable collections. return queuedItems.isEmpty ? nil : queuedItems.removeFirst() } func continueMaybe(_ res: Maybe<T>) { lock.lock() defer { lock.unlock() } if res.isFailure { self.queuedItems.removeAll() self.terminal.fill(Maybe(failure: res.failureValue!)) return } let accumulator = res.successValue! guard let item = nextItem() else { self.terminal.fill(Maybe(success: accumulator)) return } let combineItem = deferDispatchAsync(dispatchQueue) { return self.combine(accumulator, item) } queueNext(combineItem) } queueNext(self.initialValueDeferred) self.isStarted = true } /** * Append one or more tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has finished already. */ open func append(_ items: U...) throws -> Deferred<Maybe<T>> { return try append(items) } /** * Append a list of tasks onto the end of the queue. * * @throws AlreadyFilled if the queue has already finished. */ open func append(_ items: [U]) throws -> Deferred<Maybe<T>> { lock.lock() defer { lock.unlock() } if terminal.isFilled { throw ReducerError.alreadyFilled } queuedItems.append(contentsOf: items) ensureStarted() return terminal } } enum ReducerError: Error { case alreadyFilled }
mpl-2.0
e39cdca4deb9bce040fcec2ddb8540fe
30.410072
124
0.631699
4.562173
false
false
false
false
RailwayStations/Bahnhofsfotos
iOS/Presentation/MapScene/StationDetails/PhotoViewController.swift
1
9604
// // PhotoViewController.swift // Bahnhofsfotos // // Created by Miguel Dönicke on 17.12.16. // Copyright © 2016 MrHaitec. All rights reserved. // import Combine import Data import Domain import Imaginary import ImagePicker import Lightbox import MessageUI import SwiftyUserDefaults import UIKit class PhotoViewController: UIViewController { private var uploadCancellable: AnyCancellable? private lazy var photoUseCase: PhotosUseCase = { PhotosUseCase(photosRepository: PhotosRepository()) }() @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var shareBarButton: UIBarButtonItem! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet weak var progressView: UIProgressView! var savedPhoto: Photo? override func viewDidLoad() { super.viewDidLoad() title = StationStorage.currentStation?.name shareBarButton.isEnabled = false progressView.alpha = 0 guard let station = StationStorage.currentStation else { return } if station.hasPhoto { if let photoUrl = station.photoUrl, let imageUrl = URL(string: photoUrl) { imageView.image = nil activityIndicatorView.startAnimating() imageView.setImage(url: imageUrl) { result in self.activityIndicatorView.stopAnimating() } } } else { do { savedPhoto = try PhotoStorage.fetch(id: station.id) if let photo = savedPhoto { imageView.image = UIImage(data: photo.data) // allow to share assigned photo if photo.uploadedAt == nil { shareBarButton.isEnabled = true } } } catch { debugPrint(error.localizedDescription) } } } @IBAction func pickImage(_ sender: Any) { guard let station = StationStorage.currentStation else { return } if station.hasPhoto && imageView.image != nil { LightboxConfig.PageIndicator.enabled = false var image: LightboxImage if let license = station.license, let photographer = station.photographer { let text = license + " - " + photographer image = LightboxImage(image: imageView.image!, text: text, videoURL: nil) } else { image = LightboxImage(image: imageView.image!) } let lightboxController = LightboxController(images: [image], startIndex: 0) present(lightboxController, animated: true, completion: nil) return } let configuration = ImagePickerConfiguration() configuration.allowMultiplePhotoSelection = false configuration.allowedOrientations = .landscape configuration.cancelButtonTitle = "Abbruch" configuration.doneButtonTitle = "Fertig" let imagePicker = ImagePickerController(configuration: configuration) imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } @IBAction func shareTouched(_ sender: Any) { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // Share by upload if Defaults.uploadToken != nil { var title = "Direkt-Upload" if let size = getSizeStringOfImage() { title += " [\(size)]" } controller.addAction(UIAlertAction(title: title, style: .default) { _ in self.shareByUpload() }) } // Share by email if CountryStorage.currentCountry?.email != nil { controller.addAction(UIAlertAction(title: "E-Mail", style: .default) { _ in self.shareByEmail() }) } // Share by installed apps controller.addAction(UIAlertAction(title: "Sonstiges", style: .default) { _ in self.shareByOthers() }) controller.addAction(UIAlertAction(title: "Schließen", style: .cancel, handler: nil)) present(controller, animated: true, completion: nil) } @IBAction func closeTouched(_ sender: Any) { navigationController?.popViewController(animated: true) } @IBAction func openNavigation(_ sender: Any) { if let station = StationStorage.currentStation { Helper.openNavigation(to: station) } } // Share via twitter private func shareByUpload() { guard let image = imageView.image else { return } guard let station = StationStorage.currentStation, let country = CountryStorage.currentCountry else { return } if let imageData = UIImageJPEGRepresentation(image, 0.5) { Helper.setIsUserInteractionEnabled(in: self, to: false) activityIndicatorView.startAnimating() progressView.alpha = 1 progressView.progress = 0 imageView.isHidden = true uploadCancellable = photoUseCase.uploadPhoto(imageData, station: station, country: country) .sink { completion in switch completion { case .finished: Helper.setIsUserInteractionEnabled(in: self, to: true) self.activityIndicatorView.stopAnimating() self.progressView.progress = 1 self.progressView.alpha = 0 self.imageView.isHidden = false self.showError("Foto wurde erfolgreich hochgeladen") self.setPhotoAsShared() case .failure(let error): if let error = error as? API.Error, case .message(let msg) = error { self.showError(msg) } else { self.showError(error.localizedDescription) } } } receiveValue: { _ in } } } // Share by sending an email private func shareByEmail() { guard let station = StationStorage.currentStation, let country = CountryStorage.currentCountry else { return } guard let image = imageView.image else { return } if MFMailComposeViewController.canSendMail() { if let email = CountryStorage.currentCountry?.email { guard let username = Defaults.accountName else { showError("Kein Accountname hinterlegt. Bitte unter \"Einstellungen\" angeben.") return } var text = "Bahnhof: \(station.name)\n" text += "Lizenz: CC0\n" text += "Verlinkung: \(Defaults.accountLinking == true ? "Ja" : "Nein")\n" text += "Accounttyp: \(Defaults.accountType)\n" text += "Accountname: \(username)" let mailController = MFMailComposeViewController() mailController.mailComposeDelegate = self mailController.setToRecipients([email]) mailController.setSubject("Neues Bahnhofsfoto: \(station.name)") mailController.setMessageBody(text, isHTML: false) if let data = UIImageJPEGRepresentation(image, 1) { mailController.addAttachmentData(data, mimeType: "image/jpeg", fileName: "\(username)-\(country.code.lowercased())-\(station.id).jpg") } present(mailController, animated: true, completion: nil) } } else { showError("Es können keine E-Mails verschickt werden.") } } // Share by using installed apps private func shareByOthers() { guard let station = StationStorage.currentStation else { return } guard let image = imageView.image else { return } guard let country = CountryStorage.currentCountry else { return } let text = "\(station.name) \(country.twitterTags ?? "")" let activityController = UIActivityViewController(activityItems: [station.name, image, text], applicationActivities: nil) present(activityController, animated: true, completion: nil) } // Show error message private func showError(_ error: String) { let alert = UIAlertController(title: nil, message: error, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } // Set photo as shared private func setPhotoAsShared() { shareBarButton.isEnabled = false savedPhoto?.uploadedAt = Date() guard let photo = savedPhoto else { return } try? PhotoStorage.save(photo) } private func getSizeStringOfImage() -> String? { guard let image = imageView.image, let data = UIImageJPEGRepresentation(image, 1) else { return nil } let sizeInMegaBytes = Double(data.count) / 1024 / 1024 let numberFormatter = NumberFormatter() numberFormatter.minimumFractionDigits = 1 numberFormatter.maximumFractionDigits = 1 if let readableSize = numberFormatter.string(from: NSNumber(value: sizeInMegaBytes)) { return "\(readableSize) MB" } return nil } } // MARK: - ImagePickerDelegate extension PhotoViewController: ImagePickerDelegate { func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { imagePicker.showGalleryView() } func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { if !images.isEmpty { imageView.image = images[0] shareBarButton.isEnabled = true if let station = StationStorage.currentStation, let imageData = UIImageJPEGRepresentation(images[0], 1) { let photo = Photo(data: imageData, withId: station.id) try? PhotoStorage.save(photo) self.savedPhoto = photo } } imagePicker.dismiss(animated: true, completion: nil) } func cancelButtonDidPress(_ imagePicker: ImagePickerController) { imagePicker.dismiss(animated: true, completion: nil) } } // MARK: - MFMailComposeViewControllerDelegate extension PhotoViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if result == .sent { setPhotoAsShared() } controller.dismiss(animated: true, completion: nil) } }
apache-2.0
7e997525e3eb5a85bd3908c00899978b
33.163701
144
0.681354
4.637681
false
false
false
false
narner/AudioKit
AudioKit/iOS/AudioKit/User Interface/AKTableView.swift
1
2105
// // AKTableView.swift // AudioKit // // Created by Aurelius Prochazka, revision7. // Copyright © 2017 AudioKit. All rights reserved. // import UIKit /// Displays the values in the table into a nice graph public class AKTableView: UIView { var table: AKTable var absmax: Double = 1.0 /// Initialize the table view @objc public init(_ table: AKTable, frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 150)) { self.table = table super.init(frame: frame) let max = Double(table.max() ?? 1.0) let min = Double(table.min() ?? -1.0) absmax = [max, abs(min)].max() ?? 1.0 } /// Required initializer required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Draw the table view override public func draw(_ rect: CGRect) { let width = Double(frame.width) let height = Double(frame.height) / 2.0 let padding = 0.9 let border = UIBezierPath(rect: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)) let bgcolor = AKStylist.sharedInstance.nextColor bgcolor.setFill() border.fill() UIColor.black.setStroke() border.lineWidth = 8 border.stroke() let midline = UIBezierPath() midline.move(to: CGPoint(x: 0, y: frame.height / 2)) midline.addLine(to: CGPoint(x: frame.width, y: frame.height / 2)) UIColor.black.setStroke() midline.lineWidth = 1 midline.stroke() let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 0.0, y: (1.0 - table[0] / absmax) * height)) for i in 1..<table.count { let x = Double(i) / table.count * width let y = (1.0 - table[i] / absmax * padding) * height bezierPath.addLine(to: CGPoint(x: x, y: y)) } bezierPath.addLine(to: CGPoint(x: Double(frame.width), y: (1.0 - table[0] / absmax * padding) * height)) UIColor.black.setStroke() bezierPath.lineWidth = 2 bezierPath.stroke() } }
mit
467430edab7c88b0892ed534358ae872
28.633803
112
0.590304
3.737123
false
false
false
false
jeremiahyan/ResearchKit
ResearchKit/ActiveTasks/ORKSwiftStroopStepViewController.swift
2
9095
/* Copyright (c) 2019, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import ResearchKit.Private public class ORKSwiftStroopStepViewController: ORKActiveStepViewController { private let stroopContentView = ORKSwiftStroopContentView() private var colors = [String: UIColor]() private var differentColorLabels = [String: [UIColor]]() private var questionNumber = 0 private let red = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) private let green = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0) private let blue = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) private let yellow = UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0) private let redString = ORKSwiftLocalizedString("STROOP_COLOR_RED", "") private let greenString = ORKSwiftLocalizedString("STROOP_COLOR_GREEN", "") private let blueString = ORKSwiftLocalizedString("STROOP_COLOR_BLUE", "") private let yellowString = ORKSwiftLocalizedString("STROOP_COLOR_YELLOW", "") private var nextQuestionTimer: Timer? private var results: NSMutableArray? private var startTime: TimeInterval? private var endTime: TimeInterval? public override init(step: ORKStep?) { super.init(step: step) suspendIfInactive = true } internal required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func stroopStep() -> ORKSwiftStroopStep { return step as! ORKSwiftStroopStep } public override func viewDidLoad() { super.viewDidLoad() results = NSMutableArray() colors[redString] = red colors[blueString] = blue colors[yellowString] = yellow colors[greenString] = green differentColorLabels[redString] = [blue, green, yellow] differentColorLabels[blueString] = [red, green, yellow] differentColorLabels[yellowString] = [red, blue, green] differentColorLabels[greenString] = [red, blue, yellow] activeStepView?.activeCustomView = stroopContentView activeStepView?.customContentFillsAvailableSpace = true stroopContentView.redButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) stroopContentView.greenButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) stroopContentView.blueButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) stroopContentView.yellowButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) } @objc private func buttonPressed(sender: Any) { if stroopContentView.colorLabelText != " " { setButtonDisabled() if let button = sender as? ORKBorderedButton { if button == stroopContentView.redButton { createResult(color: (colors as NSDictionary).allKeys(for: stroopContentView.colorLabelColor!).first as? String ?? "", withText: stroopContentView.colorLabelText!, withColorSelected: redString) } else if button == stroopContentView.greenButton { createResult(color: (colors as NSDictionary).allKeys(for: stroopContentView.colorLabelColor!).first as? String ?? "", withText: stroopContentView.colorLabelText!, withColorSelected: greenString) } else if button == stroopContentView.blueButton { createResult(color: (colors as NSDictionary).allKeys(for: stroopContentView.colorLabelColor!).first as? String ?? "", withText: stroopContentView.colorLabelText!, withColorSelected: blueString) } else if button == stroopContentView.yellowButton { createResult(color: (colors as NSDictionary).allKeys(for: stroopContentView.colorLabelColor!).first as? String ?? "", withText: stroopContentView.colorLabelText!, withColorSelected: yellowString) } nextQuestionTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(startNextQuestionOrFinish), userInfo: nil, repeats: false) } } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) start() } public override func stepDidFinish() { super.stepDidFinish() stroopContentView.finishStep(self) goForward() } public override var result: ORKStepResult? { let stepResult = super.result if results != nil { stepResult?.results = results?.copy() as? [ORKResult] } return stepResult! } public override func start() { super.start() startQuestion() } private func createResult(color: String, withText text: String, withColorSelected colorSelected: String) { let stroopResult = ORKSwiftStroopResult(identifier: (step!.identifier)) stroopResult.startTime = startTime stroopResult.endTime = ProcessInfo.processInfo.systemUptime stroopResult.color = color stroopResult.text = text stroopResult.colorSelected = colorSelected results?.add(stroopResult) } @objc private func startNextQuestionOrFinish() { if nextQuestionTimer != nil { nextQuestionTimer?.invalidate() nextQuestionTimer = nil } questionNumber += 1 if questionNumber == stroopStep().numberOfAttempts { finish() } else { startQuestion() } } private func startQuestion() { let pattern: Int = Int(arc4random()) % 2 if pattern == 0 { let index: Int = Int(arc4random()) % differentColorLabels.keys.count let text = Array(differentColorLabels.keys)[index] stroopContentView.setColorLabelText(colorLabelText: text) let color = colors[text]! stroopContentView.colorLabelColor = color stroopContentView.setColorLabelColor(colorLabelColor: color) } else { let index: Int = Int(arc4random()) % differentColorLabels.keys.count let text = Array(differentColorLabels.keys)[index] stroopContentView.setColorLabelText(colorLabelText: text) let colorArray = differentColorLabels[text]! let randomColorIndex = Int(arc4random()) % colorArray.count let color = colorArray[randomColorIndex] stroopContentView.setColorLabelColor(colorLabelColor: color) } setButtonsEnabled() startTime = ProcessInfo.processInfo.systemUptime } private func setButtonDisabled() { stroopContentView.redButton.isEnabled = false stroopContentView.greenButton.isEnabled = false stroopContentView.blueButton.isEnabled = false stroopContentView.yellowButton.isEnabled = false } private func setButtonsEnabled() { stroopContentView.redButton.isEnabled = true stroopContentView.greenButton.isEnabled = true stroopContentView.blueButton.isEnabled = true stroopContentView.yellowButton.isEnabled = true } }
bsd-3-clause
25da7f8f05f976b5a178480d270e69f3
43.365854
215
0.664101
4.802006
false
false
false
false
AlexLittlejohn/Weight
Weight/Middleware/SaveWeightMiddleware.swift
1
1015
// // SaveWeightMiddleware.swift // Weight // // Created by Alex Littlejohn on 2016/02/21. // Copyright © 2016 Alex Littlejohn. All rights reserved. // import UIKit import ReSwift import RealmSwift let SaveWeightMiddleware: Middleware<AppState> = { dispatch, getState in return { next in return { action in // if let addWeightAction = action as? AddWeightAction { // // let weightDBO = WeightDBO() // let weight = addWeightAction.weight // weightDBO.weight = weight.weight // weightDBO.date = weight.date // weightDBO.unit = weight.unit.rawValue // // guard let realm = try? Realm() else { // return next(action) // } // // try! realm.write { // realm.add(weightDBO) // } // } return next(action) } } }
mit
36e84001340f4837223b4e517db1a855
26.405405
72
0.488166
4.333333
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/Logic/Request/CIOTrackRecommendationResultsViewData.swift
1
2061
// // CIOTrackRecommendationResultsViewData.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating the parameters that must/can be set set in order to track browse result click */ struct CIOTrackRecommendationResultsViewData: CIORequestData { let podID: String let url: String let numResultsViewed: Int? let resultPage: Int? let resultCount: Int? let sectionName: String? let resultID: String? func url(with baseURL: String) -> String { return String(format: Constants.TrackRecommendationResultsView.format, baseURL) } init(podID: String, numResultsViewed: Int? = nil, resultPage: Int? = nil, resultCount: Int? = nil, sectionName: String? = nil, resultID: String? = nil, url: String = "Not Available") { self.podID = podID self.url = url self.numResultsViewed = numResultsViewed self.resultPage = resultPage self.resultCount = resultCount self.sectionName = sectionName self.resultID = resultID } func decorateRequest(requestBuilder: RequestBuilder) {} func httpMethod() -> String { return "POST" } func httpBody(baseParams: [String: Any]) -> Data? { var dict = [ "pod_id": self.podID, "url": self.url ] as [String: Any] if self.numResultsViewed != nil { dict["num_results_viewed"] = self.numResultsViewed } if self.resultPage != nil { dict["result_page"] = self.resultPage } if self.resultCount != nil { dict["result_count"] = self.resultCount } if self.sectionName != nil { dict["section"] = self.sectionName } if self.resultID != nil { dict["result_id"] = self.resultID } dict["beacon"] = true dict.merge(baseParams) { current, _ in current } return try? JSONSerialization.data(withJSONObject: dict) } }
mit
8a413ff1e67add191c3ec37cb9ed76f6
28.014085
188
0.615534
4.153226
false
false
false
false
makma/cloud-sdk-swift
Example/KenticoCloud/ViewControllers/Cafe/CafeDetailViewController.swift
1
2637
// // CafeDetailViewController.swift // KenticoCloud // // Created by Martin Makarsky on 17/08/2017. // Copyright © 2017 Kentico Software. All rights reserved. // import UIKit import MapKit import KenticoCloud class CafeDetailViewController: UIViewController { // MARK: Properties var cafe: Cafe? var image: UIImage? @IBOutlet var name: UILabel! @IBOutlet var email: UILabel! @IBOutlet weak var city: UILabel! @IBOutlet weak var address: UILabel! @IBOutlet weak var phone: UILabel! @IBOutlet weak var photo: UIImageView! @IBOutlet weak var map: MKMapView? @IBOutlet var backButton: UIButton! // MARK: VC lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { backButton.stylePinkButton() SetContent() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Outlet actions @IBAction func navigateBack(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } // MARK: Behaviour private func SetContent() { if let cafe = cafe { name.text = cafe.name city.text = cafe.city address.text = "\(cafe.street ?? "") \(cafe.city ?? "")" phone.text = cafe.phone email.text = cafe.email setImages() setMap(cafe: cafe) } } private func setMap(cafe: Cafe) { let address = "\(cafe.street ?? "") \(cafe.state ?? "") \(cafe.country ?? "") \(cafe.zip ?? "")" let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(address) { (placemarks, error) in guard let placemarks = placemarks, let location = placemarks.first?.location else { // handle no location found return } let pinPoint = MKPointAnnotation() pinPoint.coordinate = location.coordinate pinPoint.title = cafe.name self.map?.addAnnotation(pinPoint) let region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)) self.map?.setRegion(region, animated: true) } } private func setImages() { if (photo) != nil { self.photo.image = image } else { self.photo.image = UIImage(named: "noContent") } } }
mit
17a2b70c15714d73fb5d76d07d381b93
27.042553
141
0.566768
4.810219
false
false
false
false
grimcoder/fourthstep
FourthStep/FourthStep/ResentmentView.swift
1
1235
import UIKit class ResentmentView: UIViewController { var resentment: Resentment? = nil @IBOutlet weak var WhoTextBox: UITextField! @IBOutlet weak var WhoLabel: UILabel! @IBOutlet weak var AffectedTextBox: UITextView! @IBOutlet weak var DidWhatTextBox: UITextView! @IBAction func Save(sender: AnyObject) { if resentment != nil { resentment?.who = WhoTextBox.text resentment?.didwhat = DidWhatTextBox.text resentment?.affectedMy = AffectedTextBox.text } else{ Resentment.createInManagedObjectContext(ObjectContext.managedObjectContext, who: WhoTextBox.text!, didwhat: DidWhatTextBox.text, affectedMy: AffectedTextBox.text) } do { try ObjectContext.managedObjectContext.save() } catch{ } navigationController?.popViewControllerAnimated(true) } override func viewDidLoad() { WhoTextBox.text = resentment?.who AffectedTextBox.text = resentment?.affectedMy DidWhatTextBox.text = resentment?.didwhat } }
mit
a7ec4d3241a34f9197cf3a03a66fff17
25.276596
174
0.591093
5.167364
false
false
false
false
smartnsoft/Extra
Extra/Classes/UIKit/UIViewController+Extra.swift
1
6631
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // 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. extension Extra where Base: UIViewController { /// Returns the current application's top most view controller. public static func topMost() -> UIViewController? { let rootViewController = UIApplication.shared.windows.first?.rootViewController return self.topMost(of: rootViewController) } /// Returns the top most view controller from given view controller's stack. public static func topMost(of viewController: UIViewController?) -> UIViewController? { // UITabBarController if let tabBarController = viewController as? UITabBarController, let selectedViewController = tabBarController.selectedViewController { return self.topMost(of: selectedViewController) } // UINavigationController if let navigationController = viewController as? UINavigationController, let visibleViewController = navigationController.visibleViewController { return self.topMost(of: visibleViewController) } // presented view controller if let presentedViewController = viewController?.presentedViewController { return self.topMost(of: presentedViewController) } // child view controller for subview in viewController?.view?.subviews ?? [] { if let childViewController = subview.next as? UIViewController { return self.topMost(of: childViewController) } } return viewController } /// Simply programmatically adding a child view controller /// /// - parameter childController: The embeded child view controller /// - parameter container: The destination container view /// - parameter insets: The desired insets betwenn you child and its container public func addChildViewController( _ childController: UIViewController, in container: UIView, insets: UIEdgeInsets = .zero) { if let childView = childController.view { self.base.addChild(childController) childView.frame = container.bounds container.ex.addSubview(childView, insets: insets) childController.didMove(toParent: self.base) } else { fatalError("Your view controller \(childController) does not contain any view") } } /// Remove the desired childViewController properly from its parent /// /// - Parameter childViewController: child controller to remove public func removeChildViewController(_ childViewController: UIViewController) { childViewController.willMove(toParent: nil) childViewController.view.removeFromSuperview() childViewController.removeFromParent() } /// Switch between child view controllers /// /// - parameter originController: The potential current controller already displayed in your container view /// - parameter destinationController: The new child that will be displayed /// - parameter viewContainer: Your child view container /// - parameter duration: Specify the animation duration. Default 0, set a value > 0 to enable animation /// - parameter transitionOptions: Your switch transition animation options /// - parameter completion: Completion block when animation completes public func switchChilds( from originController: UIViewController?, to destinationController: UIViewController, in viewContainer: UIView, duration: TimeInterval = 0.3, transitionOptions: UIView.AnimationOptions = .transitionCrossDissolve, insets: UIEdgeInsets = .zero, completion: ((Bool) -> Void)? = nil) { guard destinationController != originController else { return } destinationController.view.frame = viewContainer.bounds destinationController.view.layoutIfNeeded() if let originController = originController { originController.willMove(toParent: nil) self.base.addChild(destinationController) self.base.transition(from: originController, to: destinationController, duration: duration, options: transitionOptions, animations: { viewContainer.ex.setSubviewConstraints(destinationController.view) }, completion: { completed in originController.removeFromParent() destinationController.didMove(toParent: self.base) completion?(completed) }) } else { destinationController.view.alpha = 0 self.addChildViewController(destinationController, in: viewContainer, insets: insets) UIView.animate(withDuration: duration, animations: { destinationController.view.alpha = 1 }, completion: { finished in completion?(finished) }) } } /// Dismiss all presented view controllers recursively. /// /// - parameter animated: indicates if all dismiss needs to be animated. /// - parameter completion: completion called when all presented view controllers have been dismissed. public func dismissAllPresented(animated: Bool = false, completion: (() -> Swift.Void)? = nil) { DispatchQueue.main.async { if let presentedViewController = self.base.presentedViewController { presentedViewController.ex.dismissAllPresented(animated: animated) presentedViewController.dismiss(animated: animated, completion: completion) } else { completion?() } } } }
mit
5af5c104eae5b396fbf8ba7da095d115
41.780645
119
0.69914
5.624258
false
false
false
false
elm4ward/BlackNest
BlackNest/Spec.swift
1
3378
// // specRun.swift // BlackNest // // Created by Elmar Kretzer on 22.08.16. // Copyright © 2016 symentis GmbH. 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. // -------------------------------------------------------------------------------- // MARK: - EvaluatableSpec // -------------------------------------------------------------------------------- /// Build on top of HasRun. /// This protocol wraps `run`, `input` and `expected`. /// Run starts by calling `evaluate` public protocol EvaluatableSpec: HasRun { var input: I { get } var expected: E { get } func evaluate() throws -> O } // -------------------------------------------------------------------------------- // MARK: - Spec // // This has everything. The input, the expected, the run. // We can start to run! // -------------------------------------------------------------------------------- /// Spec /// A Spec has all: input, expected and run. public struct Spec<I, E, O>: EvaluatableSpec { public let run: RunFunction<I, E, O> public let input: I public let expected: E public func evaluate() throws -> O { return try run(input, expected) } } // -------------------------------------------------------------------------------- // MARK: - SpecCombinator which moves on // -------------------------------------------------------------------------------- /// It's called SpecCombinator because why not. /// This is a Type for using the method `then` in order to combine tests. public struct SpecCombinator<I> { let input: I? @discardableResult public func then<E, O>(_ breeding: @escaping RunFunction<I, E, O>, is expected: E, line: UInt = #line, file: StaticString = #file) -> SpecCombinator<O> { guard let input = input else { return SpecCombinator<O>(input: nil) } return expect(input, in: breeding => expected, line: line, file: file) } @discardableResult public func then<E, O>(_ waitingForInput: RunWithExpected<I, E, O>, line: UInt = #line, file: StaticString = #file) -> SpecCombinator<O> { guard let input = input else { return SpecCombinator<O>(input: nil) } return expect(input, in: waitingForInput.run => waitingForInput.expected, line: line, file: file) } }
mit
5c37d41f1ad86cf67ea00149c65c166d
39.202381
101
0.579805
4.551213
false
false
false
false
natecook1000/swift
test/IRGen/objc_class_export.swift
2
5943
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK-DAG: %swift.refcounted = type // CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK-DAG: [[INT:%TSi]] = type <{ i64 }> // CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }> // CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }> // CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }> // CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK-DAG: [[OBJC:%objc_object]] = type opaque // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 129, // CHECK: i32 40, // CHECK: i32 40, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 128, // CHECK: i32 16, // CHECK: i32 24, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: @_IVARS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: _PROPERTIES__TtC17objc_class_export3Foo // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @"$S17objc_class_export3FooCMf" = internal global <{{.*i64}} }> <{ // CHECK: void ([[FOO]]*)* @"$S17objc_class_export3FooCfD", // CHECK: i8** @"$SBOWV", // CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1), // CHECK: [[FOO]]* (%swift.type*)* @"$S17objc_class_export3FooC6createACyFZ", // CHECK: void (double, double, double, double, [[FOO]]*)* @"$S17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF" // CHECK: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @"$S17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$S17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$S17objc_class_export3FooCN" import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { @objc var x = 0 @objc class func create() -> Foo { return Foo() } @objc func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @"$S17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @"$S17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } @objc func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @"$S17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$S17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]]) @objc func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @"$S17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @"$S17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @"$S17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo" func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_ @objc init() { } }
apache-2.0
df2feb1a9e9ccd6c60a4ef47f2147bd2
49.794872
219
0.63823
3.124606
false
false
false
false
gnachman/iTerm2
sources/IdempotentOperationJoiner.swift
2
2487
// // IdempotentOperationJoiner.swift // iTerm2SharedARC // // Created by George Nachman on 12/29/21. // import Foundation @objc(iTermIdempotentOperationScheduler) protocol IdempotentOperationScheduler: AnyObject { func scheduleIdempotentOperation(_ closure: @escaping () -> Void) } // Simplifies setNeedsUpdate/updateIfNeeded. Performs the last closure given to setNeedsUpdate(_:) // when updateIfNeeded() is called. Thread-safe. // // Sample usage: // // class Example { // private joiner = IdempotentOperationJoiner.asyncJoiner(.main) // func scheduleRedraw() { // joiner.setNeedsUpdate { [weak self] in redraw() } // } // func redraw() { // …do something expensive… // } // } @objc(iTermIdempotentOperationJoiner) class IdempotentOperationJoiner: NSObject { typealias Closure = () -> Void private var lastClosure = MutableAtomicObject<Closure?>(nil) private var invalidated = false // This closure's job is to cause updateIfNeeded() to be called eventually. It is run when // lastClosure goes from nil to nonnil. private let scheduler: ((IdempotentOperationJoiner) -> Void) // Schedules updates to run on the next spin of the main loop. @objc static func asyncJoiner(_ queue: DispatchQueue) -> IdempotentOperationJoiner { return IdempotentOperationJoiner() { joiner in queue.async { joiner.updateIfNeeded() } } } @objc(joinerWithScheduler:) static func joiner(_ scheduler: IdempotentOperationScheduler) -> IdempotentOperationJoiner { return IdempotentOperationJoiner() { [weak scheduler] joiner in scheduler?.scheduleIdempotentOperation { joiner.updateIfNeeded() } } } private override init() { fatalError() } private init(_ scheduler: @escaping (IdempotentOperationJoiner) -> Void) { self.scheduler = scheduler } @objc(setNeedsUpdateWithBlock:) func setNeedsUpdate(_ closure: @escaping Closure) { let previous = lastClosure.getAndSet(closure) if previous == nil { scheduler(self) } } @objc func updateIfNeeded() { guard !invalidated else { return } guard let maybeClosure = lastClosure.getAndSet(nil) else { return } maybeClosure() } @objc func invalidate() { invalidated = true } }
gpl-2.0
56e2d7322879c1d7acd137458345b4cc
26.588889
98
0.641563
4.547619
false
false
false
false
hivinau/LivingElectro
iOS/LivingElectro/LivingElectro/Home.swift
1
1841
// // Home.swift // LivingElectro // // Created by Aude Sautier on 13/05/2017. // Copyright © 2017 Hivinau GRAFFE. All rights reserved. // import UIKit @objc(Home) public class Home: UIViewController, TitlesDelegate, PartsDelegate { @IBOutlet weak var imageView: UIImageView! private var titles: Titles? private var parts: Parts? public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } public func titles(_ titles: Titles, didSelectRowAt indexPath: IndexPath) { parts?.selectRow(at: indexPath) } public func parts(_ parts: Parts, didSelectRowAt indexPath: IndexPath) { titles?.selectRow(at: indexPath) } public override func viewDidLoad() { super.viewDidLoad() imageView.image = UIImage(named: "app_background") imageView.contentMode = .scaleAspectFill titles?.titlesDelegate = self parts?.partsDelegate = self if let genres = LocalizableHelper.value(for: "genres") as? [String] { titles?.genres = genres genres.forEach { genre in parts?.addSongs(for: genre) } } let indexPath = IndexPath(row: 0, section: 0) titles?.selectRow(at: indexPath) parts?.selectRow(at: indexPath) } public override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let titles = segue.destination as? Titles { self.titles = titles } else if let parts = segue.destination as? Parts { self.parts = parts } } }
mit
b4a0324abca9bcb2496174a13759059a
24.915493
79
0.566304
5
false
false
false
false
jamesdouble/JDGamesLoading
JDGamesLoading/JDGamesLoading/JDGamesConfiguration.swift
1
1395
// // JDGamesConfiguration.swift // JDGamesLoading // // Created by 郭介騵 on 2017/5/11. // Copyright © 2017年 james12345. All rights reserved. // import UIKit public class JDGamesConfiguration { } public class JDPingPongConfiguration:JDGamesConfiguration{ var paddle_color:UIColor = UIColor.white var ball_color:UIColor = UIColor.white init(paddlecolor:UIColor,ballcolor:UIColor) { paddle_color = paddlecolor ball_color = ballcolor } } public class JDSnackGameConfiguration:JDGamesConfiguration{ var Snack_color:UIColor = UIColor.green var Food_color:UIColor = UIColor.white var Snack_Speed:CGFloat = 10.0 init(snackcolor:UIColor,foodcolor:UIColor,snackspeed:CGFloat) { Snack_color = snackcolor Food_color = foodcolor Snack_Speed = snackspeed } } public class JDBreaksGameConfiguration:JDGamesConfiguration{ var paddle_color:UIColor = UIColor.white var ball_color:UIColor = UIColor.white var block_color:UIColor = UIColor.white var RowCount:Int = 1 var ColumnCount:Int = 3 init(paddlecolor:UIColor,ballcolor:UIColor,blockcolor:UIColor,RowCount:Int,ColumnCount:Int) { paddle_color = paddlecolor ball_color = ballcolor block_color = blockcolor self.RowCount = RowCount self.ColumnCount = ColumnCount } }
mit
a74f42f7ce51f0b83ff537e0ee66753b
24.2
95
0.694805
3.786885
false
true
false
false
turingcorp/gattaca
Pods/GifHero/gifhero/Source/Extensions/CGSizeExtension.swift
1
1465
import UIKit extension CGSize { public func fittingRectFor( width:CGFloat, height:CGFloat, contentMode:UIViewContentMode) -> CGRect { let ratioWidth:CGFloat = width / self.width let ratioHeight:CGFloat = height / self.height let ratio:CGFloat = ratioFor( contentMode:contentMode, ratioA:ratioWidth, ratioB:ratioHeight) let scaledWidth:CGFloat = width / ratio let scaledHeight:CGFloat = height / ratio let remainWidth:CGFloat = self.width - scaledWidth let remainHeight:CGFloat = self.height - scaledHeight let marginX:CGFloat = remainWidth / 2.0 let marginY:CGFloat = remainHeight / 2.0 let drawingRect:CGRect = CGRect( x:marginX, y:marginY, width:scaledWidth, height:scaledHeight) return drawingRect } //MARK: private private func ratioFor( contentMode:UIViewContentMode, ratioA:CGFloat, ratioB:CGFloat) -> CGFloat { let ratio:CGFloat switch contentMode { case UIViewContentMode.scaleAspectFit: ratio = max(ratioA, ratioB) break default: ratio = min(ratioA, ratioB) break } return ratio } }
mit
fc676bc028a3a257372ffae5263ab4b3
23.830508
61
0.537201
5.250896
false
false
false
false
ilyapuchka/SwiftNetworking
SwiftNetworking/APIRequestTask.swift
1
2170
// // APIRequestTask.swift // SwiftNetworking // // Created by Ilya Puchka on 16.08.15. // Copyright © 2015 Ilya Puchka. All rights reserved. // import Foundation final public class APIRequestTask: Task, Resumable, Cancellable, Equatable { public typealias TaskIdentifier = Int var onCancel: ((APIRequestTask, ErrorType?) -> ())? private var completionHandlers: [APIResponseDecodable -> Void] = [] public func addCompletionHandler(handler: APIResponseDecodable -> Void) { completionHandlers.append(handler) } let session: NSURLSession let requestBuilder: () throws -> NSURLRequest private static var requestTasksCounter = 0 init(request: APIRequestType, session: NSURLSession, requestBuilder: APIRequestType throws -> NSURLRequest) { self.taskIdentifier = ++APIRequestTask.requestTasksCounter self.session = session self.requestBuilder = { () throws -> NSURLRequest in return try requestBuilder(request) } } private(set) public var taskIdentifier: TaskIdentifier private var sessionTask: NSURLSessionTask! var originalRequest: NSURLRequest? { get { return sessionTask?.originalRequest } } func isTaskForSessionTask(task: NSURLSessionTask) -> Bool { if let sessionTask = sessionTask { return sessionTask === task } return false } } //MARK: - Resumable extension APIRequestTask { func resume() { do { let httpRequest = try requestBuilder() sessionTask = self.session.dataTaskWithRequest(httpRequest) sessionTask.resume() } catch { cancel(error) } } } //MARK: - Cancellable extension APIRequestTask { func cancel(error: ErrorType?) { if let sessionTask = sessionTask { sessionTask.cancel() } else { onCancel?(self, error) onCancel = nil } } } public func ==(left: APIRequestTask, right: APIRequestTask) -> Bool { return left.taskIdentifier == right.taskIdentifier }
mit
5aab348469fc7565b4a91c6338a6c96d
25.463415
113
0.627939
5.12766
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/_UIKitDelegate/UIApplicationDelegate/ContinuingUserActivityAndHandlingQuickActions/UIApplicationDelegateUserActivity.swift
1
3295
// // UIApplicationDelegateUserActivity.swift // OOSwift // // Created by Karsten Litsche on 28.10.17. // // import UIKit import OOBase /** Implementation of UIApplicationDelegate section: - Continuing User Activity and Handling Quick Actions See documentation of UIApplicationDelegate for more informations. */ public final class UIApplicationDelegateUserActivity: UIResponder, UIApplicationDelegate { // MARK: - init public init( willContinueUserActivity: @escaping (UIApplication, String) -> OOBool = { _,_ in BoolConst(false) }, continueUserActivity: @escaping (UIApplication, NSUserActivity, @escaping ([Any]?) -> ()) -> OOBool = { _,_,_ in BoolConst(false) }, didUpdateUserActivity: @escaping (UIApplication, NSUserActivity) -> OOExecutable = { _,_ in DoNothing() }, didFailToContinueUserActivity: @escaping (UIApplication, String, Error) -> OOExecutable = { _,_,_ in DoNothing() }, performActionForShortcutItem: @escaping (UIApplication, UIApplicationShortcutItem, @escaping (Bool) -> ()) -> OOExecutable = { _,_,completion in DoGenericSnippet { completion(true) } } ) { self.willContinueUserActivity = willContinueUserActivity self.continueUserActivity = continueUserActivity self.didUpdateUserActivity = didUpdateUserActivity self.didFailToContinueUserActivity = didFailToContinueUserActivity self.performActionForShortcutItem = performActionForShortcutItem super.init() } // MARK: - protocol: UIApplicationDelegate public func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool { return willContinueUserActivity(application, userActivityType).value } public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Swift.Void) -> Bool { return continueUserActivity(application, userActivity, restorationHandler as! ([Any]?) -> ()).value } public func application(_ application: UIApplication, didUpdate userActivity: NSUserActivity) { didUpdateUserActivity(application, userActivity).execute() } public func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error) { didFailToContinueUserActivity(application, userActivityType, error).execute() } public func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Swift.Void) { performActionForShortcutItem(application, shortcutItem, completionHandler).execute() } // MARK: - private private let willContinueUserActivity: (UIApplication, String) -> OOBool private let continueUserActivity: (UIApplication, NSUserActivity, @escaping ([Any]?) -> ()) -> OOBool private let didUpdateUserActivity: (UIApplication, NSUserActivity) -> OOExecutable private let didFailToContinueUserActivity: (UIApplication, String, Error) -> OOExecutable private let performActionForShortcutItem: (UIApplication, UIApplicationShortcutItem, @escaping (Bool) -> ()) -> OOExecutable }
mit
4079d8a55d672c56afa25e5a0e639f9c
48.179104
192
0.731715
5.661512
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Chat/ChatViewController.swift
1
10747
// // ChatViewController.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/27. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit import QorumLogs fileprivate let chatBarHeight:CGFloat = 50.0 class ChatViewController: UIViewController { //MARK: 懒加载 var delegate:ChatViewControllerDelegate? //: 录音音量提示 var voiceView:RecordVoiceView = { () -> RecordVoiceView in let view = RecordVoiceView() view.backgroundColor = UIColor(white: 0.7, alpha: 0.5) view.layer.cornerRadius = margin*0.5 view.layer.masksToBounds = true return view }() //: 工具条 var chatBar:ChatBar = { () -> ChatBar in let bar = ChatBar() bar.viewModel = ChatBarViewModel() return bar }() //: 聊天板 lazy var chatBoard:ChatBoardView = ChatBoardView(frame: CGRect.zero, style: .plain) //MARK: 系统方法 override func viewDidLoad() { super.viewDidLoad() setupChatView() setupChatViewSubView() testMessage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() delegate?.chatViewControllerDidLoadSubViews(withChatBoard: chatBoard) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupChatViewWhenViewWillAppear() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) setupChatViewWhenViewWillDisappear() } //MARK: 私有方法 private func setupChatViewWhenViewWillAppear() { //: 键盘通知 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name:.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidAppear(notification:)), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameWillChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil) } private func setupChatViewWhenViewWillDisappear() { NotificationCenter.default.removeObserver(self) } private func setupChatView() { title = "客服" delegate = chatBoard chatBoard.boardDelegate = self chatBar.delegate = self view.addSubview(chatBoard) view.addSubview(chatBar) } private func setupChatViewSubView() { chatBoard.snp.makeConstraints { (make) in make.left.right.top.equalToSuperview() make.bottom.equalTo(chatBar.snp.top) } chatBar.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.greaterThanOrEqualTo(chatBarHeight) } } //MARK: 内部处理 @objc private func keyboardWillAppear(notification:Notification) { } @objc private func keyboardDidAppear(notification:Notification) { } @objc private func keyboardWillDisappear(notification:Notification) { } @objc private func keyboardFrameWillChange(notification:Notification) { guard let value = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] else { return } let frame = value as! CGRect QL2("\(frame.origin.y),\(frame.size.height),\(chatBoard.contentSize.height)") chatBar.snp.updateConstraints { (make) in make.bottom.equalToSuperview().offset(frame.origin.y - ScreenHeight) } view.layoutIfNeeded() chatBoard.scrollChatBoard(keyboardY: frame.origin.y, chatBarHeight: chatBar.bounds.height, true) //: 通过transform方式,由后台进入前台,transform 变成ident 导致bar出问题,不建议使用 // UIView.animate(withDuration: 0.5) { // self.view.transform = CGAffineTransform(translationX: 0, y: frame.origin.y - ScreenHeight) // } } //MARK: 开放接口 //: 添加消息 func addMessage(withMessageModel msg:MessageModel) { chatBoard.addMsgModel(MessageModel: msg) } //: 更新消息 func updateMessage(withMessageModel msg:MessageModel) { chatBoard.updateMsgModel(MessageModel: msg) } //: 删除消息 func deleteMessage(withMessageModel msg:MessageModel) { chatBoard.deleteMsgModel(MessageModel: msg, withAnimation: true) } //MARK: 测试方法 func testMessage() { var i = 0 for _ in 0...5 { i += 1 let msg = TextMessage() msg.text = "呵呵哒,来聊天,呵呵哒,来聊天,呵呵哒,来聊天,呵呵哒,来聊天,呵呵哒,来聊天,摸摸哒,傻逼最傲娇😄" msg.owner = .user msg.source = .myself addMessage(withMessageModel: msg) let msg0 = TextMessage() msg0.text = "做什么呀?摸摸哒,傻逼最傲娇😄" msg0.owner = .user msg0.source = .friends msg0.date = Date() let usr = UserModel() usr.avatarLoc = "me_avatar_boy" usr.nickname = "天不怕,地不怕" usr.uid = "6666666" msg0.fromUsr = usr addMessage(withMessageModel: msg0) } let msg1 = VoiceMessage() msg1.owner = .user msg1.source = .friends msg1.date = Date() let usr = UserModel() usr.avatarLoc = "me_avatar_boy" usr.nickname = "天不怕,地不怕" usr.uid = "6666666" msg1.fromUsr = usr msg1.status = .normal let path = Bundle.main.path(forResource: "贝加尔湖畔", ofType: "mp3") msg1.fileName = "贝加尔湖畔" msg1.path = path msg1.time = 45.0 msg1.status = .normal addMessage(withMessageModel: msg1) let msg2 = VoiceMessage() msg2.owner = .user msg2.source = .friends msg2.date = Date() let usr1 = UserModel() usr1.avatarLoc = "me_avatar_boy" usr1.nickname = "天不怕,地不怕" usr1.uid = "6666666" msg2.fromUsr = usr1 msg2.status = .normal let path1 = Bundle.main.path(forResource: "唐古 - 你懂不懂爱", ofType: "mp3") msg2.fileName = "唐古 - 你懂不懂爱" msg2.path = path1 msg2.time = 120.0 msg2.status = .normal addMessage(withMessageModel: msg2) } } //: 代理方法 extension ChatViewController:ChatBoardViewDelegate { func chatboardViewDidTap() { _ = chatBar.resignFirstResponder() } } extension ChatViewController:ChatBarDelegate { func chatBarSendText(text: String) { addMessage(withMessageModel: TextMessage.userMessage(text: text)) } //: 录音相关 func chatBarStartRecording() { if AudioPlayer.shared.isPlaying { AudioPlayer.shared.playAudioStop() } //: 插入提示录音提示 chatBoard.addSubview(voiceView) voiceView.snp.makeConstraints { (make) in make.center.equalTo(view) make.size.equalTo(CGSize(width: 150, height: 170)) } let msg = VoiceMessage.userMessage(status: .recording) //: 开始录音 var count = 0 AudioRecorder.shared.startRecording(volumeChanged: { (volume) in count += 1 if count == 2 { self.addMessage(withMessageModel: msg) } //: 设置录音音量 self.voiceView.volume = volume }, complete: { (filePath, time) in if time < 1.0 { self.voiceView.recordingStatus = .tooShort DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: { //: 删除消息 self.voiceView.removeFromSuperview() self.deleteMessage(withMessageModel: msg) }) return } self.voiceView.removeFromSuperview() QL2(filePath) if FileManager.default.fileExists(atPath: filePath) { //: .caf-> kAudioFormatAppleIMA4 .m4a -> kAudioFormatMPEG4AAC let fileName = String(format: "%.0lf.m4a", Date().timeIntervalSince1970*1000) let path = FileManager.userChatVoicePath(voiceName: fileName) do { try FileManager.default.moveItem(atPath: filePath, toPath: path) } catch{ QL4("录音文件出错") return } msg.fileName = fileName msg.path = path msg.time = time msg.status = .normal //: 录制完毕发送消息 msg.status = .normal self.updateMessage(withMessageModel: msg) } }, cancel: { self.deleteMessage(withMessageModel: msg) self.voiceView.removeFromSuperview() }) } func chatBarFinshedRecording() { AudioRecorder.shared.stopRecording() } func chatBarWillCancelRecording(cancel: Bool) { voiceView.recordingStatus = cancel ? .willCancel:.recording } func chatBarDidCancelRecording() { AudioRecorder.shared.cancelRecording() } func chatBarDidSelectUserKeyboard(keyboardY offsetY: CGFloat, chatBarHeight height: CGFloat) { chatBoard.scrollChatBoard(keyboardY: offsetY, chatBarHeight: height, true) } } //: 控制器的代理方法 protocol ChatViewControllerDelegate:NSObjectProtocol { func chatViewControllerDidLoadSubViews(withChatBoard view:ChatBoardView) }
mit
b6c5e4e13d80fa000875a116e111d23d
28.602305
160
0.576324
4.557232
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/XC8.playground/Pages/Text On Image.xcplaygroundpage/Contents.swift
1
2460
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport var screenSize = CGSize(width: 600, height: 600) let containerView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)) containerView.backgroundColor = UIColor.orange print(UIColor.orange.cgColor) func combine2LONGImage(imageUn: UIImage, imageDeux: UIImage) -> UIImage { let size = CGSize(width: imageUn.size.width + imageDeux.size.width, height: imageUn.size.height) UIGraphicsBeginImageContext(size) imageUn.draw(in: CGRect(x: 0, y: 0, width: imageUn.size.width, height: imageUn.size.height)) imageDeux.draw(in: CGRect(x: imageUn.size.width, y: 0, width: imageDeux.size.width, height: imageDeux.size.height)) let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } func resizeLONGImage(image: UIImage, newSize: CGSize) -> UIImage { UIGraphicsBeginImageContext(newSize) image.draw(in: CGRect(x:0, y:0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } func addTextToImage(image: UIImage, str: String, fctr: CGFloat) -> UIImage { let font = UIFont(name: "Arial", size: 18) var sz = image.size sz.width *= fctr sz.height *= fctr // UIGraphicsBeginImageContext(sz) UIGraphicsBeginImageContextWithOptions(sz, true, 0.0) image.draw(in: CGRect(x:0, y:0, width: sz.width, height: sz.height)) let nstr: NSString = str as NSString nstr.draw(in: CGRect(x:0, y:0, width: sz.width, height: sz.height), withAttributes: nil) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } var finalImage: UIImage? // original image size is 2048 x 768 //let img = UIImage(named: "orig2048x768.png") //let img = UIImage(named: "pic3264x2050.png") var img = UIImage(named: "swiftGreen.png") //img = UIImage(named: "pic3264x2050.png") // target image size should be 3840 x 1080 let targetImageSize = CGSize(width: screenSize.width * 2.0, height: screenSize.height) finalImage = addTextToImage(image: img!, str: "Testing 1 2 3", fctr: 1) let imgView = UIImageView(image: finalImage) imgView.frame = containerView.frame.insetBy(dx: 80.0, dy: 80.0) containerView.addSubview(imgView) PlaygroundPage.current.liveView = containerView PlaygroundPage.current.needsIndefiniteExecution = true
mit
72aee698befac8daa4d5e334ea04e056
27.275862
116
0.752439
3.519313
false
false
false
false
DannyvanSwieten/SwiftSignals
SwiftEngine/SwiftEngine/ResourceManager.swift
1
1925
// // ResourceManager.swift // SwiftEngine // // Created by Danny van Swieten on 1/25/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import ModelIO import MetalKit class ResourceManager { private var models = [(path: String, asset: Renderable)]() private var textures = [(path: String, asset: MTLTexture)]() private var textureLoader: MTKTextureLoader? private var device: MTLDevice? private var library: MTLLibrary? init(device: MTLDevice) { self.device = device library = device.newDefaultLibrary() textureLoader = MTKTextureLoader(device: device) } func getShader(name: String) -> MTLFunction? { return library?.newFunctionWithName(name) } private func loadTexture(path: String) -> Bool { let url = NSURL(fileURLWithPath: path) do{ let t = try textureLoader?.newTextureWithContentsOfURL(url, options: nil) textures.append((path, t!)) return true } catch { return false } } func getTexture(path: String) -> MTLTexture? { for texture in textures { if texture.path == path { return texture.asset } } if loadTexture(path) { return getTexture(path) } return nil } // func getModel(path: String) -> Renderable? { // // for model in models { // if model.path == path { // return model.asset // } // } // // let succes = loadModel(path) // if succes { // return getModel(path) // } else { // return nil // } // } // // private func loadModel(path: String) -> Bool { // let asset = SkinnedMesh2(pathToFile: path) // models.append((path, asset)) // return true // } }
gpl-3.0
4132d721b2621cb99652e8da79d69b0f
25.013514
85
0.546778
4.294643
false
false
false
false
vernon99/Gamp
Gamp/GACardView.swift
1
5268
// // GACardView.swift // Gamp // // Created by Mikhail Larionov on 7/19/14. // Copyright (c) 2014 Mikhail Larionov. All rights reserved. // import UIKit class GACardView: UIView { var loadingStarted = false var buildString: String? = nil { didSet{ if let build = buildString { labelBuild.text = labelBuild.text + build } } } var startDate: NSDate = NSDate() var endDate: NSDate = NSDate() { didSet{ } } @IBOutlet weak var labelLifetime: UILabel! @IBOutlet weak var labelARPDAU: UILabel! @IBOutlet weak var labelLTV: UILabel! @IBOutlet weak var lineChart: PNLineChart! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var labelBuild: UILabel! @IBOutlet weak var labelStatus: UILabel! class func instanceFromNib() -> GACardView { var result:UINib = UINib(nibName: "GACardView", bundle: NSBundle.mainBundle()) var array = result.instantiateWithOwner(nil, options: nil) return array[0] as GACardView } func prepare() { // Setup chart lineChart.setDefaultValues() lineChart.yLabelFormat = "%1.2f" lineChart.showLabel = true lineChart.yValueStartsFromZero = true lineChart.showCoordinateAxis = false lineChart.yLabelMaxCount = 10 lineChart.clipsToBounds = false } func load() { loadingStarted = true // Start animating activityIndicator.startAnimating() // Fetch data var collection = GACohortDataCollection(build:buildString, start:startDate, end:endDate) collection.startLoading({ // Stop animating dispatch_async(dispatch_get_main_queue(), { self.activityIndicator.stopAnimating() }) // Check if the params were set up if gameId == "NUMBER_HERE" { self.labelStatus.hidden = false; self.labelStatus.text = "You haven't set game id and secret, check Config.swift file" return } // Check data var retentionArray = collection.averageRetentionByDay if retentionArray.count < 2 { self.labelStatus.hidden = false self.labelStatus.text = "Insufficient data, need at least two days from build launch" return } // Add estimated data to historical if needed var estimation:Array<Float> = [] if let retentionDecay = collection.retentionDecay { estimation = retentionDecay.dataForDaysTill(maximumRetentionDays) for var n = retentionArray.count; n < estimation.count; n++ { retentionArray.append(estimation[n]) } } // Create charts var arrayDays:[String] = []; var counter:Int = 0 for point in retentionArray { if counter % 5 == 0 { arrayDays.append(String(counter)) } else { arrayDays.append("") } counter++ } // Historical chart var historicalData = PNLineChartData() historicalData.inflexionPointStyle = PNLineChartData.PNLineChartPointStyle.PNLineChartPointStyleNone historicalData.color = PNGreenColor historicalData.itemCount = retentionArray.count historicalData.getData = ({(index: Int) -> PNLineChartDataItem in var item = PNLineChartDataItem() item.y = CGFloat(retentionArray[index] as NSNumber) return item }) // Estimated chart var estimatedData = PNLineChartData() estimatedData.inflexionPointStyle = PNLineChartData.PNLineChartPointStyle.PNLineChartPointStyleNone estimatedData.color = PNGreyColor estimatedData.itemCount = estimation.count estimatedData.getData = ({(index: Int) -> PNLineChartDataItem in var item = PNLineChartDataItem() item.y = CGFloat(estimation[index] as Float) return item }) // Redraw in the main thread dispatch_async(dispatch_get_main_queue(), { // Key numbers self.labelLifetime.text = NSString(format:"%.2f d", collection.userLifetime) self.labelARPDAU.text = NSString(format:"$%.3f", collection.averageARPDAU) self.labelLTV.text = NSString(format:"$%.3f", collection.lifetimeValue) // Chart self.lineChart.xLabels = arrayDays self.lineChart.chartData = [estimatedData, historicalData] self.lineChart.strokeChart() }) }) } }
gpl-3.0
2374834dfacd38fef47a768bcf61ebf9
33.207792
112
0.54385
5.403077
false
false
false
false
RobinChao/PageMenu
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/TestTableViewController.swift
28
2485
// // TestTableViewController.swift // NFTopMenuController // // Created by Niklas Fahl on 12/17/14. // Copyright (c) 2014 Niklas Fahl. All rights reserved. // import UIKit class TestTableViewController: UITableViewController { var namesArray : [String] = ["David Fletcher", "Charles Gray", "Timothy Jones", "Marie Turner", "Kim White"] var photoNameArray : [String] = ["man8.jpg", "man2.jpg", "man3.jpg", "woman4.jpg", "woman1.jpg"] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerNib(UINib(nibName: "FriendTableViewCell", bundle: nil), forCellReuseIdentifier: "FriendTableViewCell") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) println("favorites page: viewWillAppear") } override func viewDidAppear(animated: Bool) { self.tableView.showsVerticalScrollIndicator = false super.viewDidAppear(animated) self.tableView.showsVerticalScrollIndicator = true // println("favorites page: viewDidAppear") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return namesArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : FriendTableViewCell = tableView.dequeueReusableCellWithIdentifier("FriendTableViewCell") as! FriendTableViewCell // Configure the cell... cell.nameLabel.text = namesArray[indexPath.row] cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row]) return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 94.0 } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } }
bsd-3-clause
00e0fa16fb69662f32992863c3ed602e
33.054795
133
0.682897
5.187891
false
false
false
false
norwoood/swiftBook
函数式swift/Immutable values Immutable values Immutable values immutableValue.playground/Contents.swift
1
1322
//: ## 不可变性的价值 //: ### 控制值的使用方式,这些机制的工作方式 //: ### 值类型和引用类型 //: ### 限制可变状态使用的良好理念 //: let var //: 值类型与引用类型 //关键区别, 被赋予一个新值或者作为一个参数传递给函数时,值类型会被复制。 struct Point { var x: Double var y: Double var person: Person //值类型的不可变性 func setPersonNil() { person.name = "" person.age = 0 } //x,y immutable 是不可变的,不能修改,非要修改的话需要加上关键字 mutating mutating func setPointOrigin() -> Void { x = 0 y = 0 } } class Person{ var name: String var age: Int init(_ age: Int, _ name: String) { self.name = name self.age = age } } let origin = Point(x: 3, y: 4, person: Person(4, "111")) var new = origin new.person = Person(3, "xxx") origin.person.name // 可变与不可变 // 值类型和引用类型 // 可变与不可变得合理使用会降低代码的复杂度,也会 // 引用透明函数 松耦合,不存在共享状态 // 使的函数更加模块化
mit
dcd711f5961673be1365189ed09ad604
8.300971
56
0.493737
2.99375
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 6 - Alien Adventure 3/Classes/Classes.playground/Pages/Cake Example.xcplaygroundpage/Contents.swift
1
1143
//: [Previous](@previous) /*: ## Cake Example */ //: ### Cake Struct struct Cake { } //: ### CakeHaver protocol protocol CakeHaver { var cake: Cake? { get set } } //: ### CakeHaverClass is-a CakeHaver class CakeHaverClass: CakeHaver { var cake: Cake? = Cake() } //: ### CakeHaverStruct is-a CakeHaver struct CakeHaverStruct: CakeHaver { var cake: Cake? = Cake() } func eatCake(cakeHaver: CakeHaver) { var cakeHaverCopy = cakeHaver cakeHaverCopy.cake = nil } func cakeStatus(cakeHaver: CakeHaver) { if let _ = cakeHaver.cake { print("Cake is still had") } else { print("No more cake") } } // Because this call to the eatCake func operators on a CakeHaverStruct (value type) it modifies a copy. var valueType = CakeHaverStruct() eatCake(cakeHaver: valueType) cakeStatus(cakeHaver: valueType) // Prints "Cake is still had" // But in this example eatCake is called on a CakeHaverClass (reference type) and it directly modifies the object. var referenceType = CakeHaverClass() eatCake(cakeHaver: referenceType) cakeStatus(cakeHaver: referenceType) // Prints "No more cake" //: [Next](@next)
mit
47d9f4fc8a5b2d4ac6dab8c3a2add363
22.8125
114
0.690289
3.219718
false
false
false
false
wrengels/Amplify4
Amplify4/Amplify4/Fragment.swift
1
8088
// // Fragment.swift // Amplify4 // // Created by Bill Engels on 3/5/15. // Copyright (c) 2015 Bill Engels. All rights reserved. // import Cocoa class Fragment: MapItem { let dmatch, gmatch : Match let isCircular : Bool let ampSize, totSize : Int let quality : CGFloat let barRect, barRectG: NSRect let bez, leftArrow, rightArrow : NSBezierPath let maxWidth : CGFloat = 10 let arrowLength : CGFloat = 5 // for circular fragments let arrowRise : CGFloat = 3 // for circular fragments let widthCutoffs : [CGFloat] = [100, 200, 300, 500, 700, 1000, 1500, 2000, 3000, 4000, 7000, 10000] init(dmatch : Match, gmatch : Match) { self.dmatch = dmatch self.gmatch = gmatch self.isCircular = dmatch.threePrime > gmatch.threePrime var targetLength : CGFloat = 0 // Placeholder. No need to compute this if it's not circular if isCircular { let apdel = NSApplication.sharedApplication().delegate! as! AppDelegate targetLength = CGFloat(apdel.substrateDelegate.targetView.textStorage!.length - apdel.targDelegate.firstbase) self.ampSize = Int(targetLength) + gmatch.threePrime - dmatch.threePrime - 1 } else { self.ampSize = gmatch.threePrime - dmatch.threePrime - 1 } self.totSize = count(dmatch.primer.seq) + ampSize + count(gmatch.primer.seq) let tempQuality = dmatch.quality() * gmatch.quality() if tempQuality > 0 { self.quality = CGFloat(ampSize)/(tempQuality * tempQuality) } else { quality = 5000000000 } let widthIncrement = maxWidth / (CGFloat(widthCutoffs.count) + 1) var barWidth = maxWidth for w in widthCutoffs { if quality > w {barWidth -= widthIncrement} } leftArrow = NSBezierPath() rightArrow = NSBezierPath() if isCircular { self.barRect = NSRect(origin: NSPoint(x: dmatch.threePrime, y: 0), size: NSSize(width: targetLength - CGFloat(dmatch.threePrime), height: barWidth)) self.barRectG = NSRect(x: 0, y: 0, width: CGFloat(gmatch.threePrime), height: barWidth); bez = NSBezierPath(rect: barRectG) bez.appendBezierPath(NSBezierPath(rect: barRect)) let arrowHalf : CGFloat = barWidth/2 + arrowRise rightArrow.moveToPoint(NSPoint(x: 0, y: 0)) rightArrow.relativeLineToPoint(NSPoint(x: 0, y: arrowHalf)) rightArrow.relativeLineToPoint(NSPoint(x: arrowLength, y: -arrowHalf)) rightArrow.relativeLineToPoint(NSPoint(x: -arrowLength, y: -arrowHalf)) rightArrow.closePath() leftArrow.moveToPoint(NSPoint(x: 0, y: 0)) leftArrow.relativeLineToPoint(NSPoint(x: 0, y: arrowHalf)) leftArrow.relativeLineToPoint(NSPoint(x: -arrowLength, y: -arrowHalf)) leftArrow.relativeLineToPoint(NSPoint(x: arrowLength, y: -arrowHalf)) leftArrow.closePath() } else { self.barRect = NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: CGFloat(gmatch.threePrime - dmatch.threePrime), height: barWidth)) self.barRectG = NSRect(x: 0, y: 0, width: 1, height: 1); self.bez = NSBezierPath() } } func setLitRec (rect : NSRect) { self.litBez = NSBezierPath(rect: NSInsetRect(rect, -5, 0)) var move = NSAffineTransform() move.translateXBy(highlightPoint.x, yBy: highlightPoint.y) self.litBez.transformUsingAffineTransform(move) litBez.lineWidth = highlightLineWidth self.coItems = [dmatch, gmatch] dmatch.coItems.append(self) gmatch.coItems.append(self) } override func doLitBez (b : NSBezierPath) { self.litBez = b var move = NSAffineTransform() move.translateXBy(highlightPoint.x, yBy: highlightPoint.y) move.scaleXBy(1, yBy: highlightScale) self.litBez.transformUsingAffineTransform(move) litBez.lineWidth = highlightLineWidth self.coItems = [dmatch, gmatch] dmatch.coItems.append(self) gmatch.coItems.append(self) } override func info() -> NSAttributedString { var info = NSMutableAttributedString(string: "Fragment of total length: \(totSize) bp ", attributes: fmat.normal as [NSObject : AnyObject]) extendString(starter: info, suffix1: "⫸(primer: ", attr1: fmat.normal, suffix2: dmatch.primer.name, attr2: fmat.bigboldblue) extendString(starter: info, suffix1: ") — \(ampSize) bp — (primer: ", attr1: fmat.normal, suffix2: gmatch.primer.name, attr2: fmat.bigboldred) extendString(starter: info, suffix: ")⫷", attr: fmat.normal) var description : String = "(very weak)" if quality < 4000 {description = "(weak)"} if quality < 1500 {description = "(moderate)"} if quality < 700 {description = "(okay)"} if quality < 300 {description = "(good)"} extendString(starter: info, suffix: String(format: " Q = %.1f %@", Double(quality), description), attr: fmat.normal); return info } override func report() -> NSAttributedString { var report = NSMutableAttributedString(string: "\r", attributes: fmat.hline1 as [NSObject : AnyObject]) let apdel = NSApplication.sharedApplication().delegate! as! AppDelegate let targFileString = apdel.substrateDelegate.targetView.textStorage!.string as NSString let firstbase = apdel.targDelegate.firstbase as Int let targString = targFileString.substringFromIndex(firstbase).uppercaseString as NSString extendString(starter: report, suffix: "Amplified fragment of length \(totSize) bp\r", attr: fmat.h3) extendString(starter: report, suffix1: "\r⫸(primer: ", attr1: fmat.normal, suffix2: dmatch.primer.name, attr2: fmat.blue) extendString(starter: report, suffix1: ") — \(ampSize) bp — (primer: ", attr1: fmat.normal, suffix2: gmatch.primer.name, attr2: fmat.red) extendString(starter: report, suffix: ")⫷", attr: fmat.normal) var description : String = "(very weak amplification — probably not visible on an agarose gel)" if quality < 4000 {description = "(weak amplification — might be visible on an agarose gel)"} if quality < 1500 {description = "(moderate amplification)"} if quality < 700 {description = "(okay amplification)"} if quality < 300 {description = "(good amplification)"} if isCircular {description += " (Circular)"} extendString(starter: report, suffix: String(format: " Q = %.1f %@\r\r", Double(quality), description), attr: fmat.normal) var gseq = "" for c in gmatch.primer.seq { gseq = apdel.substrateDelegate.iubComp(String(c)) + gseq } var ampSeq = NSMutableAttributedString(string: dmatch.primer.seq.lowercaseString, attributes: fmat.blueseq as [NSObject : AnyObject]) var ampBases = "" if isCircular { ampBases = targString.substringWithRange(NSMakeRange(dmatch.threePrime + 1, targString.length - dmatch.threePrime - 1)) ampBases += targString.substringWithRange(NSMakeRange(0, gmatch.threePrime)) } else { ampBases = targString.substringWithRange(NSMakeRange(dmatch.threePrime + 1, ampSize)).uppercaseString } extendString(starter: ampSeq, suffix1: ampBases, attr1: fmat.seq, suffix2: gseq.lowercaseString, attr2: fmat.redseq) extendString(starter: report, suffix: "Amplified sequence: \r", attr: fmat.normal) report.appendAttributedString(ampSeq) extendString(starter: report, suffix: "\r\r", attr: fmat.normal) if isCircular { apdel.targDelegate.targetView.setSelectedRange(NSMakeRange(apdel.targDelegate.firstbase, 0)) } else { apdel.targDelegate.selectBasesFrom(dmatch.threePrime + 2, lastSelected: dmatch.threePrime + ampSize + 1) } return report } }
gpl-2.0
0b0adfb0363f76a4a7a67c8b08276c87
50.717949
160
0.64824
3.941378
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Card/BillingAddress/BillingAddressScreenPresenter.swift
1
11856
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import DIKit import FeatureCardPaymentDomain import Localization import PlatformKit import RxCocoa import RxRelay import RxSwift import ToolKit final class BillingAddressScreenPresenter: RibBridgePresenter { // MARK: - Types enum CellType: Equatable { case selectionView case textField(TextFieldType) case doubleTextField(TextFieldType, TextFieldType) } struct PresentationData { let cellTypes: [CellType] var cellCount: Int { cellTypes.count } init(country: FeatureCardPaymentDomain.Country) { var cellTypes: [CellType] = [ .selectionView, .textField(.personFullName), .textField(.addressLine(1)), .textField(.addressLine(2)), .textField(.city) ] switch country { case .US: cellTypes += [ .doubleTextField(.state, .postcode) ] default: cellTypes += [ .textField(.postcode) ] } self.cellTypes = cellTypes } func row(for cellType: CellType) -> Int { cellTypes.enumerated().first { $0.element == cellType }!.offset } func cellType(for row: Int) -> CellType { cellTypes[row] } } private typealias AnalyticsEvent = AnalyticsEvents.SimpleBuy private typealias LocalizedString = LocalizationConstants.BillingAddressScreen // MARK: - Properties let title = LocalizedString.title let buttonViewModel: ButtonViewModel let presentationDataRelay = BehaviorRelay(value: PresentationData(country: .US)) let selectionButtonViewModel: SelectionButtonViewModel var refresh: Signal<Void> { refreshRelay.asSignal() } var isValid: Driver<Bool> { isValidRelay.asDriver() } var textFieldViewModelsMap: [TextFieldType: TextFieldViewModel] { textFieldViewModelsMapRelay.value } var errorTrigger: Signal<Error> { errorTriggerRelay.asSignal() } let textFieldViewModelsMapRelay = BehaviorRelay<[TextFieldType: TextFieldViewModel]>(value: [:]) private let errorTriggerRelay = PublishRelay<Error>() private let isValidRelay = BehaviorRelay(value: false) private let refreshRelay = PublishRelay<Void>() private let disposeBag = DisposeBag() // MARK: - Injected private let interactor: BillingAddressScreenInteractor private let countrySelectionRouter: SelectionRouterAPI private let loadingViewPresenter: LoadingViewPresenting private let eventRecorder: AnalyticsEventRecorderAPI private let messageRecorder: MessageRecording private let userDataRepository: DataRepositoryAPI init( interactor: BillingAddressScreenInteractor, countrySelectionRouter: SelectionRouterAPI, loadingViewPresenter: LoadingViewPresenting = resolve(), eventRecorder: AnalyticsEventRecorderAPI, messageRecorder: MessageRecording, userDataRepository: DataRepositoryAPI = resolve() ) { self.interactor = interactor self.countrySelectionRouter = countrySelectionRouter self.loadingViewPresenter = loadingViewPresenter self.eventRecorder = eventRecorder self.messageRecorder = messageRecorder self.userDataRepository = userDataRepository selectionButtonViewModel = SelectionButtonViewModel() selectionButtonViewModel.shouldShowSeparatorRelay.accept(true) buttonViewModel = .primary(with: LocalizedString.button) super.init(interactable: interactor) } override func viewDidLoad() { super.viewDidLoad() // 1. Country is selected // 2. `PresentationData` is regenerated // 3. Data is mapped into text field view models // 4. A layout refresh is triggered interactor.selectedCountry .map { .text($0.flag) } .bindAndCatch(to: selectionButtonViewModel.leadingContentTypeRelay) .disposed(by: disposeBag) interactor.selectedCountry .map(\.name) .bindAndCatch(to: selectionButtonViewModel.titleRelay) .disposed(by: disposeBag) interactor.selectedCountry .map(\.code) .bindAndCatch(to: selectionButtonViewModel.subtitleRelay) .disposed(by: disposeBag) interactor.selectedCountry .map { .init(id: $0.code, label: $0.name) } .bindAndCatch(to: selectionButtonViewModel.accessibilityContentRelay) .disposed(by: disposeBag) interactor.selectedCountry .map { PresentationData(country: $0) } .bindAndCatch(to: presentationDataRelay) .disposed(by: disposeBag) presentationDataRelay .map(weak: self) { (self, data) in self.transformPresentationDataIntoViewModels(data) } .bindAndCatch(to: textFieldViewModelsMapRelay) .disposed(by: disposeBag) textFieldViewModelsMapRelay .mapToVoid() .bindAndCatch(to: refreshRelay) .disposed(by: disposeBag) selectionButtonViewModel.trailingContentRelay.accept( .image( ImageViewContent( imageResource: .local(name: "icon-disclosure-down-small", bundle: .platformUIKit) ) ) ) selectionButtonViewModel.tap .emit(onNext: { [unowned self] in self.showCountrySelectionScreen() }) .disposed(by: disposeBag) let viewModelsObservable = textFieldViewModelsMapRelay .map { textFieldMap -> [TextFieldViewModel?] in [ textFieldMap[.personFullName], textFieldMap[.addressLine(1)], textFieldMap[.addressLine(2)], textFieldMap[.city], textFieldMap[.postcode], textFieldMap[.state] ] } .map { viewModels in viewModels.compactMap { $0 } } Observable.combineLatest(textFieldViewModelsMapRelay, userDataRepository.user.asObservable()) .subscribe(onNext: { textfields, user in textfields[.personFullName]?.textRelay.accept(user.personalDetails.fullName) textfields[.addressLine(1)]?.textRelay.accept(user.address?.lineOne ?? "") textfields[.addressLine(2)]?.textRelay.accept(user.address?.lineTwo ?? "") textfields[.city]?.textRelay.accept(user.address?.city ?? "") textfields[.postcode]?.textRelay.accept(user.address?.postalCode ?? "") textfields[.state]?.textRelay.accept(user.address?.state ?? "") }) .disposed(by: disposeBag) let stateArrayObservable = viewModelsObservable .map { viewModels in viewModels.map(\.state) } .flatMap { Observable.combineLatest($0) } let statesTuple = stateArrayObservable .map { states in ( name: states[0], addressLine1: states[1], addressLine2: states[2], city: states[3], postcode: states[4], state: states[safe: 5] ) } let billingAddress = Observable .combineLatest( statesTuple, interactor.selectedCountry ) .map { payload -> BillingAddress? in let states = payload.0 let country = payload.1 return BillingAddress( country: country, fullName: states.name.value, addressLine1: states.addressLine1.value, addressLine2: states.addressLine2.value, city: states.city.value, state: states.state?.value ?? "", postCode: states.postcode.value ) } .share(replay: 1) billingAddress .compactMap { $0 } .bindAndCatch(to: interactor.billingAddressRelay) .disposed(by: disposeBag) billingAddress .map { $0 != nil } .bindAndCatch(to: isValidRelay) .disposed(by: disposeBag) isValid .drive(buttonViewModel.isEnabledRelay) .disposed(by: disposeBag) buttonViewModel.tapRelay .withLatestFrom(interactor.billingAddress) .bindAndCatch(weak: self) { (self, billingAddress) in self.eventRecorder.record(event: AnalyticsEvent.sbBillingAddressSet) self.add(billingAddress: billingAddress) } .disposed(by: disposeBag) } private func add(billingAddress: BillingAddress) { interactor .add(billingAddress: billingAddress) .handleLoaderForLifecycle( loader: loadingViewPresenter, style: .circle, text: LocalizedString.linkingYourCard ) .subscribe( onError: { [weak errorTriggerRelay] error in errorTriggerRelay?.accept(error) } ) .disposed(by: disposeBag) } private func transformPresentationDataIntoViewModels(_ data: PresentationData) -> [TextFieldType: TextFieldViewModel] { func viewModel(by type: TextFieldType, returnKeyType: UIReturnKeyType) -> TextFieldViewModel { TextFieldViewModel( with: type, returnKeyType: returnKeyType, validator: TextValidationFactory.General.notEmpty, messageRecorder: messageRecorder ) } var viewModelByType: [TextFieldType: TextFieldViewModel] = [:] var previousTextFieldViewModel: TextFieldViewModel? for (index, cell) in data.cellTypes.enumerated() { switch cell { case .doubleTextField(let leadingType, let trailingType): let leading = viewModel(by: leadingType, returnKeyType: .next) let trailing = viewModel(by: trailingType, returnKeyType: .done) viewModelByType[leadingType] = leading viewModelByType[trailingType] = trailing previousTextFieldViewModel?.set(next: leading) leading.set(next: trailing) previousTextFieldViewModel = trailing case .textField(let type): let textFieldViewModel = viewModel( by: type, returnKeyType: index == data.cellTypes.count - 1 ? .done : .next ) viewModelByType[type] = textFieldViewModel previousTextFieldViewModel?.set(next: textFieldViewModel) previousTextFieldViewModel = textFieldViewModel case .selectionView: break } } return viewModelByType } private func showCountrySelectionScreen() { countrySelectionRouter.showSelectionScreen( screenTitle: LocalizationConstants.CountrySelectionScreen.title, searchBarPlaceholder: LocalizationConstants.CountrySelectionScreen.searchBarPlaceholder, using: interactor.countrySelectionService ) } // MARK: - Navigation func previous() { interactor.previous() } }
lgpl-3.0
17209fc9d90ed808224a2fb7cff07589
33.263006
123
0.594264
5.605201
false
false
false
false
jovito-royeca/ManaKit
Sources/Classes/SetsViewModel.swift
1
2118
// // SetsViewModel.swift // ManaKit_Example // // Created by Jovito Royeca on 31.08.18. // Copyright © 2018 CocoaPods. All rights reserved. // import CoreData import PromiseKit public class SetsViewModel: BaseViewModel { // MARK: - Variables var _predicate: NSPredicate? override public var predicate: NSPredicate? { get { if _predicate == nil { guard let queryString = queryString else { return nil } let count = queryString.count if count > 0 { if count == 1 { _predicate = NSPredicate(format: "name BEGINSWITH[cd] %@ OR code BEGINSWITH[cd] %@", queryString, queryString) } else { _predicate = NSPredicate(format: "name CONTAINS[cd] %@ OR code CONTAINS[cd] %@", queryString, queryString) } } } return _predicate } set { _predicate = newValue } } var _fetchRequest: NSFetchRequest<NSFetchRequestResult>? override public var fetchRequest: NSFetchRequest<NSFetchRequestResult>? { get { if _fetchRequest == nil { _fetchRequest = MGSet.fetchRequest() } return _fetchRequest } set { _fetchRequest = newValue } } // MARK: - Initialization override public init() { super.init() entityName = String(describing: MGSet.self) sortDescriptors = [NSSortDescriptor(key: "releaseDate", ascending: false)] sectionName = "myYearSection" } // MARK: - Overrides override public func fetchRemoteData() -> Promise<(data: Data, response: URLResponse)> { let path = "/sets?json=true" return ManaKit.sharedInstance.createNodePromise(apiPath: path, httpMethod: "GET", httpBody: nil) } }
mit
bfc0a913389d7026ee09302da2bbb459
29.681159
134
0.511101
5.456186
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/AssetPriceView/Interactor/AssetPriceViewHistoricalInteractor.swift
1
2222
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit import RxRelay import RxSwift /// Implementation of `AssetPriceViewInteracting` that streams a State based on the given /// HistoricalFiatPriceService state. public final class AssetPriceViewHistoricalInteractor: AssetPriceViewInteracting { public typealias InteractionState = DashboardAsset.State.AssetPrice.Interaction // MARK: - Exposed Properties public var state: Observable<InteractionState> { _ = setup return stateRelay .asObservable() .observe(on: MainScheduler.instance) } public func refresh() {} // MARK: - Private Accessors private lazy var setup: Void = historicalPriceProvider.calculationState .map { state -> InteractionState in switch state { case .calculating, .invalid: return .loading case .value(let result): let delta = result.historicalPrices.delta let currency = result.historicalPrices.currency let window = result.priceWindow let currentPrice = result.currentFiatValue let priceChange = FiatValue( amount: result.historicalPrices.fiatChange, currency: result.currentFiatValue.currency ) return .loaded( next: .init( currentPrice: currentPrice.moneyValue, time: window.time(for: currency), changePercentage: delta.doubleValue, priceChange: priceChange.moneyValue ) ) } } .catchAndReturn(.loading) .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) private let stateRelay = BehaviorRelay<InteractionState>(value: .loading) private let disposeBag = DisposeBag() private let historicalPriceProvider: HistoricalFiatPriceServiceAPI // MARK: - Setup public init(historicalPriceProvider: HistoricalFiatPriceServiceAPI) { self.historicalPriceProvider = historicalPriceProvider } }
lgpl-3.0
ce8ca642796b2a8301c6293eb05f5830
33.169231
89
0.624944
5.594458
false
false
false
false
Ehrippura/firefox-ios
SyncTelemetry/SyncTelemetry.swift
2
4059
/* 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 Alamofire import Foundation import GCDWebServers import XCGLogger import SwiftyJSON import Shared private let log = Logger.browserLogger private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL! private let AppName = "Fennec" public enum TelemetryDocType: String { case core = "core" case sync = "sync" } public protocol SyncTelemetryEvent { func record(_ prefs: Prefs) } open class SyncTelemetry { private static var prefs: Prefs? private static var telemetryVersion: Int = 4 open class func initWithPrefs(_ prefs: Prefs) { assert(self.prefs == nil, "Prefs already initialized") self.prefs = prefs } open class func recordEvent(_ event: SyncTelemetryEvent) { guard let prefs = prefs else { assertionFailure("Prefs not initialized") return } event.record(prefs) } open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) { let docID = UUID().uuidString let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String let channel = AppConstants.BuildChannel.rawValue let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)" let url = ServerURL.appendingPathComponent(path) var request = URLRequest(url: url) log.debug("Ping URL: \(url)") log.debug("Ping payload: \(ping.payload.stringValue() ?? "")") // Don't add the common ping format for the mobile core ping. let pingString: String? if docType != .core { var json = JSON(commonPingFormat(forType: docType)) json["payload"] = ping.payload pingString = json.stringValue() } else { pingString = ping.payload.stringValue() } guard let body = pingString?.data(using: String.Encoding.utf8) else { log.error("Invalid data!") assertionFailure() return } guard channel != "default" else { log.debug("Non-release build; not sending ping") return } request.httpMethod = "POST" request.httpBody = body request.addValue(GCDWebServerFormatRFC822(Date()), forHTTPHeaderField: "Date") request.setValue("application/json", forHTTPHeaderField: "Content-Type") SessionManager.default.request(request).response { response in log.debug("Ping response: \(response.response?.statusCode ?? -1).") } } private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let date = formatter.string(from: NSDate() as Date) let displayVersion = [ AppInfo.appVersion, "b", AppInfo.buildNumber ].joined() let version = ProcessInfo.processInfo.operatingSystemVersion let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" return [ "type": type.rawValue, "id": UUID().uuidString, "creationDate": date, "version": SyncTelemetry.telemetryVersion, "application": [ "architecture": "arm", "buildId": AppInfo.buildNumber, "name": AppInfo.displayName, "version": AppInfo.appVersion, "displayVersion": displayVersion, "platformVersion": osVersion, "channel": AppConstants.BuildChannel.rawValue ] ] } } public protocol SyncTelemetryPing { var payload: JSON { get } }
mpl-2.0
33e8d0348a530e6e1719f6aa77c706f9
33.109244
114
0.622567
4.80355
false
false
false
false
cogentParadigm/XMPPClient
Example/Tests/Tests.swift
1
1159
// https://github.com/Quick/Quick import Quick import Nimble class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
010d47e704ef93c912d7bb67cc50d583
22.530612
63
0.355594
5.490476
false
false
false
false
tjw/swift
benchmark/utils/TestsUtils.swift
1
6932
//===--- TestsUtils.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(Linux) import Glibc #else import Darwin #endif public enum BenchmarkCategory : String { // Validation "micro" benchmarks test a specific operation or critical path that // we know is important to measure. case validation // subsystems to validate and their subcategories. case api, Array, String, Dictionary, Codable, Set, Data case sdk case runtime, refcount, metadata // Other general areas of compiled code validation. case abstraction, safetychecks, exceptions, bridging, concurrency // Algorithms are "micro" that test some well-known algorithm in isolation: // sorting, searching, hashing, fibonaci, crypto, etc. case algorithm // Miniapplications are contrived to mimic some subset of application behavior // in a way that can be easily measured. They are larger than micro-benchmarks, // combining multiple APIs, data structures, or algorithms. This includes small // standardized benchmarks, pieces of real applications that have been extracted // into a benchmark, important functionality like JSON parsing, etc. case miniapplication // Regression benchmarks is a catch-all for less important "micro" // benchmarks. This could be a random piece of code that was attached to a bug // report. We want to make sure the optimizer as a whole continues to handle // this case, but don't know how applicable it is to general Swift performance // relative to the other micro-benchmarks. In particular, these aren't weighted // as highly as "validation" benchmarks and likely won't be the subject of // future investigation unless they significantly regress. case regression // Most benchmarks are assumed to be "stable" and will be regularly tracked at // each commit. A handful may be marked unstable if continually tracking them is // counterproductive. case unstable // CPU benchmarks represent instrinsic Swift performance. They are useful for // measuring a fully baked Swift implementation across different platforms and // hardware. The benchmark should also be reasonably applicable to real Swift // code--it should exercise a known performance critical area. Typically these // will be drawn from the validation benchmarks once the language and standard // library implementation of the benchmark meets a reasonable efficiency // baseline. A benchmark should only be tagged "cpubench" after a full // performance investigation of the benchmark has been completed to determine // that it is a good representation of future Swift performance. Benchmarks // should not be tagged if they make use of an API that we plan on // reimplementing or call into code paths that have known opportunities for // significant optimization. case cpubench // Explicit skip marker case skip } public struct BenchmarkInfo { /// The name of the benchmark that should be displayed by the harness. public var name: String /// A function that invokes the specific benchmark routine. public var runFunction: (Int) -> () /// A set of category tags that describe this benchmark. This is used by the /// harness to allow for easy slicing of the set of benchmarks along tag /// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc. public var tags: [BenchmarkCategory] /// An optional function that if non-null is run before benchmark samples /// are timed. public var setUpFunction: (() -> ())? /// An optional function that if non-null is run immediately after a sample is /// taken. public var tearDownFunction: (() -> ())? public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory], setUpFunction: (() -> ())? = nil, tearDownFunction: (() -> ())? = nil) { self.name = name self.runFunction = runFunction self.tags = tags self.setUpFunction = setUpFunction self.tearDownFunction = tearDownFunction } } extension BenchmarkInfo : Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { return lhs.name == rhs.name } } extension BenchmarkInfo : Hashable { public var hashValue: Int { return name.hashValue } } // Linear function shift register. // // This is just to drive benchmarks. I don't make any claim about its // strength. According to Wikipedia, it has the maximal period for a // 32-bit register. struct LFSR { // Set the register to some seed that I pulled out of a hat. var lfsr : UInt32 = 0xb78978e7 mutating func shift() { lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001) } mutating func randInt() -> Int64 { var result : UInt32 = 0 for _ in 0..<32 { result = (result << 1) | (lfsr & 1) shift() } return Int64(bitPattern: UInt64(result)) } } var lfsrRandomGenerator = LFSR() // Start the generator from the beginning public func SRand() { lfsrRandomGenerator = LFSR() } public func Random() -> Int64 { return lfsrRandomGenerator.randInt() } @inline(__always) public func CheckResults( _ resultsMatch: Bool, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) { guard _fastPath(resultsMatch) else { print("Incorrect result in \(function), \(file):\(line)") abort() } } public func False() -> Bool { return false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct : SomeProtocol { init() {} func getValue() -> Int { return 1 } } public func someProtocolFactory() -> SomeProtocol { return MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func blackHole<T>(_ x: T) { } // Return the passed argument without letting the optimizer know that. @inline(never) public func identity<T>(_ x: T) -> T { return x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) public func getInt(_ x: Int) -> Int { return x } // The same for String. @inline(never) public func getString(_ s: String) -> String { return s }
apache-2.0
4ed987575e730cb88a3b16d49e827ffe
34.367347
90
0.698067
4.460746
false
false
false
false
royhsu/RHGoogleMapsDirections
RHGoogleMapsDirections/RHDirectionManager.swift
1
2529
// // RHDirectionManager.swift // RHGoogleMapsDirections // // Created by 許郁棋 on 2015/4/26. // Copyright (c) 2015年 tinyworld. All rights reserved. // import Foundation class RHDirectionManager { enum Mode: Int, Printable { case Driving case Walking case Bicycling case Transit var description: String { switch self { case .Driving: return "driving" case .Walking: return "walking" case .Bicycling: return "bicycling" case .Transit: return "transit" } } } struct Static { static let GetPathDidSuccessNotification = "GetPathDidSuccessNotification" static let GetPathDidFailNotification = "GetPathDidFailNotification" } class var sharedManager: RHDirectionManager { struct Static { static let instance = RHDirectionManager() } return Static.instance } var mode: Mode = .Driving var path: String? func getPathFromLocation(location: RHLocation, toLocation: RHLocation) { let parameters = [ "origin": "\(location.latitude), \(location.longitude)", "destination": "\(toLocation.latitude), \(toLocation.longitude)", "sensor": "true", "mode": mode.description ] request(RHDirectionRouter.Directions(parameters: parameters)).responseJSON(options: .allZeros) { _, _, data, error in if error == nil { if let json = data as? NSDictionary { if let routes = json["routes"] as? Array<AnyObject> { if let firstRoute = routes.first as? NSDictionary { if let overviewPolyline = firstRoute["overview_polyline"] as? NSDictionary { if let points = overviewPolyline["points"] as? String { self.path = points NSNotificationCenter.defaultCenter().postNotificationName(Static.GetPathDidSuccessNotification, object: nil) return } } } } } } else { println("Error: \(error!)") } NSNotificationCenter.defaultCenter().postNotificationName(Static.GetPathDidFailNotification, object: nil) } } }
mit
c89e3345f4eb2dfe08bc08ecfc589508
33.547945
144
0.535105
5.409871
false
false
false
false
vector-im/vector-ios
Riot/Managers/OnBoarding/OnBoardingManager.swift
1
3303
/* Copyright 2018 New Vector Ltd 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 /// `OnBoardingManager` is used to manage onboarding steps, like create DM room with riot bot. final public class OnBoardingManager: NSObject { // MARK: - Constants private enum Constants { static let riotBotMatrixId = "@riot-bot:matrix.org" static let createRiotBotDMRequestMaxNumberOfTries: UInt = UInt.max } // MARK: - Properties private let session: MXSession // MARK: - Setup & Teardown @objc public init(session: MXSession) { self.session = session super.init() } // MARK: - Public @objc public func createRiotBotDirectMessageIfNeeded(success: (() -> Void)?, failure: ((Error) -> Void)?) { // Check user has joined no rooms so is a new comer guard self.isUserJoinedARoom() == false else { // As the user has already rooms, one of their riot client has already created a room with riot bot success?() return } // Check first that the user homeserver is federated with the Riot-bot homeserver self.session.matrixRestClient.avatarUrl(forUser: Constants.riotBotMatrixId) { (response) in switch response { case .success: // Create DM room with Riot-bot let roomCreationParameters = MXRoomCreationParameters(forDirectRoomWithUser: Constants.riotBotMatrixId) let httpOperation = self.session.createRoom(parameters: roomCreationParameters) { (response) in switch response { case .success: success?() case .failure(let error): MXLog.debug("[OnBoardingManager] Create chat with riot-bot failed") failure?(error) } } // Make multipe tries, until we get a response httpOperation.maxNumberOfTries = Constants.createRiotBotDMRequestMaxNumberOfTries case .failure(let error): MXLog.debug("[OnBoardingManager] riot-bot is unknown or the user hs is non federated. Do not try to create a room with riot-bot") failure?(error) } } } // MARK: - Private private func isUserJoinedARoom() -> Bool { var isUserJoinedARoom = false for room in session.rooms { guard let roomSummary = room.summary else { continue } if case .join = roomSummary.membership { isUserJoinedARoom = true break } } return isUserJoinedARoom } }
apache-2.0
c7f3e710e1a8378328fd7604ac0cb75b
32.704082
145
0.604905
5.058193
false
false
false
false
lintmachine/RxEasing
Pod/Classes/easing.swift
1
7253
// // easing.swift // // Created by CraigGrummitt on 6/08/2014. // Copyright (c) 2014 CraigGrummitt. All rights reserved. // // Based on easing.c // // Copyright (c) 2011, Auerhaus Development, LLC // // This program is free software. It comes without any warranty, to // the extent permitted by applicable law. You can redistribute it // and/or modify it under the terms of the Do What The Fuck You Want // To Public License, Version 2, as published by Sam Hocevar. See // http://sam.zoy.org/wtfpl/COPYING for more details. // import UIKit let M_PI_2_f = Double.pi / 2.0 let M_PI_f = Double.pi typealias AHEasingFunction = (Double)->Double func dub(num:Double)->Double { return (Double(Int32(num))) } func sinDouble(num:Double)->Double { return sin(num) } func NoInterpolation(p:Double)->Double { return 1.0; } // Modeled after the line y = x func LinearInterpolation(p:Double)->Double { return p; } // Modeled after the parabola y = x^2 func QuadraticEaseIn(p:Double)->Double { return p * p; } // Modeled after the parabola y = -x^2 + 2x func QuadraticEaseOut(p:Double)->Double { return -(p * (p - 2)); } // Modeled after the piecewise quadratic // y = (1/2)((2x)^2) ; [0, 0.5) // y = -(1/2)((2x-1)*(2x-3) - 1) ; [0.5, 1] func QuadraticEaseInOut(p:Double)->Double { if(p < 0.5) { return 2 * p * p; } else { return (-2 * p * p) + (4 * p) - 1; } } // Modeled after the cubic y = x^3 func CubicEaseIn(p:Double)->Double { return p * p * p; } // Modeled after the cubic y = (x - 1)^3 + 1 func CubicEaseOut(p:Double)->Double { let f:Double = (p - 1); return f * f * f + 1; } // Modeled after the piecewise cubic // y = (1/2)((2x)^3) ; [0, 0.5) // y = (1/2)((2x-2)^3 + 2) ; [0.5, 1] func CubicEaseInOut(p:Double)->Double { if(p < 0.5) { return 4 * p * p * p; } else { let f:Double = ((2 * p) - 2); return 0.5 * f * f * f + 1; } } // Modeled after the quartic x^4 func QuarticEaseIn(p:Double)->Double { return p * p * p * p; } // Modeled after the quartic y = 1 - (x - 1)^4 func QuarticEaseOut(p:Double)->Double { let f:Double = (p - 1); return f * f * f * (1 - p) + 1; } // Modeled after the piecewise quartic // y = (1/2)((2x)^4) ; [0, 0.5) // y = -(1/2)((2x-2)^4 - 2) ; [0.5, 1] func QuarticEaseInOut(p:Double)->Double { if(p < 0.5) { return 8 * p * p * p * p; } else { let f:Double = (p - 1); return -8 * f * f * f * f + 1; } } // Modeled after the quintic y = x^5 func QuinticEaseIn(p:Double)->Double { return p * p * p * p * p; } // Modeled after the quintic y = (x - 1)^5 + 1 func QuinticEaseOut(p:Double)->Double { let f:Double = (p - 1); return f * f * f * f * f + 1; } // Modeled after the piecewise quintic // y = (1/2)((2x)^5) ; [0, 0.5) // y = (1/2)((2x-2)^5 + 2) ; [0.5, 1] func QuinticEaseInOut(p:Double)->Double { if(p < 0.5) { return 16 * p * p * p * p * p; } else { let f:Double = ((2 * p) - 2); return 0.5 * f * f * f * f * f + 1; } } // Modeled after quarter-cycle of sine wave func SineEaseIn(p:Double)->Double { return sinDouble(num: (p - 1.0) * M_PI_2_f)+1.0 } // Modeled after quarter-cycle of sine wave (different phase) func SineEaseOut(p:Double)->Double { return sinDouble(num: p * M_PI_2_f) } // Modeled after half sine wave func SineEaseInOut(p:Double)->Double { return 0.5 * (1.0 - cos(p * M_PI_f)); } // Modeled after shifted quadrant IV of unit circle func CircularEaseIn(p:Double)->Double { return 1 - sqrt(1 - (p * p)); } // Modeled after shifted quadrant II of unit circle func CircularEaseOut(p:Double)->Double { return sqrt((2 - p) * p); } // Modeled after the piecewise circular function // y = (1/2)(1 - sqrt(1 - 4x^2)) ; [0, 0.5) // y = (1/2)(sqrt(-(2x - 3)*(2x - 1)) + 1) ; [0.5, 1] func CircularEaseInOut(p:Double)->Double { if(p < 0.5) { return 0.5 * (1 - sqrt(1 - 4 * (p * p))); } else { return 0.5 * (sqrt(-((2 * p) - 3) * ((2 * p) - 1)) + 1); } } // Modeled after the exponential function y = 2^(10(x - 1)) func ExponentialEaseIn(p:Double)->Double { return (p == 0.0) ? p : pow(2, 10 * (p - 1)); } // Modeled after the exponential function y = -2^(-10x) + 1 func ExponentialEaseOut(p:Double)->Double { return (p == 1.0) ? p : 1 - pow(2, -10 * p); } // Modeled after the piecewise exponential // y = (1/2)2^(10(2x - 1)) ; [0,0.5) // y = -(1/2)*2^(-10(2x - 1))) + 1 ; [0.5,1] func ExponentialEaseInOut(p:Double)->Double { if(p == 0.0 || p == 1.0) { return p; } if(p < 0.5) { return 0.5 * pow(2, (20 * p) - 10); } else { return -0.5 * pow(2, (-20 * p) + 10) + 1; } } // Modeled after the damped sine wave y = sin(13pi/2*x)*pow(2, 10 * (x - 1)) func ElasticEaseIn(p:Double)->Double { return sinDouble(num: 13 * M_PI_2_f * p) * pow(2, 10.0 * (p - 1.0)); } // Modeled after the damped sine wave y = sin(-13pi/2*(x + 1))*pow(2, -10x) + 1 func ElasticEaseOut(p:Double)->Double { return sinDouble(num: -13 * M_PI_2_f * (p + 1)) * pow(2, -10 * p) + 1; } // Modeled after the piecewise exponentially-damped sine wave: // y = (1/2)*sin(13pi/2*(2*x))*pow(2, 10 * ((2*x) - 1)) ; [0,0.5) // y = (1/2)*(sin(-13pi/2*((2x-1)+1))*pow(2,-10(2*x-1)) + 2) ; [0.5, 1] func ElasticEaseInOut(p:Double)->Double { if(p < 0.5) { return 0.5 * sinDouble(num: 13.0 * M_PI_2_f * (2 * p)) * pow(2, 10 * ((2 * p) - 1)); } else { return 0.5 * (sinDouble(num: -13 * M_PI_2_f * ((2 * p - 1) + 1)) * pow(2, -10 * (2 * p - 1)) + 2); } } // Modeled after the overshooting cubic y = x^3-x*sin(x*pi) func BackEaseIn(p:Double)->Double { return p * p * p - p * sinDouble(num: p * M_PI_f); } // Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi)) func BackEaseOut(p:Double)->Double { let f:Double = (1 - p); return 1 - (f * f * f - f * sinDouble(num: f * M_PI_f)); } // Modeled after the piecewise overshooting cubic function: // y = (1/2)*((2x)^3-(2x)*sin(2*x*pi)) ; [0, 0.5) // y = (1/2)*(1-((1-x)^3-(1-x)*sin((1-x)*pi))+1) ; [0.5, 1] func BackEaseInOut(p:Double)->Double { if(p < 0.5) { let f:Double = 2 * p; return 0.5 * (f * f * f - f * sinDouble(num: f * M_PI_f)); } else { let f:Double = (1 - (2*p - 1)); return 0.5 * (1 - (f * f * f - f * sinDouble(num: f * M_PI_f))) + 0.5; } } func BounceEaseIn(p:Double)->Double { return 1 - BounceEaseOut(p: 1 - p); } func BounceEaseOut(p:Double)->Double { if(p < 4/11.0) { return (121 * p * p)/16.0; } else if(p < 8/11.0) { return (363/40.0 * p * p) - (99/10.0 * p) + 17/5.0; } else if(p < 9/10.0) { return (4356/361.0 * p * p) - (35442/1805.0 * p) + 16061/1805.0; } else { return (54/5.0 * p * p) - (513/25.0 * p) + 268/25.0; } } func BounceEaseInOut(p:Double)->Double { if(p < 0.5) { return 0.5 * BounceEaseIn(p: p*2); } else { return 0.5 * BounceEaseOut(p: p * 2 - 1) + 0.5; } }
mit
6cc2ab4d7b79086d8b8a8b9ee8d7a491
21.455108
106
0.526954
2.526297
false
false
false
false
crashlytics/cannonball-ios
Cannonball/PoemTimelineViewController.swift
2
3613
// // Copyright (C) 2017 Google, Inc. and other contributors. // // 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 TwitterKit import Crashlytics class PoemTimelineViewController: TWTRTimelineViewController { // MARK: Properties // Search query for Tweets matching the right hashtags and containing an attached poem picture. let poemSearchQuery = "#cannonballapp AND pic.twitter.com AND (#adventure OR #romance OR #nature OR #mystery)" // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Log Answers Custom Event. Answers.logCustomEvent(withName: "Viewed Poem Timeline", customAttributes: nil) let client = TWTRAPIClient() self.dataSource = TWTRSearchTimelineDataSource(searchQuery: self.poemSearchQuery, apiClient: client) // Customize the table view. let headerHeight: CGFloat = 15 tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: headerHeight)) tableView.tableFooterView = UIView() tableView.backgroundColor = UIColor.cannonballBeigeColor() // Customize the navigation bar. title = "Popular Poems" navigationController?.navigationBar.isTranslucent = true // Add an initial offset to the table view to show the animated refresh control. let refreshControlOffset = refreshControl?.frame.size.height tableView.frame.origin.y += refreshControlOffset! refreshControl?.tintColor = UIColor.cannonballGreenColor() refreshControl?.beginRefreshing() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Make sure the navigation bar is not translucent when scrolling the table view. navigationController?.navigationBar.isTranslucent = false // Display a label on the background if there are no recent Tweets to display. let noTweetsLabel = UILabel() noTweetsLabel.text = "Sorry, there are no recent Tweets to display." noTweetsLabel.textAlignment = .center noTweetsLabel.textColor = UIColor.cannonballGreenColor() noTweetsLabel.font = UIFont(name: "HelveticaNeue", size: CGFloat(14)) tableView.backgroundView = noTweetsLabel tableView.backgroundView?.isHidden = true tableView.backgroundView?.alpha = 0 toggleNoTweetsLabel() } // MARK: Utilities fileprivate func toggleNoTweetsLabel() { if tableView.numberOfRows(inSection: 0) == 0 { UIView.animate(withDuration: 0.15, animations: { self.tableView.backgroundView!.isHidden = false self.tableView.backgroundView!.alpha = 1 }) } else { UIView.animate(withDuration: 0.15, animations: { self.tableView.backgroundView!.alpha = 0 }, completion: { finished in self.tableView.backgroundView!.isHidden = true } ) } } }
apache-2.0
d40df2ac0a7b64448d8f5838ecc77239
37.43617
127
0.672294
5.018056
false
false
false
false
kevintavog/Radish
src/Radish/PlacenameDetailsProvider.swift
1
3651
import Foundation import Alamofire import SwiftyJSON open class PlacenameDetail { public let name: String public let value: String init(name: String, value: String) { self.name = name self.value = value } } open class PlacenameDetailsProvider { public init() { } public func lookup(latitude: Double, longitude: Double) -> [PlacenameDetail] { var details = [PlacenameDetail]() let url = "\(Preferences.baseLocationLookup)api/v1/test" let parameters = [ "lat": "\(latitude)", "lon": "\(longitude)"] var error: Swift.Error? = nil var resultData: Data? = nil let semaphore = DispatchSemaphore(value: 0) Alamofire.request(url, parameters: parameters) .validate() .response { response in if response.error != nil { error = response.error } else { resultData = response.data } semaphore.signal() } semaphore.wait() if error != nil { return details } do { let json = try JSON(data: resultData!) details.append(contentsOf: getDetails(json["ocd"], "ocd")) details.append(contentsOf: getDetails(json["overpass"], "overpass")) details.append(contentsOf: getDetails(json["azure"], "azure")) details.append(contentsOf: getDetails(json["foursquare"], "foursquare")) details.append(contentsOf: getDetails(json["ocd_results"], "ocd_results")) details.append(contentsOf: getDetails(json["azure_results"], "azure_results")) details.append(contentsOf: getDetails(json["overpass_elements"], "overpass_elements")) return details } catch { return details } } private func getDetails(_ json: JSON?, _ prefix: String) -> [PlacenameDetail] { var details = [PlacenameDetail]() if let validJson = json { for (key,subJson):(String, JSON) in validJson { if let jsonArray = subJson.array { // If it's an array of objects, call recursively, otherwise convert each item to a string if let first = jsonArray.first { if nil != first.rawValue as? String { let items: [String] = jsonArray.compactMap({ $0.rawValue as? String }) let val = "[" + items.joined(separator: ", ") + "]" details.append(PlacenameDetail(name: prefix + "." + key, value: val)) } else { for (index, arraySubJson) in jsonArray.enumerated() { details.append(contentsOf: getDetails(arraySubJson, "\(prefix).\(key).\(index)")) } } } } else if let jsonDictionary = subJson.dictionary { for (dictionaryKey, dictionaryJson) in jsonDictionary { details.append(contentsOf: getDetails(dictionaryJson, "\(prefix).\(key).\(dictionaryKey)")) } } else { details.append(PlacenameDetail(name: prefix + "." + key, value: subJson.rawString()!)) } } } if details.count > 0 { details.insert(PlacenameDetail(name: "", value: ""), at: 0) } return details } }
mit
c3bb3d158ff2e1d1692c73879f47b79b
35.148515
115
0.511367
4.920485
false
false
false
false
jalehman/YelpClone
YelpClone/YelpFilters.swift
1
580
// // YelpFilters.swift // YelpClone // // Created by Josh Lehman on 2/15/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import Foundation class YelpFilters: NSObject { var sort: Int? var categories: NSMutableSet = NSMutableSet() var radius: Int? var deals: Bool? init(sort: Int? = nil, categories: NSMutableSet = NSMutableSet(), radius: Int? = nil, deals: Bool? = nil) { self.sort = sort self.categories = NSMutableSet(set: categories, copyItems: true) self.radius = radius self.deals = deals } }
gpl-2.0
0177d4e99d12df26557a5572cb34821c
24.26087
111
0.636207
3.694268
false
false
false
false
kean/Arranged
Tests/Internal.swift
1
4522
// The MIT License (MIT) // // Copyright (c) 2018 Alexander Grebenyuk (github.com/kean). import Arranged import UIKit import XCTest func assertEqualConstraints(_ constraints1: [NSLayoutConstraint], _ constraints2: [NSLayoutConstraint]) -> Bool { func filterOutMarginContraints(_ constraints: [NSLayoutConstraint]) -> [NSLayoutConstraint] { return constraints.filter { return $0.identifier?.hasSuffix("Margin-guide-constraint") == false } } // We fitler out margin-guide constraints because Arranged.StackView doesn't use those return _assertEqualConstraints(filterOutMarginContraints(constraints1), filterOutMarginContraints(constraints2)) } func _assertEqualConstraints(_ constraints1: [NSLayoutConstraint], _ constraints2: [NSLayoutConstraint]) -> Bool { guard constraints1.count == constraints2.count else { XCTFail("Constraints count doesn't match") return false } var array1 = constraints1 var array2 = constraints2 while let c1 = array1.popLast() { let idx2 = array2.index { c2 in return isEqual(c1, c2) } guard let unpackedIdx2 = idx2 else { XCTFail("Couldn't find matching constraint for \(c1)") return false } array2.remove(at: unpackedIdx2) } guard array1.count == 0 && array2.count == 0 else { XCTFail("Failed to match all constraints") return false } return true } // MARK: Constrain Comparison func isEqual(_ lhs: NSLayoutConstraint, _ rhs: NSLayoutConstraint) -> Bool { func identifier(_ constraint: NSLayoutConstraint) -> String? { return constraint.identifier?.replacingOccurrences(of: "ASV-", with: "UISV-") } guard identifier(lhs) == identifier(rhs) else { return false } func isEqual(_ item1: AnyObject?, _ item2: AnyObject?) -> Bool { // True if both nil if item1 == nil && item2 == nil { return true } // True if both items are stack views if ((item1 is UIStackView && item2 is Arranged.StackView) || (item1 is Arranged.StackView && item2 is UIStackView)) { return true } // True if both are for content views with the same indexes if let view1 = item1 as? UIView, let view2 = item2 as? UIView { return view1.test_isContentView && view2.test_isContentView && view1.tag == view2.tag } // FIXME: Find a better way to test layout guides // Assume that the remaining items are spacers, we can't check really return item1 != nil && item2 != nil } guard isEqual(lhs.firstItem, rhs.firstItem) && isEqual(lhs.secondItem, rhs.secondItem) else { return false } return lhs.firstAttribute == rhs.firstAttribute && lhs.secondAttribute == rhs.secondAttribute && lhs.relation == rhs.relation && lhs.constant == rhs.constant && lhs.multiplier == rhs.multiplier && lhs.priority == rhs.priority } // MARK: Misc func constraintsFor(_ view: UIView) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() constraints.append(contentsOf: view.constraints) for subview in view.subviews { constraints.append(contentsOf: subview.constraints) } return constraints } extension UIStackViewAlignment { var toString: String { switch self { case .fill: return ".Fill" case .leading: return ".Leading" case .firstBaseline: return ".FirstBaseline" case .center: return ".Center" case .lastBaseline: return ".LastBaseline" case .trailing: return ".Trailing" } } } extension UIStackViewDistribution { var toString: String { switch self { case .fill: return ".Fill" case .fillEqually: return ".FillEqually" case .fillProportionally: return ".FillProportionally" case .equalSpacing: return ".EqualSpacing" case .equalCentering: return ".EqualCentering" } } } private struct AssociatedKeys { static var IsContentView = "Arranged.Test.IsContentView" } extension UIView { var test_isContentView: Bool { get { return objc_getAssociatedObject(self, &AssociatedKeys.IsContentView) != nil } set { objc_setAssociatedObject(self, &AssociatedKeys.IsContentView, true, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
mit
d8adba0b2a92245813533d1e31a8ce1d
31.532374
116
0.636223
4.600203
false
false
false
false
mshhmzh/firefox-ios
Storage/SQL/SQLiteBookmarksSyncing.swift
4
49482
/* 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 Deferred import Foundation import Shared import XCGLogger private let log = Logger.syncLogger extension SQLiteBookmarks: LocalItemSource { public func getLocalItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksLocal, guid: guid) } public func getLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.db.getMirrorItemsFromTable(TableBookmarksLocal, guids: guids) } public func prefetchLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Not implemented for SQLiteBookmarks.") return succeed() } } extension SQLiteBookmarks: MirrorItemSource { public func getMirrorItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksMirror, guid: guid) } public func getMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.db.getMirrorItemsFromTable(TableBookmarksMirror, guids: guids) } public func prefetchMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Not implemented for SQLiteBookmarks.") return succeed() } } extension SQLiteBookmarks { func getSQLToOverrideFolder(folder: GUID, atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { return self.getSQLToOverrideFolders([folder], atModifiedTime: modified) } func getSQLToOverrideFolders(folders: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { if folders.isEmpty { return (sql: [], args: []) } let vars = BrowserDB.varlist(folders.count) let args: Args = folders.map { $0 as AnyObject } // Copy it to the local table. // Most of these will be NULL, because we're only dealing with folders, // and typically only the Mobile Bookmarks root. let overrideSQL = "INSERT OR IGNORE INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," + " description, tags, keyword, folderName, queryId, is_deleted, " + " local_modified, sync_status, faviconID) " + "SELECT guid, type, bmkUri, title, parentid, parentName, " + "feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " + "is_deleted, " + "\(modified) AS local_modified, \(SyncStatus.Changed.rawValue) AS sync_status, faviconID " + "FROM \(TableBookmarksMirror) WHERE guid IN \(vars)" // Copy its mirror structure. let dropSQL = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(vars)" let copySQL = "INSERT INTO \(TableBookmarksLocalStructure) " + "SELECT * FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(vars)" // Mark as overridden. let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)" return (sql: [overrideSQL, dropSQL, copySQL, markSQL], args: args) } func getSQLToOverrideNonFolders(records: [GUID], atModifiedTime modified: Timestamp) -> (sql: [String], args: Args) { log.info("Getting SQL to override \(records).") if records.isEmpty { return (sql: [], args: []) } let vars = BrowserDB.varlist(records.count) let args: Args = records.map { $0 as AnyObject } // Copy any that aren't overridden to the local table. let overrideSQL = "INSERT OR IGNORE INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, parentid, parentName, feedUri, siteUri, pos," + " description, tags, keyword, folderName, queryId, is_deleted, " + " local_modified, sync_status, faviconID) " + "SELECT guid, type, bmkUri, title, parentid, parentName, " + "feedUri, siteUri, pos, description, tags, keyword, folderName, queryId, " + "is_deleted, " + "\(modified) AS local_modified, \(SyncStatus.Changed.rawValue) AS sync_status, faviconID " + "FROM \(TableBookmarksMirror) WHERE guid IN \(vars) AND is_overridden = 0" // Mark as overridden. let markSQL = "UPDATE \(TableBookmarksMirror) SET is_overridden = 1 WHERE guid IN \(vars)" return (sql: [overrideSQL, markSQL], args: args) } /** * Insert a bookmark into the specified folder. * If the folder doesn't exist, or is deleted, insertion will fail. * * Preconditions: * * `deferred` has not been filled. * * this function is called inside a transaction that hasn't been finished. * * Postconditions: * * `deferred` has been filled with success or failure. * * the transaction will include any status/overlay changes necessary to save the bookmark. * * the return value determines whether the transaction should be committed, and * matches the success-ness of the Deferred. * * Sorry about the long line. If we break it, the indenting below gets crazy. */ private func insertBookmarkInTransaction(deferred: Success, url: NSURL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String, conn: SQLiteDBConnection, inout err: NSError?) -> Bool { log.debug("Inserting bookmark in transaction on thread \(NSThread.currentThread())") // Keep going if this returns true. func change(sql: String, args: Args?, desc: String) -> Bool { err = conn.executeChange(sql, withArgs: args) if let err = err { log.error(desc) deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err))) return false } return true } let urlString = url.absoluteString let newGUID = Bytes.generateGUID() let now = NSDate.now() let parentArgs: Args = [parent] //// Insert the new bookmark and icon without touching structure. var args: Args = [ newGUID, BookmarkNodeType.Bookmark.rawValue, urlString, title, parent, parentTitle, NSDate.nowNumber(), SyncStatus.New.rawValue, ] let faviconID: Int? // Insert the favicon. if let icon = favicon { faviconID = self.favicons.insertOrUpdate(conn, obj: icon) } else { faviconID = nil } log.debug("Inserting bookmark with GUID \(newGUID) and specified icon \(faviconID).") // If the caller didn't provide an icon (and they usually don't!), // do a reverse lookup in history. We use a view to make this simple. let iconValue: String if let faviconID = faviconID { iconValue = "?" args.append(faviconID) } else { iconValue = "(SELECT iconID FROM \(ViewIconForURL) WHERE url = ?)" args.append(urlString) } let insertSQL = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, parentid, parentName, local_modified, sync_status, faviconID) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, \(iconValue))" if !change(insertSQL, args: args, desc: "Error inserting \(newGUID).") { return false } let bumpParentStatus = { (status: Int) -> Bool in let bumpSQL = "UPDATE \(TableBookmarksLocal) SET sync_status = \(status), local_modified = \(now) WHERE guid = ?" return change(bumpSQL, args: parentArgs, desc: "Error bumping \(parent)'s modified time.") } func overrideParentMirror() -> Bool { // We do this slightly tortured work so that we can reuse these queries // in a different context. let (sql, args) = getSQLToOverrideFolder(parent, atModifiedTime: now) var generator = sql.generate() while let query = generator.next() { if !change(query, args: args, desc: "Error running overriding query.") { return false } } return true } //// Make sure our parent is overridden and appropriately bumped. // See discussion here: <https://github.com/mozilla/firefox-ios/commit/2041f1bbde430de29aefb803aae54ed26db47d23#commitcomment-14572312> // Note that this isn't as obvious as you might think. We must: let localStatusFactory: SDRow -> (Int, Bool) = { row in let status = row["sync_status"] as! Int let deleted = (row["is_deleted"] as! Int) != 0 return (status, deleted) } let overriddenFactory: SDRow -> Bool = { row in row.getBoolean("is_overridden") } // TODO: these can be merged into a single query. let mirrorStatusSQL = "SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = ?" let localStatusSQL = "SELECT sync_status, is_deleted FROM \(TableBookmarksLocal) WHERE guid = ?" let mirrorStatus = conn.executeQuery(mirrorStatusSQL, factory: overriddenFactory, withArgs: parentArgs)[0] let localStatus = conn.executeQuery(localStatusSQL, factory: localStatusFactory, withArgs: parentArgs)[0] let parentExistsInMirror = mirrorStatus != nil let parentExistsLocally = localStatus != nil // * Figure out if we were already overridden. We only want to re-clone // if we weren't. if !parentExistsLocally { if !parentExistsInMirror { deferred.fillIfUnfilled(Maybe(failure: DatabaseError(description: "Folder \(parent) doesn't exist in either mirror or local."))) return false } // * Mark the parent folder as overridden if necessary. // Overriding the parent involves copying the parent's structure, so that // we can amend it, but also the parent's row itself so that we know it's // changed. overrideParentMirror() } else { let (status, deleted) = localStatus! if deleted { log.error("Trying to insert into deleted local folder.") deferred.fillIfUnfilled(Maybe(failure: DatabaseError(description: "Local folder \(parent) is deleted."))) return false } // * Bump the overridden parent's modified time. We already copied its // structure and values, and if it's in the local table it'll either // already be New or Changed. if let syncStatus = SyncStatus(rawValue: status) { switch syncStatus { case .Synced: log.debug("We don't expect folders to ever be marked as Synced.") if !bumpParentStatus(SyncStatus.Changed.rawValue) { return false } case .New: fallthrough case .Changed: // Leave it marked as new or changed, but bump the timestamp. if !bumpParentStatus(syncStatus.rawValue) { return false } } } else { log.warning("Local folder marked with unknown state \(status). This should never occur.") if !bumpParentStatus(SyncStatus.Changed.rawValue) { return false } } } /// Add the new bookmark as a child in the modified local structure. // We always append the new row: after insertion, the new item will have the largest index. let newIndex = "(SELECT (COALESCE(MAX(idx), -1) + 1) AS newIndex FROM \(TableBookmarksLocalStructure) WHERE parent = ?)" let structureSQL = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "VALUES (?, ?, \(newIndex))" let structureArgs: Args = [parent, newGUID, parent] if !change(structureSQL, args: structureArgs, desc: "Error adding new item \(newGUID) to local structure.") { return false } log.debug("Returning true to commit transaction on thread \(NSThread.currentThread())") /// Fill the deferred and commit the transaction. deferred.fill(Maybe(success: ())) return true } /** * Assumption: the provided folder GUID exists in either the local table or the mirror table. */ func insertBookmark(url: NSURL, title: String, favicon: Favicon?, intoFolder parent: GUID, withTitle parentTitle: String) -> Success { log.debug("Inserting bookmark task on thread \(NSThread.currentThread())") let deferred = Success() var error: NSError? error = self.db.transaction(synchronous: false, err: &error) { (conn, err) -> Bool in self.insertBookmarkInTransaction(deferred, url: url, title: title, favicon: favicon, intoFolder: parent, withTitle: parentTitle, conn: conn, err: &err) } log.debug("Returning deferred on thread \(NSThread.currentThread())") return deferred } } private extension BookmarkMirrorItem { func getChildrenArgs() -> [Args] { // Only folders have children, and we manage roots ourselves. if self.type != .Folder || self.guid == BookmarkRoots.RootGUID { return [] } let parent = self.guid var idx = 0 return self.children?.map { child in let ret: Args = [parent, child, idx] idx += 1 return ret } ?? [] } func getUpdateOrInsertArgs() -> Args { let args: Args = [ self.type.rawValue, NSNumber(unsignedLongLong: self.serverModified), self.isDeleted ? 1 : 0, self.hasDupe ? 1 : 0, self.parentID, self.parentName, self.feedURI, self.siteURI, self.pos, self.title, self.description, self.bookmarkURI, self.tags, self.keyword, self.folderName, self.queryID, self.guid, ] return args } } private func deleteStructureForGUIDs(guids: [GUID], fromTable table: String, connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) -> NSError? { log.debug("Deleting \(guids.count) parents from \(table).") let chunks = chunk(guids, by: maxVars) for chunk in chunks { let inList = Array<String>(count: chunk.count, repeatedValue: "?").joinWithSeparator(", ") let delStructure = "DELETE FROM \(table) WHERE parent IN (\(inList))" let args: Args = chunk.flatMap { $0 as AnyObject } if let error = connection.executeChange(delStructure, withArgs: args) { log.error("Updating structure: \(error.description).") return error } } return nil } private func insertStructureIntoTable(table: String, connection: SQLiteDBConnection, children: [Args], maxVars: Int) -> NSError? { if children.isEmpty { return nil } // Insert the new structure rows. This uses three vars per row. let maxRowsPerInsert: Int = maxVars / 3 let chunks = chunk(children, by: maxRowsPerInsert) for chunk in chunks { log.verbose("Inserting \(chunk.count)…") let childArgs: Args = chunk.flatMap { $0 } // Flatten [[a, b, c], [...]] into [a, b, c, ...]. let ins = "INSERT INTO \(table) (parent, child, idx) VALUES " + Array<String>(count: chunk.count, repeatedValue: "(?, ?, ?)").joinWithSeparator(", ") log.debug("Inserting \(chunk.count) records (out of \(children.count)).") if let error = connection.executeChange(ins, withArgs: childArgs) { return error } } return nil } /** * This stores incoming records in a buffer. * When appropriate, the buffer is merged with the mirror and local storage * in the DB. */ public class SQLiteBookmarkBufferStorage: BookmarkBufferStorage { let db: BrowserDB public init(db: BrowserDB) { self.db = db } public func synchronousBufferCount() -> Int? { return self.db.runQuery("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", args: nil, factory: IntFactory).value.successValue?[0] } /** * Remove child records for any folders that've been deleted or are empty. */ private func deleteChildrenInTransactionWithGUIDs(guids: [GUID], connection: SQLiteDBConnection, withMaxVars maxVars: Int=BrowserDB.MaxVariableNumber) -> NSError? { return deleteStructureForGUIDs(guids, fromTable: TableBookmarksBufferStructure, connection: connection, withMaxVars: maxVars) } public func isEmpty() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksBuffer)") } /** * This is a little gnarly because our DB access layer is rough. * Within a single transaction, we walk the list of items, attempting to update * and inserting if the update failed. (TODO: batch the inserts!) * Once we've added all of the records, we flatten all of their children * into big arg lists and hard-update the structure table. */ public func applyRecords(records: [BookmarkMirrorItem]) -> Success { return self.applyRecords(records, withMaxVars: BrowserDB.MaxVariableNumber) } public func applyRecords(records: [BookmarkMirrorItem], withMaxVars maxVars: Int) -> Success { let deferred = Deferred<Maybe<()>>(defaultQueue: dispatch_get_main_queue()) let deleted = records.filter { $0.isDeleted }.map { $0.guid } let values = records.map { $0.getUpdateOrInsertArgs() } let children = records.filter { !$0.isDeleted }.flatMap { $0.getChildrenArgs() } let folders = records.filter { $0.type == BookmarkNodeType.Folder }.map { $0.guid } var err: NSError? self.db.transaction(&err) { (conn, err) -> Bool in // These have the same values in the same order. let update = "UPDATE \(TableBookmarksBuffer) SET " + "type = ?, server_modified = ?, is_deleted = ?, " + "hasDupe = ?, parentid = ?, parentName = ?, " + "feedUri = ?, siteUri = ?, pos = ?, title = ?, " + "description = ?, bmkUri = ?, tags = ?, keyword = ?, " + "folderName = ?, queryId = ? " + "WHERE guid = ?" let insert = "INSERT OR IGNORE INTO \(TableBookmarksBuffer) " + "(type, server_modified, is_deleted, hasDupe, parentid, parentName, " + "feedUri, siteUri, pos, title, description, bmkUri, tags, keyword, folderName, queryId, guid) " + "VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" for args in values { if let error = conn.executeChange(update, withArgs: args) { log.error("Updating mirror in buffer: \(error.description).") err = error deferred.fill(Maybe(failure: DatabaseError(err: error))) return false } if conn.numberOfRowsModified > 0 { continue } if let error = conn.executeChange(insert, withArgs: args) { log.error("Inserting mirror into buffer: \(error.description).") err = error deferred.fill(Maybe(failure: DatabaseError(err: error))) return false } } // Delete existing structure for any folders we've seen. We always trust the folders, // not the children's parent pointers, so we do this here: we'll insert their current // children right after, when we process the child structure rows. // We only drop the child structure for deleted folders, not the record itself. // Deleted records stay in the buffer table so that we know about the deletion // when we do a real sync! log.debug("\(folders.count) folders and \(deleted.count) deleted maybe-folders to drop from buffer structure table.") if let error = self.deleteChildrenInTransactionWithGUIDs(folders + deleted, connection: conn) { deferred.fill(Maybe(failure: DatabaseError(err: error))) return false } // (Re-)insert children in chunks. log.debug("Inserting \(children.count) children.") if let error = insertStructureIntoTable(TableBookmarksBufferStructure, connection: conn, children: children, maxVars: maxVars) { log.error("Updating buffer structure: \(error.description).") err = error deferred.fill(Maybe(failure: DatabaseError(err: error))) return false } if err == nil { deferred.fillIfUnfilled(Maybe(success: ())) return true } deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err))) return false } return deferred } public func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteBookmarkBufferStorage: BufferItemSource { public func getBufferItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.db.getMirrorItemFromTable(TableBookmarksBuffer, guid: guid) } public func getBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.db.getMirrorItemsFromTable(TableBookmarksBuffer, guids: guids) } public func prefetchBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { log.debug("Not implemented.") return succeed() } } extension BrowserDB { private func getMirrorItemFromTable(table: String, guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { let args: Args = [guid] let sql = "SELECT * FROM \(table) WHERE guid = ?" return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory) >>== { cursor in guard let item = cursor[0] else { return deferMaybe(DatabaseError(description: "Expected to find \(guid) in \(table) but did not.")) } return deferMaybe(item) } } private func getMirrorItemsFromTable<T: CollectionType where T.Generator.Element == GUID>(table: String, guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { var acc: [GUID: BookmarkMirrorItem] = [:] func accumulate(args: Args) -> Success { let sql = "SELECT * FROM \(table) WHERE guid IN \(BrowserDB.varlist(args.count))" return self.runQuery(sql, args: args, factory: BookmarkFactory.mirrorItemFactory) >>== { cursor in cursor.forEach { row in guard let row = row else { return } // Oh, Cursor. acc[row.guid] = row } return succeed() } } let args: Args = guids.map { $0 as AnyObject } if args.count < BrowserDB.MaxVariableNumber { return accumulate(args) >>> { deferMaybe(acc) } } let chunks = chunk(args, by: BrowserDB.MaxVariableNumber) return walk(chunks.lazy.map { Array($0) }, f: accumulate) >>> { deferMaybe(acc) } } } extension MergedSQLiteBookmarks: BookmarkBufferStorage { public func synchronousBufferCount() -> Int? { return self.buffer.synchronousBufferCount() } public func isEmpty() -> Deferred<Maybe<Bool>> { return self.buffer.isEmpty() } public func applyRecords(records: [BookmarkMirrorItem]) -> Success { return self.buffer.applyRecords(records) } public func doneApplyingRecordsAfterDownload() -> Success { // It doesn't really matter which one we checkpoint -- they're both backed by the same DB. return self.buffer.doneApplyingRecordsAfterDownload() } public func validate() -> Success { return self.buffer.validate() } public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { return self.buffer.getBufferedDeletions() } public func applyBufferCompletionOp(op: BufferCompletionOp, itemSources: ItemSources) -> Success { return self.buffer.applyBufferCompletionOp(op, itemSources: itemSources) } } extension MergedSQLiteBookmarks: BufferItemSource { public func getBufferItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.buffer.getBufferItemWithGUID(guid) } public func getBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.buffer.getBufferItemsWithGUIDs(guids) } public func prefetchBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { return self.buffer.prefetchBufferItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: MirrorItemSource { public func getMirrorItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.local.getMirrorItemWithGUID(guid) } public func getMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.local.getMirrorItemsWithGUIDs(guids) } public func prefetchMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { return self.local.prefetchMirrorItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: LocalItemSource { public func getLocalItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { return self.local.getLocalItemWithGUID(guid) } public func getLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> { return self.local.getLocalItemsWithGUIDs(guids) } public func prefetchLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { return self.local.prefetchLocalItemsWithGUIDs(guids) } } extension MergedSQLiteBookmarks: ShareToDestination { public func shareItem(item: ShareItem) { self.local.shareItem(item) } } // Not actually implementing SyncableBookmarks, just a utility for MergedSQLiteBookmarks to do so. extension SQLiteBookmarks { public func isUnchanged() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksLocal)") } public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { let sql = "SELECT guid, local_modified FROM \(TableBookmarksLocal) " + "WHERE is_deleted = 1" return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("local_modified")!) }) >>== { deferMaybe($0.asArray()) } } } extension MergedSQLiteBookmarks: SyncableBookmarks { public func isUnchanged() -> Deferred<Maybe<Bool>> { return self.local.isUnchanged() } public func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { return self.local.getLocalDeletions() } public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> { return self.local.treeForMirror() } public func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> { return self.local.treeForLocal() >>== { local in return self.local.treeForBuffer() >>== { buffer in return deferMaybe((local: local, buffer: buffer)) } } } } // MARK: - Validation of buffer contents. // Note that these queries tend to not have exceptions for deletions. // That's because a record can't be deleted in isolation -- if it's // deleted its parent should be changed, too -- and so our views will // correctly reflect that. We'll have updated rows in the structure table, // and updated values -- and thus a complete override -- for the parent and // the deleted child. private let allBufferStructuresReferToRecords = [ "SELECT s.child AS pointee, s.parent AS pointer FROM", ViewBookmarksBufferStructureOnMirror, "s LEFT JOIN", ViewBookmarksBufferOnMirror, "b ON b.guid = s.child WHERE b.guid IS NULL", ].joinWithSeparator(" ") private let allNonDeletedBufferRecordsAreInStructure = [ "SELECT b.guid AS missing, b.parentid AS parent FROM", ViewBookmarksBufferOnMirror, "b LEFT JOIN", ViewBookmarksBufferStructureOnMirror, "s ON b.guid = s.child WHERE s.child IS NULL AND", "b.is_deleted IS 0 AND b.parentid IS NOT '\(BookmarkRoots.RootGUID)'", ].joinWithSeparator(" ") private let allRecordsAreChildrenOnce = [ "SELECT s.child FROM", ViewBookmarksBufferStructureOnMirror, "s INNER JOIN (", "SELECT child, COUNT(*) AS dupes FROM", ViewBookmarksBufferStructureOnMirror, "GROUP BY child HAVING dupes > 1", ") i ON s.child = i.child", ].joinWithSeparator(" ") private let bufferParentidMatchesStructure = [ "SELECT b.guid, b.parentid, s.parent, s.child, s.idx FROM", TableBookmarksBuffer, "b JOIN", TableBookmarksBufferStructure, "s ON b.guid = s.child WHERE b.parentid IS NOT s.parent", ].joinWithSeparator(" ") public enum BufferInconsistency { case MissingValues case MissingStructure case OverlappingStructure case ParentIDDisagreement public var query: String { switch self { case .MissingValues: return allBufferStructuresReferToRecords case .MissingStructure: return allNonDeletedBufferRecordsAreInStructure case .OverlappingStructure: return allRecordsAreChildrenOnce case .ParentIDDisagreement: return bufferParentidMatchesStructure } } public var trackingEvent: String { switch self { case .MissingValues: return "missingvalues" case .MissingStructure: return "missingstructure" case .OverlappingStructure: return "overlappingstructure" case .ParentIDDisagreement: return "parentiddisagreement" } } public var description: String { switch self { case .MissingValues: return "Not all buffer structures refer to records." case .MissingStructure: return "Not all buffer records are in structure." case .OverlappingStructure: return "Some buffer structures refer to the same records." case .ParentIDDisagreement: return "Some buffer record parent IDs don't match structure." } } public static let all: [BufferInconsistency] = [.MissingValues, .MissingStructure, .OverlappingStructure, .ParentIDDisagreement] } public class BookmarksDatabaseError: DatabaseError {} extension SQLiteBookmarkBufferStorage { public func validate() -> Success { let notificationCenter = NSNotificationCenter.defaultCenter() var validations: [String: Bool] = [:] let deferred = BufferInconsistency.all.map { inc in self.db.queryReturnsNoResults(inc.query) >>== { yes in validations[inc.trackingEvent] = !yes guard yes else { let message = inc.description log.warning(message) return deferMaybe(BookmarksDatabaseError(description: message)) } return succeed() } }.allSucceed() deferred.upon { success in notificationCenter.postNotificationName(NotificationBookmarkBufferValidated, object: Box(validations)) } return deferred } public func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> { let sql = "SELECT guid, server_modified FROM \(TableBookmarksBuffer) " + "WHERE is_deleted = 1" return self.db.runQuery(sql, args: nil, factory: { ($0["guid"] as! GUID, $0.getTimestamp("server_modified")!) }) >>== { deferMaybe($0.asArray()) } } } extension SQLiteBookmarks { private func structureQueryForTable(table: String, structure: String) -> String { // We use a subquery so we get back rows for overridden folders, even when their // children aren't in the shadowing table. let sql = "SELECT s.parent AS parent, s.child AS child, COALESCE(m.type, -1) AS type " + "FROM \(structure) s LEFT JOIN \(table) m ON s.child = m.guid AND m.is_deleted IS NOT 1 " + "ORDER BY s.parent, s.idx ASC" return sql } private func remainderQueryForTable(table: String, structure: String) -> String { // This gives us value rows that aren't children of a folder. // You might notice that these complementary LEFT JOINs are how you // express a FULL OUTER JOIN in sqlite. // We exclude folders here because if they have children, they'll appear // in the structure query, and if they don't, they'll appear in the bottom // half of this query. let sql = "SELECT m.guid AS guid, m.type AS type " + "FROM \(table) m LEFT JOIN \(structure) s ON s.child = m.guid " + "WHERE m.is_deleted IS NOT 1 AND m.type IS NOT \(BookmarkNodeType.Folder.rawValue) AND s.child IS NULL " + "UNION ALL " + // This gives us folders with no children. "SELECT m.guid AS guid, m.type AS type " + "FROM \(table) m LEFT JOIN \(structure) s ON s.parent = m.guid " + "WHERE m.is_deleted IS NOT 1 AND m.type IS \(BookmarkNodeType.Folder.rawValue) AND s.parent IS NULL " return sql } private func statusQueryForTable(table: String) -> String { return "SELECT guid, is_deleted FROM \(table)" } private func treeForTable(table: String, structure: String, alwaysIncludeRoots includeRoots: Bool) -> Deferred<Maybe<BookmarkTree>> { // The structure query doesn't give us non-structural rows -- that is, if you // make a value-only change to a record, and it's not otherwise mentioned by // way of being a child of a structurally modified folder, it won't appear here at all. // It also doesn't give us empty folders, because they have no children. // We run a separate query to get those. let structureSQL = self.structureQueryForTable(table, structure: structure) let remainderSQL = self.remainderQueryForTable(table, structure: structure) let statusSQL = self.statusQueryForTable(table) func structureFactory(row: SDRow) -> StructureRow { let typeCode = row["type"] as! Int let type = BookmarkNodeType(rawValue: typeCode) // nil if typeCode is invalid (e.g., -1). return (parent: row["parent"] as! GUID, child: row["child"] as! GUID, type: type) } func nonStructureFactory(row: SDRow) -> BookmarkTreeNode { let guid = row["guid"] as! GUID let typeCode = row["type"] as! Int if let type = BookmarkNodeType(rawValue: typeCode) { switch type { case .Folder: return BookmarkTreeNode.Folder(guid: guid, children: []) default: return BookmarkTreeNode.NonFolder(guid: guid) } } else { return BookmarkTreeNode.Unknown(guid: guid) } } func statusFactory(row: SDRow) -> (GUID, Bool) { return (row["guid"] as! GUID, row.getBoolean("is_deleted")) } return self.db.runQuery(statusSQL, args: nil, factory: statusFactory) >>== { cursor in var deleted = Set<GUID>() var modified = Set<GUID>() cursor.forEach { pair in let (guid, del) = pair! // Oh, cursor. if del { deleted.insert(guid) } else { modified.insert(guid) } } return self.db.runQuery(remainderSQL, args: nil, factory: nonStructureFactory) >>== { cursor in let nonFoldersAndEmptyFolders = cursor.asArray() return self.db.runQuery(structureSQL, args: nil, factory: structureFactory) >>== { cursor in let structureRows = cursor.asArray() let tree = BookmarkTree.mappingsToTreeForStructureRows(structureRows, withNonFoldersAndEmptyFolders: nonFoldersAndEmptyFolders, withDeletedRecords: deleted, modifiedRecords: modified, alwaysIncludeRoots: includeRoots) return deferMaybe(tree) } } } } public func treeForMirror() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksMirror, structure: TableBookmarksMirrorStructure, alwaysIncludeRoots: true) } public func treeForBuffer() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksBuffer, structure: TableBookmarksBufferStructure, alwaysIncludeRoots: false) } public func treeForLocal() -> Deferred<Maybe<BookmarkTree>> { return self.treeForTable(TableBookmarksLocal, structure: TableBookmarksLocalStructure, alwaysIncludeRoots: false) } } // MARK: - Applying merge operations. public extension SQLiteBookmarkBufferStorage { public func applyBufferCompletionOp(op: BufferCompletionOp, itemSources: ItemSources) -> Success { log.debug("Marking buffer rows as applied.") if op.isNoOp { log.debug("Nothing to do.") return succeed() } var queries: [(sql: String, args: Args?)] = [] op.processedBufferChanges.subsetsOfSize(BrowserDB.MaxVariableNumber).forEach { guids in let varlist = BrowserDB.varlist(guids.count) let args: Args = guids.map { $0 as AnyObject } queries.append((sql: "DELETE FROM \(TableBookmarksBufferStructure) WHERE parent IN \(varlist)", args: args)) queries.append((sql: "DELETE FROM \(TableBookmarksBuffer) WHERE guid IN \(varlist)", args: args)) } return self.db.run(queries) } } extension MergedSQLiteBookmarks { public func applyLocalOverrideCompletionOp(op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success { log.debug("Applying local op to merged.") if op.isNoOp { log.debug("Nothing to do.") return succeed() } let deferred = Success() var err: NSError? let resultError = self.local.db.transaction(&err) { (conn, inout err: NSError?) in // This is a little tortured because we want it all to happen in a single transaction. // We walk through the accrued work items, applying them in the right order (e.g., structure // then value), doing so with the ugly NSError-based transaction API. // If at any point we fail, we abort, roll back the transaction (return false), // and reject the deferred. func change(sql: String, args: Args?=nil) -> Bool { if let e = conn.executeChange(sql, withArgs: args) { err = e deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: e))) return false } return true } // So we can trample the DB in any order. if !change("PRAGMA defer_foreign_keys = ON") { return false } log.debug("Deleting \(op.mirrorItemsToDelete.count) mirror items.") op.mirrorItemsToDelete .withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in guard err == nil else { return } let args: Args = guids.map { $0 as AnyObject } let varlist = BrowserDB.varlist(guids.count) let sqlMirrorStructure = "DELETE FROM \(TableBookmarksMirrorStructure) WHERE parent IN \(varlist)" if !change(sqlMirrorStructure, args: args) { return } let sqlMirror = "DELETE FROM \(TableBookmarksMirror) WHERE guid IN \(varlist)" change(sqlMirror, args: args) } if err != nil { return false } // Copy from other tables for simplicity. // Do this *before* we throw away local and buffer changes! // This is one reason why the local override step needs to be processed before the buffer is cleared. op.mirrorValuesToCopyFromBuffer .withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 as AnyObject } let varlist = BrowserDB.varlist(guids.count) let copySQL = [ "INSERT OR REPLACE INTO \(TableBookmarksMirror)", "(guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, server_modified)", "SELECT guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, server_modified", "FROM \(TableBookmarksBuffer)", "WHERE guid IN", varlist ].joinWithSeparator(" ") change(copySQL, args: args) } if err != nil { return false } op.mirrorValuesToCopyFromLocal .withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 as AnyObject } let varlist = BrowserDB.varlist(guids.count) let copySQL = [ // TODO: parentid might well be wrong. "INSERT OR REPLACE INTO \(TableBookmarksMirror)", "(guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, faviconID, server_modified)", "SELECT guid, type, parentid, parentName, feedUri, siteUri, pos, title, description,", "bmkUri, tags, keyword, folderName, queryId, faviconID,", // This will be fixed up in batches after the initial copy. "0 AS server_modified", "FROM \(TableBookmarksLocal) WHERE guid IN", varlist, ].joinWithSeparator(" ") change(copySQL, args: args) } op.modifiedTimes.forEach { (time, guids) in if err != nil { return } // This will never be too big: we upload in chunks // smaller than 999! precondition(guids.count < BrowserDB.MaxVariableNumber) log.debug("Swizzling server modified time to \(time) for \(guids.count) GUIDs.") let args: Args = guids.map { $0 as AnyObject } let varlist = BrowserDB.varlist(guids.count) let updateSQL = [ "UPDATE \(TableBookmarksMirror) SET server_modified = \(time)", "WHERE guid IN", varlist, ].joinWithSeparator(" ") change(updateSQL, args: args) } if err != nil { return false } log.debug("Marking \(op.processedLocalChanges.count) local changes as processed.") op.processedLocalChanges .withSubsetsOfSize(BrowserDB.MaxVariableNumber) { guids in guard err == nil else { return } let args: Args = guids.map { $0 as AnyObject } let varlist = BrowserDB.varlist(guids.count) let sqlLocalStructure = "DELETE FROM \(TableBookmarksLocalStructure) WHERE parent IN \(varlist)" if !change(sqlLocalStructure, args: args) { return } let sqlLocal = "DELETE FROM \(TableBookmarksLocal) WHERE guid IN \(varlist)" if !change(sqlLocal, args: args) { return } // If the values change, we'll handle those elsewhere, but at least we need to mark these as non-overridden. let sqlMirrorOverride = "UPDATE \(TableBookmarksMirror) SET is_overridden = 0 WHERE guid IN \(varlist)" change(sqlMirrorOverride, args: args) } if err != nil { return false } if !op.mirrorItemsToUpdate.isEmpty { let updateSQL = [ "UPDATE \(TableBookmarksMirror) SET", "type = ?, server_modified = ?, is_deleted = ?,", "hasDupe = ?, parentid = ?, parentName = ?,", "feedUri = ?, siteUri = ?, pos = ?, title = ?,", "description = ?, bmkUri = ?, tags = ?, keyword = ?,", "folderName = ?, queryId = ?, is_overridden = 0", "WHERE guid = ?", ].joinWithSeparator(" ") op.mirrorItemsToUpdate.forEach { (guid, mirrorItem) in // Break out of the loop if we failed. guard err == nil else { return } let args = mirrorItem.getUpdateOrInsertArgs() change(updateSQL, args: args) } if err != nil { return false } } if !op.mirrorItemsToInsert.isEmpty { let insertSQL = [ "INSERT OR IGNORE INTO \(TableBookmarksMirror) (", "type, server_modified, is_deleted,", "hasDupe, parentid, parentName,", "feedUri, siteUri, pos, title,", "description, bmkUri, tags, keyword,", "folderName, queryId, guid", "VALUES", "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ].joinWithSeparator(" ") op.mirrorItemsToInsert.forEach { (guid, mirrorItem) in // Break out of the loop if we failed. guard err == nil else { return } let args = mirrorItem.getUpdateOrInsertArgs() change(insertSQL, args: args) } if err != nil { return false } } if !op.mirrorStructures.isEmpty { let structureRows = op.mirrorStructures.flatMap { (parent, children) in return children.enumerate().map { (idx, child) -> Args in let vals: Args = [parent, child, idx] return vals } } let parents = op.mirrorStructures.map { $0.0 } if let e = deleteStructureForGUIDs(parents, fromTable: TableBookmarksMirrorStructure, connection: conn) { err = e deferred.fill(Maybe(failure: DatabaseError(err: err))) return false } if let e = insertStructureIntoTable(TableBookmarksMirrorStructure, connection: conn, children: structureRows, maxVars: BrowserDB.MaxVariableNumber) { err = e deferred.fill(Maybe(failure: DatabaseError(err: err))) return false } } // Commit the result. return true } if let err = resultError { log.warning("Got error “\(err.localizedDescription)”") deferred.fillIfUnfilled(Maybe(failure: DatabaseError(err: err))) } else { deferred.fillIfUnfilled(Maybe(success: ())) } return deferred } }
mpl-2.0
08bff57b3b5ec1047e49f240198fa92f
41.46867
249
0.597664
4.95404
false
false
false
false
mojio/mojio-ios-sdk
MojioSDK/Models/NotificationsSettings.swift
1
3568
// // NotificationsSettings.swift // Pods // // Created by Narayan Sainaney on 2016-06-30. // // import Foundation import ObjectMapper public class SettingsGeofence : Mappable { public dynamic var Id : String? = nil public dynamic var EnableEnterActivity: Bool = false public dynamic var EnableExitActivity: Bool = false public required convenience init?(_ map: Map) { self.init() } public required init() { } public static func primaryKey() -> String? { return "Id" } public func mapping(map: Map) { Id <- map["Id"] EnableEnterActivity <- map["EnableEnterActivity"] EnableExitActivity <- map["EnableExitActivity"] } } public class NotificationsSettings : Mappable { public var SpeedThreshold : Speed? = nil public dynamic var EnableTripCompletedActivity : Bool = false public dynamic var EnableTripStartActivity : Bool = false public dynamic var EnableLowFuelActivity : Bool = false public dynamic var EnableLowBatteryActivity : Bool = false public dynamic var EnableSpeedActivity : Bool = false public dynamic var EnableDtcActivity : Bool = false public dynamic var EnableCheckEngineActivity : Bool = false public dynamic var EnableTowActivity : Bool = false public dynamic var EnableMaintenanceActivity : Bool = false public dynamic var EnableRecallActivity : Bool = false public dynamic var EnableServiceBulletinActivity : Bool = false public dynamic var EnableDisturbanceActivity : Bool = false public dynamic var EnableAccidentActivity : Bool = false public dynamic var EnableDeviceUnpluggedActivity : Bool = false public dynamic var EnableGeofenceActivity : Bool = false public var Geofences : [SettingsGeofence] = [] public required convenience init?(_ map: Map) { self.init() } public required init() { } public func jsonDict () -> NSDictionary { var dictionary = self.toJSON() if let threshold = self.SpeedThreshold { dictionary["SpeedThreshold"] = threshold.jsonDict() } var geofences: [[String: AnyObject]] = [] for geofence in self.Geofences { geofences.append(geofence.toJSON()) } dictionary["Geofences"] = geofences return dictionary } public func mapping(map: Map) { SpeedThreshold <- map["SpeedThreshold"] EnableTripStartActivity <- map["EnableTripStartActivity"] EnableTripCompletedActivity <- map["EnableTripCompletedActivity"] EnableLowFuelActivity <- map["EnableLowFuelActivity"] EnableLowBatteryActivity <- map["EnableLowBatteryActivity"] EnableSpeedActivity <- map["EnableSpeedActivity"] EnableDtcActivity <- map["EnableDtcActivity"] EnableCheckEngineActivity <- map["EnableCheckEngineActivity"] EnableTowActivity <- map["EnableTowActivity"] EnableMaintenanceActivity <- map["EnableMaintenanceActivity"] EnableRecallActivity <- map["EnableRecallActivity"] EnableServiceBulletinActivity <- map["EnableServiceBulletinActivity"] EnableDisturbanceActivity <- map["EnableDisturbanceActivity"] EnableAccidentActivity <- map["EnableAccidentActivity"] EnableDeviceUnpluggedActivity <- map["EnableDeviceUnpluggedActivity"] EnableGeofenceActivity <- map["EnableGeofenceActivity"] Geofences <- map["Geofences"] } }
mit
30c2d90772aafac5928ff2c5b5ade4a4
33.650485
77
0.674327
5.025352
false
false
false
false