repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Characteristics/Characteristic.TargetVerticalTiltAngle.swift
mit
1
import Foundation public extension AnyCharacteristic { static func targetVerticalTiltAngle( _ value: Int = -90, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Vertical Tilt Angle", format: CharacteristicFormat? = .int, unit: CharacteristicUnit? = .arcdegrees, maxLength: Int? = nil, maxValue: Double? = 90, minValue: Double? = -90, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.targetVerticalTiltAngle( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func targetVerticalTiltAngle( _ value: Int = -90, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Vertical Tilt Angle", format: CharacteristicFormat? = .int, unit: CharacteristicUnit? = .arcdegrees, maxLength: Int? = nil, maxValue: Double? = 90, minValue: Double? = -90, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Int> { GenericCharacteristic<Int>( type: .targetVerticalTiltAngle, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
e969b21499f52dbf7bc757e65bd68eae
33.770492
75
0.585573
false
false
false
false
Pluto-tv/RxSwift
refs/heads/master
Rx.playground/Pages/Observable_Utility_Operators.xcplaygroundpage/Contents.swift
mit
14
//: [<< Previous](@previous) - [Index](Index) import RxSwift import Foundation /*: ## Observable Utility Operators A toolbox of useful Operators for working with Observables. */ /*: ### `subscribe` [More info in reactive.io website]( http://reactivex.io/documentation/operators/subscribe.html ) */ example("subscribe") { let sequenceOfInts = PublishSubject<Int>() sequenceOfInts .subscribe { print($0) } sequenceOfInts.on(.Next(1)) sequenceOfInts.on(.Completed) } /*: There are several variants of the `subscribe` operator. */ /*: ### `subscribeNext` */ example("subscribeNext") { let sequenceOfInts = PublishSubject<Int>() sequenceOfInts .subscribeNext { print($0) } sequenceOfInts.on(.Next(1)) sequenceOfInts.on(.Completed) } /*: ### `subscribeCompleted` */ example("subscribeCompleted") { let sequenceOfInts = PublishSubject<Int>() sequenceOfInts .subscribeCompleted { print("It's completed") } sequenceOfInts.on(.Next(1)) sequenceOfInts.on(.Completed) } /*: ### `subscribeError` */ example("subscribeError") { let sequenceOfInts = PublishSubject<Int>() sequenceOfInts .subscribeError { error in print(error) } sequenceOfInts.on(.Next(1)) sequenceOfInts.on(.Error(NSError(domain: "Examples", code: -1, userInfo: nil))) } /*: ### `doOn` register an action to take upon a variety of Observable lifecycle events ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/do.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/do.html ) */ example("doOn") { let sequenceOfInts = PublishSubject<Int>() sequenceOfInts .doOn { print("Intercepted event \($0)") } .subscribe { print($0) } sequenceOfInts.on(.Next(1)) sequenceOfInts.on(.Completed) } //: [Index](Index) - [Next >>](@next)
e0a84c7aa48b5a0f0e529e467534ff34
16.911504
96
0.628953
false
false
false
false
aberger/SwiftMite
refs/heads/develop
SwiftMite/MiteSync/MiteSync.swift
mit
1
// // MiteSync.swift // SwiftMite // // Created by Alex Berger on 6/8/14. // Copyright (c) 2014 aberger.me. All rights reserved. // import UIKit class MiteSync: NSObject { var operationQueue = NSOperationQueue() var subdomain: String var username: String var password: String init(subdomain: String, username: String, password: String) { self.subdomain = subdomain self.username = username self.password = password } func miteRetrieval(var retrievalPath: String, method: String, parameters: Dictionary<String, Dictionary<String, String>>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let url = NSURL(string: "https://" + self.subdomain + ".mite.yo.lk/" + retrievalPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)) let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 60.0) let credential = NSURLCredential(user: self.username, password: self.password, persistence: NSURLCredentialPersistence.None) if method == "POST" || method == "PUT" { var error: NSError? let requestData = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted, error: &error) request.HTTPBody = requestData } request.setValue("SwiftMite", forHTTPHeaderField: "User-Agent") request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("utf-8", forHTTPHeaderField: "Accept-Charset") request.HTTPMethod = method let operation = AFHTTPRequestOperation(request: request) operation.credential = credential operation.setCompletionBlockWithSuccess( { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in if operation.responseData != nil { var error: NSError? let responseJSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(operation.responseData, options: NSJSONReadingOptions.MutableContainers, error: &error) if responseJSON != nil { onSuccess(result: responseJSON) } else { onSuccess(result: true) } } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription) println(operation.responseObject) onFailure(error: error) }) operationQueue.addOperation(operation) } func timeEntries(#timeEntryID: Int?, customerID: Int?, projectID: Int?, serviceID: Int?, userID: Int?, limit: Int?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if customerID != nil { parameters["customer_id"] = String(customerID!) } if projectID != nil { parameters["project_id"] = String(projectID!) } if serviceID != nil { parameters["service_id"] = String(serviceID!) } if userID != nil { parameters["user_id"] = String(userID!) } if limit != nil { parameters["limit"] = String(limit!) } let timeEntries = MiteSyncTypes.TimeEntries var retrievalPath = timeEntries.syncTypeDescription() if timeEntryID != nil { retrievalPath += "/" + String(timeEntryID!) + ".json" } else { retrievalPath += ".json" } if parameters.count != 0 { // var parametersArray = String[]() retrievalPath += "?" for (filterKey, filterValue) in parameters { retrievalPath += filterKey + "=" + filterValue + "&" } // NSArray.componentsJoinedByString not working! // retrievalPath += ".json?" + parametersArray.componentsJoinedByString("&") } miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func addTimeEntry(#date: String?, minutes: Int?, note: String?, projectID: Int?, serviceID: Int?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if date != nil { parameters["date_at"] = date! } if minutes != nil { parameters["minutes"] = String(minutes!) } if note != nil { parameters["note"] = note! } if projectID != nil { parameters["project_id"] = String(projectID!) } if serviceID != nil { parameters["service_id"] = String(serviceID!) } let finalParams: Dictionary<String, Dictionary<String, String>> = ["time_entry": parameters] let timeEntries = MiteSyncTypes.TimeEntries let retrievalPath = timeEntries.syncTypeDescription() + ".json" miteRetrieval( retrievalPath, method: "POST", parameters: finalParams, onSuccess, onFailure) } func editTimeEntry(id: Int, date: String?, minutes: Int?, note: String?, projectID: Int?, serviceID: Int?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if date != nil { parameters["date_at"] = date! } if minutes != nil { parameters["minutes"] = String(minutes!) } if note != nil { parameters["note"] = note! } if projectID != nil { parameters["project_id"] = String(projectID!) } if serviceID != nil { parameters["service_id"] = String(serviceID!) } let finalParams: Dictionary<String, Dictionary<String, String>> = ["time_entry": parameters] let timeEntries = MiteSyncTypes.TimeEntries let retrievalPath = timeEntries.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval( retrievalPath, method: "PUT", parameters: finalParams, onSuccess, onFailure) } func deleteTimeEntry(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let timeEntries = MiteSyncTypes.TimeEntries let retrievalPath = timeEntries.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval(retrievalPath, method: "DELETE", parameters: nil, onSuccess, onFailure) } func currentTimeTracker(#onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let currentTimeTracker = MiteSyncTypes.TimeTracker let retrievalPath = currentTimeTracker.syncTypeDescription() miteRetrieval(retrievalPath, method: "GET", parameters: Dictionary<String, Dictionary<String, String>>(), onSuccess, onFailure) } func startTimeTracker(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let currentTimeTracker = MiteSyncTypes.TimeTracker let retrievalPath = currentTimeTracker.syncTypeDescription() miteRetrieval(retrievalPath, method: "PUT", parameters: Dictionary<String, Dictionary<String, String>>(), onSuccess, onFailure) } func stopTimeTracker(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let currentTimeTracker = MiteSyncTypes.TimeTracker let retrievalPath = currentTimeTracker.syncTypeDescription() miteRetrieval(retrievalPath, method: "DELETE", parameters: Dictionary<String, Dictionary<String, String>>(), onSuccess, onFailure) } func customers(#customerID: Int?, customerName: String?, limit: Int?, archived: Bool, var parameters: Dictionary<String, String>, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { if customerName != nil { parameters["name"] = customerName! } if limit != nil { parameters["limit"] = String(limit!) } let customers = MiteSyncTypes.Customers var retrievalPath = customers.syncTypeDescription() if customerID != nil { retrievalPath += "/" + String(customerID!) + ".json" } else if archived == true { retrievalPath += "/archived.json" } else { retrievalPath += ".json" } if parameters.count != 0 { // var parametersArray = String[]() retrievalPath += "?" for (filterKey, filterValue) in parameters { retrievalPath += filterKey + "=" + filterValue + "&" } // NSArray.componentsJoinedByString not working! // retrievalPath += ".json?" + parametersArray.componentsJoinedByString("&") } miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func addCustomer(#name: String!, note: String?, archived: Bool?, hourlyRate: Int?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>(); parameters["name"] = name if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) parameters["active_hourly_rate"] = "hourly_rate" } let finalParams: Dictionary<String, Dictionary<String, String>> = ["customer": parameters] let customers = MiteSyncTypes.Customers let retrievalPath = customers.syncTypeDescription() miteRetrieval( retrievalPath, method: "POST", parameters: finalParams, onSuccess, onFailure) } func editCustomer(id: Int, name: String?, note: String?, archived: Bool?, hourlyRate: Int?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if name != nil { parameters["name"] = name! } if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) parameters["active_hourly_rate"] = "hourly_rate" } let finalParams: Dictionary<String, Dictionary<String, String>> = ["customer": parameters] let customers = MiteSyncTypes.Customers let retrievalPath = customers.syncTypeDescription() + "/" + String(id) + ".json" println(retrievalPath) miteRetrieval( retrievalPath, method: "PUT", parameters: finalParams, onSuccess, onFailure) } func deleteCustomer(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let customers = MiteSyncTypes.Customers let retrievalPath = customers.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval(retrievalPath, method: "DELETE", parameters: nil, onSuccess, onFailure) } func projects(#projectID: Int?, projectName: String?, customerID: Int?, customerName: String?, limit: Int?, archived: Bool, var parameters: Dictionary<String, String>, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { if projectName != nil { parameters["name"] = projectName! } if customerID != nil { parameters["customer_id"] = String(customerID!) } if customerName != nil { parameters["customer_name"] = customerName! } if limit != nil { parameters["limit"] = String(limit!) } let projects = MiteSyncTypes.Projects var retrievalPath = projects.syncTypeDescription() if projectID != nil { retrievalPath += "/" + String(projectID!) + ".json" } else if archived == true { retrievalPath += "/archived.json" } else { retrievalPath += ".json" } if parameters.count != 0 { // var parametersArray = String[]() retrievalPath += "?" for (filterKey, filterValue) in parameters { retrievalPath += filterKey + "=" + filterValue + "&" } // NSArray.componentsJoinedByString not working! // retrievalPath += ".json?" + parametersArray.componentsJoinedByString("&") } miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func addProject(#name: String!, customerID: Int?, note: String?, archived: Bool?, hourlyRate: Int?, budget: Int?, budgetType: MiteBudgetDataType?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>(); parameters["name"] = name if customerID != nil { parameters["customer_id"] = String(customerID!) } if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) parameters["active_hourly_rate"] = "hourly_rate" } if budget != nil { parameters["budget"] = String(budget!) } if budgetType != nil { var budgetTypesDescription = budgetType!.budgetDataTypeDescription() parameters["budget_type"] = budgetTypesDescription } let finalParams: Dictionary<String, Dictionary<String, String>> = ["project": parameters] let projects = MiteSyncTypes.Projects let retrievalPath = projects.syncTypeDescription() miteRetrieval( retrievalPath, method: "POST", parameters: finalParams, onSuccess, onFailure) } func editProject(id: Int, name: String?, customerID: Int?, note: String?, archived: Bool?, hourlyRate: Int?, budget: Int?, budgetType: MiteBudgetDataType?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if name != nil { parameters["name"] = name! } if customerID != nil { parameters["customer_id"] = String(customerID!) } if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) parameters["active_hourly_rate"] = "hourly_rate" } if budget != nil { parameters["budget"] = String(budget!) } if budgetType != nil { var budgetTypesDescription = budgetType!.budgetDataTypeDescription() parameters["budget_type"] = budgetTypesDescription } var finalParams: Dictionary<String, Dictionary<String, String>> = ["project": parameters] let projects = MiteSyncTypes.Projects let retrievalPath = projects.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval( retrievalPath, method: "PUT", parameters: finalParams, onSuccess, onFailure) } func deleteProject(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let projects = MiteSyncTypes.Projects let retrievalPath = projects.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval(retrievalPath, method: "DELETE", parameters: nil, onSuccess, onFailure) } func services(#serviceID: Int?, serviceName: String?, limit: Int?, archived: Bool, var parameters: Dictionary<String, String>, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { if serviceName != nil { parameters["name"] = serviceName! } if limit != nil { parameters["limit"] = String(limit!) } let services = MiteSyncTypes.Services var retrievalPath = services.syncTypeDescription() if serviceID != nil { retrievalPath += "/" + String(serviceID!) + ".json" } else if archived == true { retrievalPath += "/archived.json" } else { retrievalPath += ".json" } if parameters.count != 0 { // var parametersArray = String[]() retrievalPath += "?" for (filterKey, filterValue) in parameters { retrievalPath += filterKey + "=" + filterValue + "&" } // NSArray.componentsJoinedByString not working! // retrievalPath += ".json?" + parametersArray.componentsJoinedByString("&") } miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func addService(#name: String!, note: String?, archived: Bool?, hourlyRate: Int?, billable: Bool?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>(); parameters["name"] = name if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) } if billable != nil { parameters["billable"] = String(billable!) } let finalParams: Dictionary<String, Dictionary<String, String>> = ["service": parameters] let services = MiteSyncTypes.Services let retrievalPath = services.syncTypeDescription() miteRetrieval( retrievalPath, method: "POST", parameters: finalParams, onSuccess, onFailure) } func editService(id: Int, name: String?, note: String?, archived: Bool?, hourlyRate: Int?, billable: Bool?, optionalParameters: Dictionary<String, String>?, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { var parameters = Dictionary<String, String>() if optionalParameters != nil { parameters = optionalParameters! } if name != nil { parameters["name"] = name! } if note != nil { parameters["note"] = note! } if archived != nil { parameters["archived"] = String(archived!) } if hourlyRate != nil { parameters["hourly_rate"] = String(hourlyRate!) } if billable != nil { parameters["billable"] = String(billable!) } let finalParams: Dictionary<String, Dictionary<String, String>> = ["service": parameters] let services = MiteSyncTypes.Services let retrievalPath = services.syncTypeDescription() miteRetrieval( retrievalPath, method: "PUT", parameters: finalParams, onSuccess, onFailure) } func deleteService(id: Int, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let services = MiteSyncTypes.Services let retrievalPath = services.syncTypeDescription() + "/" + String(id) + ".json" miteRetrieval(retrievalPath, method: "DELETE", parameters: nil, onSuccess, onFailure) } func account(#onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let account = MiteSyncTypes.Account let retrievalPath = account.syncTypeDescription() miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func myself(#onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { let myself = MiteSyncTypes.Myself let retrievalPath = myself.syncTypeDescription() miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } func users(#userID: Int?, userName: String?, userEmail: String?, limit: Int?, archived: Bool?, var parameters: Dictionary<String, String>, onSuccess: (result: AnyObject) -> (), onFailure: (error : NSError) -> ()) { if userID != nil { parameters["id"] = String(userID!) } if userName != nil { parameters["name"] = userName! } if userEmail != nil { parameters["email"] = userEmail! } if limit != nil { parameters["limit"] = String(limit!) } if archived != nil { parameters["archived"] = String(archived!) } let users = MiteSyncTypes.Users let retrievalPath = users.syncTypeDescription() miteRetrieval( retrievalPath, method: "GET", parameters: nil, onSuccess, onFailure) } }
51a9e260075631572cf9c6082c8cd2ad
33.048696
163
0.662478
false
false
false
false
Ahyufei/swift3-weibo
refs/heads/master
WeiBo/WeiBo/Classes/View(视图和控制器)/Main/WBBaseViewController.swift
apache-2.0
1
// // WBBaseViewController.swift // WeiBo // // Created by 豪康 on 2017/7/5. // Copyright © 2017年 ahyufei. All rights reserved. // import UIKit class WBBaseViewController: UIViewController { /// 访客视图信息字典 var visitorInfo: [String : String]? /// 用户登录标记 // var userLogon = false /// 表格视图 var tableView: UITableView? var refreshControl : UIRefreshControl? /// 上拉刷新标记 var isPullup = false override func viewDidLoad() { super.viewDidLoad() setupUI() // 判断是否需要加载数据,未登录不需要加载数据 if WBNetworkManager.shared.userLogon { loadData() } } func loadData() { refreshControl?.endRefreshing() } } // MARK:- 设置UI extension WBBaseViewController { fileprivate func setupUI() { view.backgroundColor = UIColor.white automaticallyAdjustsScrollViewInsets = false setupNavBar() WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView() // userLogon ? setupTableView() : setupVisitorView() } /// 登录后显示表格视图(子类重写此方法) func setupTableView() { tableView = UITableView(frame: view.bounds, style: .plain) view.addSubview(tableView!) tableView?.delegate = self; tableView?.dataSource = self; tableView?.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 49, right: 0) refreshControl = UIRefreshControl() tableView?.addSubview(refreshControl!) refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged) } /// 没登录显示访客视图 fileprivate func setupVisitorView() { let visitorView = WBVisitorView(frame: view.bounds) view.addSubview(visitorView) visitorView.visitorInfo = visitorInfo // 访客视图按钮监听 visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside) visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "注册", target: self, action: #selector(register)) navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "登录", target: self, action: #selector(login)) } fileprivate func setupNavBar() { // 设置navbar的渲染颜色 navigationController?.navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6) // 设置navBar的字体颜色 navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.darkGray] } } // MARK:- 访客视图监听方法 extension WBBaseViewController { @objc func register() { print("注册") } @objc func login() { // 发送通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil) } } extension WBBaseViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } /// 在显示最后一行时候,做上拉加载 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // 判断是否最后一行 let row = indexPath.row let section = tableView.numberOfSections - 1 // print("section - \(section)") if row < 0 || section < 0 { return } // 行数 let count = tableView.numberOfRows(inSection: section) // 如果是最后一行,同时没有上拉刷新 if row == (count - 1) && !isPullup { // print("上拉刷新") isPullup = true loadData() } } }
768738541d5033ca2a2b8330413cac2c
28.383459
120
0.62001
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/BusinessLayer/Core/Services/Mnemonic/Keys/HDPrivateKey.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation import CryptoSwift struct HDPrivateKey { let raw: Data let chainCode: Data private let depth: UInt8 private let fingerprint: UInt32 private let childIndex: UInt32 private let network: Chain init(seed: Data, network: Chain) { let output = CryptoHash.hmacsha512(seed, key: "Bitcoin seed".data(using: .ascii)!) self.raw = output[0..<32] self.chainCode = output[32..<64] self.depth = 0 self.fingerprint = 0 self.childIndex = 0 self.network = network } private init(hdPrivateKey: Data, chainCode: Data, depth: UInt8, fingerprint: UInt32, index: UInt32, network: Chain) { self.raw = hdPrivateKey self.chainCode = chainCode self.depth = depth self.fingerprint = fingerprint self.childIndex = index self.network = network } func privateKey() -> PrivateKey { return PrivateKey(raw: raw) } func hdPublicKey() -> HDPublicKey { return HDPublicKey(hdPrivateKey: self, chainCode: chainCode, network: network, depth: depth, fingerprint: fingerprint, childIndex: childIndex) } func extended() -> String { var extendedPrivateKeyData = Data() extendedPrivateKeyData += network.privateKeyPrefix.bigEndian extendedPrivateKeyData += depth.littleEndian extendedPrivateKeyData += fingerprint.littleEndian extendedPrivateKeyData += childIndex.littleEndian extendedPrivateKeyData += chainCode extendedPrivateKeyData += UInt8(0) extendedPrivateKeyData += raw let checksum = CryptoHash.sha256sha256(extendedPrivateKeyData).prefix(4) return Base58.encode(extendedPrivateKeyData + checksum) } func derived(at index: UInt32, hardens: Bool = false) throws -> HDPrivateKey { guard (0x80000000 & index) == 0 else { fatalError("Invalid index \(index)") } let keyDeriver = KeyDerivation( privateKey: raw, publicKey: hdPublicKey().raw, chainCode: chainCode, depth: depth, fingerprint: fingerprint, childIndex: childIndex ) guard let derivedKey = keyDeriver.derived(at: index, hardened: hardens) else { throw Errors.keyDerivateionFailed } return HDPrivateKey( hdPrivateKey: derivedKey.privateKey!, chainCode: derivedKey.chainCode, depth: derivedKey.depth, fingerprint: derivedKey.fingerprint, index: derivedKey.childIndex, network: network ) } enum Errors: Error { case keyDerivateionFailed } }
0df5edbdd5920d46bd99ace4a75f84be
28.413793
146
0.695584
false
false
false
false
IngmarStein/swift
refs/heads/master
test/DebugInfo/protocolarg.swift
apache-2.0
7
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} func use<T>(_ t: inout T) {} public protocol IGiveOutInts { func callMe() -> Int64 } // CHECK: define {{.*}}@_TF11protocolarg16printSomeNumbersFPS_12IGiveOutInts_T_ // CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_* % // CHECK-SAME: metadata ![[VAR:.*]], metadata ![[EMPTY:.*]]) // CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_** % // CHECK-SAME: metadata ![[ARG:.*]], metadata ![[DEREF:.*]]) // CHECK: ![[EMPTY]] = !DIExpression() public func printSomeNumbers(_ gen: IGiveOutInts) { var gen = gen // CHECK: ![[VAR]] = !DILocalVariable(name: "gen", {{.*}} line: [[@LINE-1]] // FIXME: Should be DW_TAG_interface_type // CHECK: ![[PT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts" // CHECK: ![[ARG]] = !DILocalVariable(name: "gen", arg: 1, // CHECK-SAME: line: [[@LINE-6]], type: ![[PT]] // CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref) markUsed(gen.callMe()) use(&gen) }
56a847a28be5da75923eb59171dd7dfc
37.068966
90
0.600543
false
false
false
false
fortmarek/Supl
refs/heads/master
Supl/NotificationViewController.swift
mit
1
// // NotificationViewController.swift // Supl // // Created by Marek Fořt on 14.02.16. // Copyright © 2016 Marek Fořt. All rights reserved. // import UIKit import Alamofire protocol NotificationsDelegate { } class NotificationViewController: UIViewController, NotificationsDelegate { @IBOutlet weak var notificationButton: UIButton! @IBOutlet weak var iconConstraint: NSLayoutConstraint! @IBOutlet weak var icon: UIImageView! override func viewDidLoad() { super.viewDidLoad() notificationButton.backgroundColor = UIColor.clear notificationButton.layer.cornerRadius = 25 notificationButton.layer.borderWidth = 1 notificationButton.layer.borderColor = UIColor.white.cgColor let difference = notificationButton.frame.origin.y + notificationButton.frame.height - view.frame.height if difference > -55 { iconConstraint.constant += -75 - difference } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func notificationButtonTapped(_ sender: UIButton) { self.registerForPushNotifications() } } extension NotificationsDelegate { func registerForPushNotifications() { UserDefaults.standard.set(true, forKey: "askedPermission") let application = UIApplication.shared if application.responds(to: #selector(UIApplication.registerUserNotificationSettings(_:))) { let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotifications() } } func postToken(_ token: String) { guard let userId = UserDefaults.standard.value(forKey: "userId") else {return} let _ = Alamofire.request("http://139.59.144.155/users/\(userId)/notification", method: .post, parameters: ["token" : token]) } func deleteToken() { guard let userId = UserDefaults.standard.value(forKey: "userId") else {return} let _ = Alamofire.request("http://139.59.144.155/users/\(userId)/notification", method: .delete) } }
8734b6fa12d179884c74f2830f7f35b7
32.082192
112
0.667495
false
false
false
false
byss/KBAPISupport
refs/heads/master
KBAPISupport/Core/Public/KBAPIFileUpload.swift
mit
1
// // KBAPIFileUpload.swift // Copyright © 2018 Kirill byss Bystrov. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Coding keys of an item that is encoded using `KBAPIMultipartFormDataEncoder`. /// /// - filename: Source file name of an item. /// - mimeType: MIME type of the encoded data. /// - contentStream: `InputStream` containing item data. /// - data: Raw data of an item. public enum KBAPIFormDataCodingKeys: String, CodingKey, CaseIterable { case filename; case mimeType; case contentStream; case data; } /// A type that is serializable using `KBAPIMultipartFormDataEncoder`. public protocol KBAPIFileUploadProtocol: Encodable { /// See `KBAPIFormDataCodingKeys`. typealias FormDataCodingKeys = KBAPIFormDataCodingKeys; /// Source file name of an item. var filename: String { get }; /// MIME type of the encoded data. var mimeType: String { get }; /// `InputStream` containing item data. var contentsStream: InputStream { get }; } /// A value representing in-memory data or a file to be uploaded. public struct KBAPIDataUpload { private typealias Metadata = KBAPIFileUploadMetadata; public let contentsStream: InputStream; private let metadata: Metadata; private init? (_ contentsStream: InputStream?, metadata: Metadata) { guard let contentsStream = contentsStream else { return nil; } self.init (contentsStream, metadata: metadata); } private init (_ contentsStream: InputStream, metadata: Metadata) { self.contentsStream = contentsStream; self.metadata = metadata; } } extension KBAPIDataUpload: Encodable { /// Fallback implementation for cases when `KBAPIDataUpload` is being used with a generic `Encoder`. public func encode (to encoder: Encoder) throws { var metaContainer = encoder.container (keyedBy: KBAPIFormDataCodingKeys.self); try metaContainer.encode (self.filename, forKey: .filename); try metaContainer.encode (self.mimeType, forKey: .mimeType); var dataContainer = metaContainer.nestedUnkeyedContainer (forKey: .data); try self.contentsStream.readAll { try dataContainer.encode (contentsOf: Data (bytesNoCopy: UnsafeMutableRawPointer (mutating: $0), count: $1, deallocator: .none)); } } } extension KBAPIDataUpload: KBAPIFileUploadProtocol { public var filename: String { return self.metadata.filename; } public var mimeType: String { return self.metadata.mimeType; } } public extension KBAPIDataUpload { /// Creates an new instance containing in-memory data for upload. /// /// - Parameter data: Raw item data to upload. public init (data: Data) { self.init (InputStream (data: data), metadata: Metadata ()); } /// Creates an new instance containing data at the given file URL. /// /// - Parameter fileURL: Source of item's data. public init? (fileURL: URL) { guard fileURL.isFileURL else { return nil; } self.init (InputStream (url: fileURL), metadata: Metadata (fileURL: fileURL)); } /// Creates an new instance containing in-memory data for upload under the given filename. /// /// - Parameters: /// - data: Raw item data to upload. /// - filename: File name associated with the item's data. public init (data: Data, filename: String) { self.init (InputStream (data: data), metadata: Metadata (filename: filename)); } /// Creates an new instance containing in-memory data for upload under the given filename with specified MIME type. /// /// - Parameters: /// - data: Raw item data to upload. /// - filename: File name associated with the item's data. /// - mimeType: MIME type of the encoded data. public init (data: Data, filename: String, mimeType: String) { self.init (InputStream (data: data), metadata: Metadata (filename: filename, mimeType: mimeType)); } } private struct KBAPIFileUploadMetadata { fileprivate let filename: String; fileprivate let mimeType: String; fileprivate init () { self.init (filename: ""); } fileprivate init (filename: String) { self.init (filename: filename.isEmpty ? "file.bin" : filename, mimeType: ""); } fileprivate init (filename: String, mimeType: String) { guard !filename.isEmpty else { self.init (filename: ""); return; } if (UTIdentifier.preferred (forTag: .mimeType, withValue: mimeType, conformingTo: .data) == nil) { let pathExtension = URL (fileURLWithPath: filename).pathExtension; if let mimeType = UTIdentifier.preferred (forTag: .filenameExtension, withValue: pathExtension, conformingTo: .data)?.preferredValue (ofTag: .mimeType) { self.init (unchecked: (filename, mimeType)); } else { self.init (unchecked: (filename, UTIdentifier.data.preferredValue (ofTag: .mimeType)!)); } } else { self.init (unchecked: (filename, mimeType)); } } fileprivate init (fileURL: URL) { let filename = fileURL.lastPathComponent; if let typeIdentifier = (try? fileURL.resourceValues (forKeys: [.typeIdentifierKey]))?.typeIdentifier.flatMap (UTIdentifier.init), typeIdentifier.conforms (to: .data), let mimeType = typeIdentifier.preferredValue (ofTag: .mimeType) { self.init (unchecked: (filename, mimeType)); } else { self.init (filename: filename); } } private init (unchecked: (filename: String, mimeType: String)) { self.filename = unchecked.filename; self.mimeType = unchecked.mimeType; } }
48a2cf3034e52e333ea9f4a041ba252c
34.438889
156
0.725976
false
false
false
false
thehung111/ViSearchSwiftSDK
refs/heads/develop
Carthage/Checkouts/visearch-sdk-swift/ViSearchSDK/ViSearchSDK/Classes/Request/ViMultipartFormData.swift
mit
4
// // ViMultipartFormData.swift // ViSearchSDK // // Created by Hung on 6/10/16. // Copyright © 2016 Hung. All rights reserved. // import Foundation /// used to encode image data in form upload open class ViMultipartFormData: NSObject { // MARK: - Helper Types and methods struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { case .initial: boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" case .encapsulated: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" case .final: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } /// Generate random boundary /// /// - returns: random boundary for use in form upload public static func randomBoundary() -> String { return String(format: "visearch.boundary.%08x%08x", arc4random(), arc4random()) } /// assumption: imageData is of the type jpeg after we compress the image /// encode image data for uploading, add content headers public static func encode(imageData: Data? , boundary: String) -> Data { var encoded = Data() if imageData != nil { let initialData = BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) encoded.append(initialData) let headers = contentHeaders(withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg") let headerData = encodeHeaders(headers: headers) encoded.append(headerData) encoded.append(imageData!) } let finalBoundaryData = BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) encoded.append(finalBoundaryData) return encoded } // MARK: - Private - Body Part Encoding private static func encodeHeaders(headers: [String: String]) -> Data { var headerText = "" for (key, value) in headers { headerText += "\(key): \(value)\(EncodingCharacters.crlf)" } headerText += EncodingCharacters.crlf return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } private static func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { var disposition = "form-data; name=\"\(name)\"" if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } var headers = ["Content-Disposition": disposition] if let mimeType = mimeType { headers["Content-Type"] = mimeType } return headers } }
0b4bbeabfb8b023cf0084c8c8fabe146
32.752577
133
0.596213
false
false
false
false
SheffieldKevin/SwiftSVG
refs/heads/develop
SwiftSVG Demo/AppDelegate.swift
bsd-2-clause
1
// // AppDelegate.swift // SwiftSVGTestNT // // Created by Jonathan Wight on 2/25/15. // Copyright (c) 2015 No. All rights reserved. // import Cocoa import SwiftSVG @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { /* let url = NSBundle.mainBundle().URLForResource("Ghostscript_Tiger", withExtension: "svg") // let url = NSBundle.mainBundle().URLForResource("Apple_Swift_Logo", withExtension: "svg") (NSDocumentController.sharedDocumentController() ).openDocumentWithContentsOfURL(url!, display: true) { (document: NSDocument?, flag: Bool, error: NSError?) in } */ } @IBAction func processFolder(sender: AnyObject?) { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.allowsMultipleSelection = false openPanel.title = "SVG Files" openPanel.prompt = "Select folder with SVG files" openPanel.beginWithCompletionHandler({ result in guard result == NSFileHandlingPanelOKButton else { return } let folderURL = openPanel.URLs[0] // Need to find any svg files in the folder. let fileManager = NSFileManager.defaultManager() let fileList = try? fileManager.contentsOfDirectoryAtURL(folderURL, includingPropertiesForKeys: nil, options: []) guard let files = fileList where files.count > 0 else { return } let svgFiles = files.filter() { fileURL in return fileURL.lastPathComponent!.hasSuffix(".svg") } guard svgFiles.count > 0 else { return } // OK we have more than one file, lets put up the dialog to ask where do we want to save the results let savePanel = NSOpenPanel() savePanel.canChooseDirectories = true savePanel.canChooseFiles = false savePanel.canCreateDirectories = true savePanel.allowsMultipleSelection = false savePanel.title = "MovingImages drawing files" savePanel.prompt = "Save folder for MovingImages" savePanel.beginWithCompletionHandler({ result in guard result == NSFileHandlingPanelOKButton else { return } let destFolder = savePanel.URLs[0] dispatch_apply(svgFiles.count, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { index in let svgFileURL = svgFiles[index] let svgFileName = svgFileURL.lastPathComponent! let movingImagesFile = svgFileName.stringByReplacingOccurrencesOfString(".svg", withString: ".json") let newFileURL = destFolder.URLByAppendingPathComponent(movingImagesFile) var encoding = NSStringEncoding() guard let source = try? String(contentsOfURL: svgFileURL, usedEncoding: &encoding) else { return } guard let xmlDocument = try? NSXMLDocument(XMLString: source, options: 0) else { return } let processor = SVGProcessor() guard let tempDocument = try? processor.processXMLDocument(xmlDocument) else { return } guard let svgDocument = tempDocument else { return } let renderer = MovingImagesRenderer() let svgRenderer = SVGRenderer() let _ = try? svgRenderer.renderDocument(svgDocument, renderer: renderer) let jsonObject = renderer.generateJSONDict() writeMovingImagesJSONObject(jsonObject, fileURL: newFileURL) }) }) }) } }
fa47d4ab3c398f6d3f495263f22f9d8b
40.057692
120
0.561124
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
test/ClangModules/optional.swift
apache-2.0
3
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3foofT_GSqSS_ : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: [[T0:%.*]] = function_ref @_TFC8optional1A3foofT_GSqSS_ // CHECK-NEXT: [[T1:%.*]] = apply [[T0]](%0) // CHECK-NEXT: strong_release // CHECK: [[T2:%.*]] = select_enum [[T1]] // CHECK-NEXT: cond_br [[T2]] // Something branch: project value, translate, inject into result. // CHECK: [[STR:%.*]] = unchecked_enum_data [[T1]] // CHECK: [[T0:%.*]] = function_ref @swift_StringToNSString // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[STR]]) // CHECK-NEXT: enum $Optional<NSString>, #Optional.Some!enumelt.1, [[T1]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<NSString>, #Optional.None!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3barfT1xGSqSS__T_ : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: [[T1:%.*]] = select_enum %0 // CHECK-NEXT: cond_br [[T1]] // Something branch: project value, translate, inject into result. // CHECK: [[NSSTR:%.*]] = unchecked_enum_data %0 // CHECK: [[T0:%.*]] = function_ref @swift_NSStringToString // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.Some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]]) // CHECK-NEXT: enum $Optional<String>, #Optional.Some!enumelt.1, [[T1]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<String>, #Optional.None!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<String>): // CHECK: [[T1:%.*]] = function_ref @_TFC8optional1A3barfT1xGSqSS__T_ // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], %1) // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
d1793a3edba01b924af298a108a195f6
40.295082
137
0.626042
false
false
false
false
chenkaige/EasyIOS-Swift
refs/heads/master
Pod/Classes/Easy/Lib/EZExtend+Bond.swift
mit
1
// // EZBond.swift // medical // // Created by zhuchao on 15/4/27. // Copyright (c) 2015年 zhuchao. All rights reserved. // import Bond import TTTAttributedLabel @objc class TapGestureDynamicHelper:NSObject { weak var view: UIView? let sink: (UITapGestureRecognizer) -> Void init(view: UIView,number:NSInteger,sink:((UITapGestureRecognizer) -> Void)) { self.view = view self.sink = sink super.init() view.addTapGesture(number, target: self, action: Selector("tapHandle:")) } func tapHandle(gesture: UITapGestureRecognizer) { sink(gesture) } } @objc class PanGestureDynamicHelper:NSObject{ weak var view: UIView? let sink: (UIPanGestureRecognizer) -> Void init(view: UIView,number:NSInteger,sink:((UIPanGestureRecognizer) -> Void)) { self.view = view self.sink = sink super.init() view.addPanGesture(self, action: Selector("panHandle:")) } func panHandle(gestureRecognizer:UIPanGestureRecognizer) { sink(gestureRecognizer) } } @objc class SwipeGestureDynamicHelper:NSObject { weak var view: UIView? let sink: ((UISwipeGestureRecognizer) -> Void) var number:NSInteger = 1 init(view: UIView,number:NSInteger,sink:((UISwipeGestureRecognizer) -> Void)) { self.view = view self.number = number self.sink = sink super.init() view.addSwipeGesture(UISwipeGestureRecognizerDirection.Right, numberOfTouches: number, target: self, action: Selector("swipeRightHandle:")) view.addSwipeGesture(UISwipeGestureRecognizerDirection.Up, numberOfTouches: number, target: self, action: Selector("swipeUpHandle:")) view.addSwipeGesture(UISwipeGestureRecognizerDirection.Down, numberOfTouches: number, target: self, action: Selector("swipeDownHandle:")) view.addSwipeGesture(UISwipeGestureRecognizerDirection.Left, numberOfTouches: number, target: self, action: Selector("swipeLeftHandle:")) } func swipeRightHandle(gestureRecognizer:UISwipeGestureRecognizer) { sink(gestureRecognizer) } func swipeUpHandle(gestureRecognizer:UISwipeGestureRecognizer) { sink(gestureRecognizer) } func swipeDownHandle(gestureRecognizer:UISwipeGestureRecognizer) { sink(gestureRecognizer) } func swipeLeftHandle(gestureRecognizer:UISwipeGestureRecognizer) { sink(gestureRecognizer) } } extension UIView{ private struct AssociatedKeys { static var PanGestureEventKey = "bnd_PanGestureEventKey" static var PanGestureEventHelperKey = "bnd_PanGestureEventHelperKey" static var SwipeGestureEventKey = "bnd_SwipeGestureEventKey" static var SwipeGestureEventHelperKey = "bnd_SwipeGestureEventHelperKey" static var TapGestureEventKey = "bnd_TapGestureEventKey" static var TapGestureEventHelperKey = "bnd_TapGestureEventHelperKey" } public func bnd_swipeGestureEvent(number:NSInteger) ->EventProducer<UISwipeGestureRecognizer> { if let bnd_swipeGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.SwipeGestureEventKey) { return bnd_swipeGestureEvent as! EventProducer<UISwipeGestureRecognizer> } else { var capturedSink: (UISwipeGestureRecognizer -> ())! = nil let bnd_swipeGestureEvent = EventProducer<UISwipeGestureRecognizer> { sink in capturedSink = sink return nil } let controlHelper = SwipeGestureDynamicHelper(view: self, number: number, sink: capturedSink) objc_setAssociatedObject(self, &AssociatedKeys.SwipeGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.SwipeGestureEventKey, bnd_swipeGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return bnd_swipeGestureEvent } } public func bnd_tapGestureEvent(number:NSInteger) ->EventProducer<UITapGestureRecognizer> { if let bnd_tapGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.TapGestureEventKey) { return bnd_tapGestureEvent as! EventProducer<UITapGestureRecognizer> } else { var capturedSink: (UITapGestureRecognizer -> ())! = nil let bnd_tapGestureEvent = EventProducer<UITapGestureRecognizer> { sink in capturedSink = sink return nil } let controlHelper = TapGestureDynamicHelper(view: self, number: number, sink: capturedSink) objc_setAssociatedObject(self, &AssociatedKeys.TapGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.TapGestureEventKey, bnd_tapGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return bnd_tapGestureEvent } } public var bnd_panGestureEvent:EventProducer<UIPanGestureRecognizer> { if let bnd_panGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.PanGestureEventKey) { return bnd_panGestureEvent as! EventProducer<UIPanGestureRecognizer> } else { var capturedSink: (UIPanGestureRecognizer -> ())! = nil let bnd_panGestureEvent = EventProducer<UIPanGestureRecognizer> { sink in capturedSink = sink return nil } let controlHelper = PanGestureDynamicHelper(view: self, number: 1, sink: capturedSink) objc_setAssociatedObject(self, &AssociatedKeys.PanGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &AssociatedKeys.PanGestureEventKey, bnd_panGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return bnd_panGestureEvent } } } extension UIImageView { private struct AssociatedKeys { static var UrlImageDynamicHandleUIImageView = "UrlImageDynamicHandleUIImageView" } public var bnd_URLImage: Observable<NSURL?> { if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.UrlImageDynamicHandleUIImageView) { return (d as? Observable<NSURL?>)! } else { let d = Observable<NSURL?>(NSURL()) d.observe { [weak self] v in if let s = self { if v != nil { s.kf_setImageWithURL(v!) } } } objc_setAssociatedObject(self, &AssociatedKeys.UrlImageDynamicHandleUIImageView, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } } extension TTTAttributedLabel { private struct AssociatedKeys { static var textDynamicHandleTTTAttributeLabel = "textDynamicHandleTTTAttributeLabel" static var attributedTextDynamicHandleTTTAttributeLabel = "attributedTextDynamicHandleTTTAttributeLabel" static var dataDynamicHandleTTTAttributeLabel = "dataDynamicHandleTTTAttributeLabel" } public var dynTTText: Observable<String> { if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.textDynamicHandleTTTAttributeLabel) { return (d as? Observable<String>)! } else { let d = Observable<String>(self.text ?? "") d.observe { [weak self] v in if let s = self { s.setText(v) } } objc_setAssociatedObject(self, &AssociatedKeys.textDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var dynTTTData: Observable<NSData> { if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.dataDynamicHandleTTTAttributeLabel) { return (d as? Observable<NSData>)! } else { let d = Observable<NSData>(NSData()) d.observe{ [weak self] v in if let s = self { s.setText(NSAttributedString(fromHTMLData: v, attributes: ["dict":s.tagProperty.style])) }} objc_setAssociatedObject(self, &AssociatedKeys.dataDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } public var dynTTTAttributedText: Observable<NSAttributedString> { if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.attributedTextDynamicHandleTTTAttributeLabel) { return (d as? Observable<NSAttributedString>)! } else { let d = Observable<NSAttributedString>(self.attributedText ?? NSAttributedString(string: "")) d.observe { [weak self] v in if let s = self { s.setText(v) } } objc_setAssociatedObject(self, &AssociatedKeys.attributedTextDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return d } } }
28f217a34dd7bfef93677fb3ec926245
44.283582
165
0.686662
false
false
false
false
e78l/swift-corelibs-foundation
refs/heads/master
TestFoundation/TestNSNumber.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // class TestNSNumber : XCTestCase { static var allTests: [(String, (TestNSNumber) -> () throws -> Void)] { return [ ("test_NumberWithBool", test_NumberWithBool ), ("test_CFBoolean", test_CFBoolean ), ("test_numberWithChar", test_numberWithChar ), ("test_numberWithUnsignedChar", test_numberWithUnsignedChar ), ("test_numberWithShort", test_numberWithShort ), ("test_numberWithUnsignedShort", test_numberWithUnsignedShort ), ("test_numberWithLong", test_numberWithLong ), ("test_numberWithUnsignedLong", test_numberWithUnsignedLong ), ("test_numberWithLongLong", test_numberWithLongLong ), ("test_numberWithUnsignedLongLong", test_numberWithUnsignedLongLong ), ("test_numberWithInt", test_numberWithInt ), ("test_numberWithUInt", test_numberWithUInt ), ("test_numberWithFloat", test_numberWithFloat ), ("test_numberWithDouble", test_numberWithDouble ), ("test_compareNumberWithBool", test_compareNumberWithBool ), ("test_compareNumberWithChar", test_compareNumberWithChar ), ("test_compareNumberWithUnsignedChar", test_compareNumberWithUnsignedChar ), ("test_compareNumberWithShort", test_compareNumberWithShort ), ("test_compareNumberWithFloat", test_compareNumberWithFloat ), ("test_compareNumberWithDouble", test_compareNumberWithDouble ), ("test_description", test_description ), ("test_descriptionWithLocale", test_descriptionWithLocale ), ("test_objCType", test_objCType ), ("test_stringValue", test_stringValue), ("test_Equals", test_Equals), ("test_boolValue", test_boolValue), ("test_hash", test_hash), ] } func test_NumberWithBool() { XCTAssertEqual(NSNumber(value: true).boolValue, true) XCTAssertEqual(NSNumber(value: true).int8Value, Int8(1)) XCTAssertEqual(NSNumber(value: true).uint8Value, UInt8(1)) XCTAssertEqual(NSNumber(value: true).int16Value, Int16(1)) XCTAssertEqual(NSNumber(value: true).uint16Value, UInt16(1)) XCTAssertEqual(NSNumber(value: true).int32Value, Int32(1)) XCTAssertEqual(NSNumber(value: true).uint32Value, UInt32(1)) XCTAssertEqual(NSNumber(value: true).int64Value, Int64(1)) XCTAssertEqual(NSNumber(value: true).uint64Value, UInt64(1)) XCTAssertEqual(NSNumber(value: true).floatValue, Float(1)) XCTAssertEqual(NSNumber(value: true).doubleValue, Double(1)) XCTAssertEqual(NSNumber(value: false).boolValue, false) XCTAssertEqual(NSNumber(value: false).int8Value, Int8(0)) XCTAssertEqual(NSNumber(value: false).uint8Value, UInt8(0)) XCTAssertEqual(NSNumber(value: false).int16Value, Int16(0)) XCTAssertEqual(NSNumber(value: false).uint16Value, UInt16(0)) XCTAssertEqual(NSNumber(value: false).int32Value, Int32(0)) XCTAssertEqual(NSNumber(value: false).uint32Value, UInt32(0)) XCTAssertEqual(NSNumber(value: false).int64Value, Int64(0)) XCTAssertEqual(NSNumber(value: false).uint64Value, UInt64(0)) XCTAssertEqual(NSNumber(value: false).floatValue, Float(0)) XCTAssertEqual(NSNumber(value: false).doubleValue, Double(0)) } func test_CFBoolean() { guard let plist = try? PropertyListSerialization.data(fromPropertyList: ["test" : true], format: .binary, options: 0) else { XCTFail() return } guard let obj = (try? PropertyListSerialization.propertyList(from: plist, format: nil)) as? [String : Any] else { XCTFail() return } guard let value = obj["test"] else { XCTFail() return } guard let boolValue = value as? Bool else { XCTFail("Expected de-serialization as round-trip boolean value") return } XCTAssertTrue(boolValue) } func test_numberWithChar() { XCTAssertEqual(NSNumber(value: Int8(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int8(0)).int8Value, Int8(0)) XCTAssertEqual(NSNumber(value: Int8(0)).uint8Value, UInt8(0)) XCTAssertEqual(NSNumber(value: Int8(0)).int16Value, Int16(0)) XCTAssertEqual(NSNumber(value: Int8(0)).uint16Value, UInt16(0)) XCTAssertEqual(NSNumber(value: Int8(0)).int32Value, Int32(0)) XCTAssertEqual(NSNumber(value: Int8(0)).uint32Value, UInt32(0)) XCTAssertEqual(NSNumber(value: Int8(0)).int64Value, Int64(0)) XCTAssertEqual(NSNumber(value: Int8(0)).uint64Value, UInt64(0)) XCTAssertEqual(NSNumber(value: Int8(-37)).boolValue, true) XCTAssertEqual(NSNumber(value: Int8(-37)).int8Value, Int8(-37)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).int16Value, Int16(-37)) XCTAssertEqual(NSNumber(value: Int8(-37)).int32Value, Int32(-37)) XCTAssertEqual(NSNumber(value: Int8(-37)).int64Value, Int64(-37)) #endif XCTAssertEqual(NSNumber(value: Int8(42)).boolValue, true) XCTAssertEqual(NSNumber(value: Int8(42)).int8Value, Int8(42)) XCTAssertEqual(NSNumber(value: Int8(42)).uint8Value, UInt8(42)) XCTAssertEqual(NSNumber(value: Int8(42)).int16Value, Int16(42)) XCTAssertEqual(NSNumber(value: Int8(42)).uint16Value, UInt16(42)) XCTAssertEqual(NSNumber(value: Int8(42)).int32Value, Int32(42)) XCTAssertEqual(NSNumber(value: Int8(42)).uint32Value, UInt32(42)) XCTAssertEqual(NSNumber(value: Int8(42)).int64Value, Int64(42)) XCTAssertEqual(NSNumber(value: Int8(42)).uint64Value, UInt64(42)) XCTAssertEqual(NSNumber(value: Int8.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int8.max).int8Value, Int8(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).uint8Value, UInt8(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).int16Value, Int16(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).uint16Value, UInt16(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).int32Value, Int32(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).uint32Value, UInt32(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).int64Value, Int64(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.max).uint64Value, UInt64(Int8.max)) XCTAssertEqual(NSNumber(value: Int8.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int8.min).int8Value, Int8(Int8.min)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8.min).int16Value, Int16(Int8.min)) XCTAssertEqual(NSNumber(value: Int8.min).int32Value, Int32(Int8.min)) XCTAssertEqual(NSNumber(value: Int8.min).int64Value, Int64(Int8.min)) #endif XCTAssertEqual(NSNumber(value: Int8(0)).floatValue, Float(0)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).floatValue, Float(-37)) #endif XCTAssertEqual(NSNumber(value: Int8(42)).floatValue, Float(42)) XCTAssertEqual(NSNumber(value: Int8.max).floatValue, Float(Int8.max)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8.min).floatValue, Float(Int8.min)) #endif XCTAssertEqual(NSNumber(value: Int8(0)).doubleValue, Double(0)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).doubleValue, Double(-37)) #endif XCTAssertEqual(NSNumber(value: Int8(42)).doubleValue, Double(42)) XCTAssertEqual(NSNumber(value: Int8.max).doubleValue, Double(Int8.max)) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8.min).doubleValue, Double(Int8.min)) #endif } func test_numberWithUnsignedChar() { XCTAssertEqual(NSNumber(value: UInt8(42)).boolValue, true) XCTAssertEqual(NSNumber(value: UInt8(42)).int8Value, Int8(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).uint8Value, UInt8(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).int16Value, Int16(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).uint16Value, UInt16(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).int32Value, Int32(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).uint32Value, UInt32(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).int64Value, Int64(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).uint64Value, UInt64(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).floatValue, Float(42)) XCTAssertEqual(NSNumber(value: UInt8(42)).doubleValue, Double(42)) XCTAssertEqual(NSNumber(value: UInt8.min).boolValue, false) XCTAssertEqual(NSNumber(value: UInt8.min).int8Value, Int8(UInt8.min)) XCTAssertEqual(NSNumber(value: UInt8.min).int16Value, Int16(UInt8.min)) XCTAssertEqual(NSNumber(value: UInt8.min).int32Value, Int32(UInt8.min)) XCTAssertEqual(NSNumber(value: UInt8.min).int64Value, Int64(UInt8.min)) XCTAssertEqual(NSNumber(value: UInt8.min).floatValue, Float(UInt8.min)) XCTAssertEqual(NSNumber(value: UInt8.min).doubleValue, Double(UInt8.min)) //-------- XCTAssertEqual(NSNumber(value: UInt8(0)).boolValue, false) XCTAssertEqual(NSNumber(value: UInt8(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).intValue, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: UInt8(0)).doubleValue, 0) //------ XCTAssertEqual(NSNumber(value: UInt8.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt8.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt8.max).int16Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).int32Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).int64Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).uint16Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).uint32Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).uint64Value, 255) XCTAssertEqual(NSNumber(value: UInt8.max).intValue, 255) XCTAssertEqual(NSNumber(value: UInt8.max).uintValue, 255) XCTAssertEqual(NSNumber(value: UInt8.max).floatValue, Float(UInt8.max)) XCTAssertEqual(NSNumber(value: UInt8.max).doubleValue, Double(UInt8.max)) } func test_numberWithShort() { XCTAssertEqual(NSNumber(value: Int16(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int16(0)).int8Value, Int8(0)) XCTAssertEqual(NSNumber(value: Int16(0)).uint8Value, UInt8(0)) XCTAssertEqual(NSNumber(value: Int16(0)).int16Value, Int16(0)) XCTAssertEqual(NSNumber(value: Int16(0)).uint16Value, UInt16(0)) XCTAssertEqual(NSNumber(value: Int16(0)).int32Value, Int32(0)) XCTAssertEqual(NSNumber(value: Int16(0)).uint32Value, UInt32(0)) XCTAssertEqual(NSNumber(value: Int16(0)).int64Value, Int64(0)) XCTAssertEqual(NSNumber(value: Int16(0)).uint64Value, UInt64(0)) XCTAssertEqual(NSNumber(value: Int16(-37)).boolValue, true) XCTAssertEqual(NSNumber(value: Int16(-37)).int8Value, Int8(-37)) XCTAssertEqual(NSNumber(value: Int16(-37)).int16Value, Int16(-37)) XCTAssertEqual(NSNumber(value: Int16(-37)).int32Value, Int32(-37)) XCTAssertEqual(NSNumber(value: Int16(-37)).int64Value, Int64(-37)) XCTAssertEqual(NSNumber(value: Int16(42)).boolValue, true) XCTAssertEqual(NSNumber(value: Int16(42)).int8Value, Int8(42)) XCTAssertEqual(NSNumber(value: Int16(42)).uint8Value, UInt8(42)) XCTAssertEqual(NSNumber(value: Int16(42)).int16Value, Int16(42)) XCTAssertEqual(NSNumber(value: Int16(42)).uint16Value, UInt16(42)) XCTAssertEqual(NSNumber(value: Int16(42)).int32Value, Int32(42)) XCTAssertEqual(NSNumber(value: Int16(42)).uint32Value, UInt32(42)) XCTAssertEqual(NSNumber(value: Int16(42)).int64Value, Int64(42)) XCTAssertEqual(NSNumber(value: Int16(42)).uint64Value, UInt64(42)) XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int16(0)).floatValue, Float(0)) XCTAssertEqual(NSNumber(value: Int16(-37)).floatValue, Float(-37)) XCTAssertEqual(NSNumber(value: Int16(42)).floatValue, Float(42)) XCTAssertEqual(NSNumber(value: Int16(0)).doubleValue, Double(0)) XCTAssertEqual(NSNumber(value: Int16(-37)).doubleValue, Double(-37)) XCTAssertEqual(NSNumber(value: Int16(42)).doubleValue, Double(42)) //------ XCTAssertEqual(NSNumber(value: Int16(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int16(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: Int16(0)).intValue, 0) XCTAssertEqual(NSNumber(value: Int16(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: Int16(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: Int16(0)).doubleValue, 0) //------ XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.min).int8Value, 0) XCTAssertEqual(NSNumber(value: Int16.min).int16Value, -32768) XCTAssertEqual(NSNumber(value: Int16.min).int32Value, -32768) XCTAssertEqual(NSNumber(value: Int16.min).int64Value, -32768) XCTAssertEqual(NSNumber(value: Int16.min).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int16.min).uint16Value, 32768) XCTAssertEqual(NSNumber(value: Int16.min).uint32Value, 4294934528) XCTAssertEqual(NSNumber(value: Int16.min).uint64Value, 18446744073709518848) XCTAssertEqual(NSNumber(value: Int16.min).intValue, -32768) let uintSize = MemoryLayout<UInt>.size switch uintSize { case 4: XCTAssertEqual(NSNumber(value: Int16.min).uintValue, 4294934528) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int16.min).uintValue, 18446744073709518848) #endif default: XCTFail("Unexpected UInt size: \(uintSize)") } XCTAssertEqual(NSNumber(value: Int16.min).floatValue, Float(Int16.min)) XCTAssertEqual(NSNumber(value: Int16.min).doubleValue, Double(Int16.min)) //------ XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.max).int8Value, -1) XCTAssertEqual(NSNumber(value: Int16.max).int16Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).int32Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).int64Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: Int16.max).uint16Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).uint32Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).uint64Value, 32767) XCTAssertEqual(NSNumber(value: Int16.max).intValue, 32767) XCTAssertEqual(NSNumber(value: Int16.max).uintValue, 32767) XCTAssertEqual(NSNumber(value: Int16.max).floatValue, Float(Int16.max)) XCTAssertEqual(NSNumber(value: Int16.max).doubleValue, Double(Int16.max)) } func test_numberWithUnsignedShort() { XCTAssertEqual(NSNumber(value: UInt16(0)).boolValue, false) XCTAssertEqual(NSNumber(value: UInt16(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).intValue, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: UInt16(0)).floatValue, 0.0) XCTAssertEqual(NSNumber(value: UInt16(0)).doubleValue, 0.0) //------ XCTAssertEqual(NSNumber(value: UInt16.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt16.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt16.max).int16Value, -1) XCTAssertEqual(NSNumber(value: UInt16.max).int32Value, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).int64Value, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt16.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).uint32Value, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).uint64Value, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).intValue, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).uintValue, 65535) XCTAssertEqual(NSNumber(value: UInt16.max).floatValue, Float(UInt16.max)) XCTAssertEqual(NSNumber(value: UInt16.max).doubleValue, Double(UInt16.max)) } func test_numberWithLong() { XCTAssertEqual(NSNumber(value: Int32(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int32(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: Int32(0)).intValue, 0) XCTAssertEqual(NSNumber(value: Int32(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: Int32(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: Int32(0)).doubleValue, 0) //------ XCTAssertEqual(NSNumber(value: Int32.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.min).int8Value, 0) XCTAssertEqual(NSNumber(value: Int32.min).int16Value, 0) XCTAssertEqual(NSNumber(value: Int32.min).int32Value, -2147483648) XCTAssertEqual(NSNumber(value: Int32.min).int64Value, -2147483648) XCTAssertEqual(NSNumber(value: Int32.min).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int32.min).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int32.min).uint32Value, 2147483648) XCTAssertEqual(NSNumber(value: Int32.min).uint64Value, 18446744071562067968) XCTAssertEqual(NSNumber(value: Int32.min).intValue, -2147483648) let uintSize = MemoryLayout<UInt>.size switch uintSize { case 4: XCTAssertEqual(NSNumber(value: Int32.min).uintValue, 2147483648) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int32.min).uintValue, 18446744071562067968) #endif default: XCTFail("Unexpected UInt size: \(uintSize)") } XCTAssertEqual(NSNumber(value: Int32.min).floatValue, Float(Int32.min)) XCTAssertEqual(NSNumber(value: Int32.min).doubleValue, Double(Int32.min)) //------ XCTAssertEqual(NSNumber(value: Int32.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.max).int8Value, -1) XCTAssertEqual(NSNumber(value: Int32.max).int16Value, -1) XCTAssertEqual(NSNumber(value: Int32.max).int32Value, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).int64Value, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: Int32.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: Int32.max).uint32Value, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).uint64Value, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).intValue, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).uintValue, 2147483647) XCTAssertEqual(NSNumber(value: Int32.max).floatValue, Float(Int32.max)) XCTAssertEqual(NSNumber(value: Int32.max).doubleValue, Double(Int32.max)) } func test_numberWithUnsignedLong() { XCTAssertEqual(NSNumber(value: UInt32(0)).boolValue, false) XCTAssertEqual(NSNumber(value: UInt32(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).intValue, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: UInt32(0)).floatValue, 0.0) XCTAssertEqual(NSNumber(value: UInt32(0)).doubleValue, 0.0) //------ XCTAssertEqual(NSNumber(value: UInt32.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt32.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt32.max).int16Value, -1) XCTAssertEqual(NSNumber(value: UInt32.max).int32Value, -1) XCTAssertEqual(NSNumber(value: UInt32.max).int64Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt32.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt32.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: UInt32.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt32.max).uint64Value, 4294967295) let intSize = MemoryLayout<Int>.size switch intSize { case 4: XCTAssertEqual(NSNumber(value: UInt32.max).intValue, -1) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: UInt32.max).intValue, 4294967295) #endif default: XCTFail("Unexpected Int size: \(intSize)") } XCTAssertEqual(NSNumber(value: UInt32.max).uintValue, 4294967295) XCTAssertEqual(NSNumber(value: UInt32.max).floatValue, Float(UInt32.max)) XCTAssertEqual(NSNumber(value: UInt32.max).doubleValue, Double(UInt32.max)) } func test_numberWithLongLong() { XCTAssertEqual(NSNumber(value: Int64(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int64(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: Int64(0)).intValue, 0) XCTAssertEqual(NSNumber(value: Int64(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: Int64(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: Int64(0)).doubleValue, 0) //------ XCTAssertEqual(NSNumber(value: Int64.min).boolValue, false) XCTAssertEqual(NSNumber(value: Int64.min).int8Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).int16Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).int32Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).int64Value, -9223372036854775808) XCTAssertEqual(NSNumber(value: Int64.min).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int64.min).uint64Value, 9223372036854775808) let intSize = MemoryLayout<Int>.size switch intSize { case 4: XCTAssertEqual(NSNumber(value: Int64.min).intValue, 0) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int64.min).intValue, -9223372036854775808) #endif default: XCTFail("Unexpected Int size: \(intSize)") } let uintSize = MemoryLayout<UInt>.size switch uintSize { case 4: XCTAssertEqual(NSNumber(value: Int64.min).uintValue, 0) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int64.min).uintValue, 9223372036854775808) #endif default: XCTFail("Unexpected UInt size: \(uintSize)") } XCTAssertEqual(NSNumber(value: Int64.min).floatValue, Float(Int64.min)) XCTAssertEqual(NSNumber(value: Int64.min).doubleValue, Double(Int64.min)) //------ XCTAssertEqual(NSNumber(value: Int64.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int64.max).int8Value, -1) XCTAssertEqual(NSNumber(value: Int64.max).int16Value, -1) XCTAssertEqual(NSNumber(value: Int64.max).int32Value, -1) XCTAssertEqual(NSNumber(value: Int64.max).int64Value, 9223372036854775807) XCTAssertEqual(NSNumber(value: Int64.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: Int64.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: Int64.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: Int64.max).uint64Value, 9223372036854775807) switch intSize { case 4: XCTAssertEqual(NSNumber(value: Int64.max).intValue, -1) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int64.max).intValue, 9223372036854775807) #endif default: XCTFail("Unexpected Int size: \(intSize)") } switch uintSize { case 4: XCTAssertEqual(NSNumber(value: Int64.max).uintValue, 4294967295) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int64.max).uintValue, 9223372036854775807) #endif default: XCTFail("Unexpected UInt size: \(uintSize)") } XCTAssertEqual(NSNumber(value: Int64.max).floatValue, Float(Int64.max)) XCTAssertEqual(NSNumber(value: Int64.max).doubleValue, Double(Int64.max)) } func test_numberWithUnsignedLongLong() { XCTAssertEqual(NSNumber(value: UInt64(0)).boolValue, false) XCTAssertEqual(NSNumber(value: UInt64(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).intValue, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: UInt64(0)).floatValue, 0.0) XCTAssertEqual(NSNumber(value: UInt64(0)).doubleValue, 0.0) //------ XCTAssertEqual(NSNumber(value: UInt64.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt64.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt64.max).int16Value, -1) XCTAssertEqual(NSNumber(value: UInt64.max).int32Value, -1) XCTAssertEqual(NSNumber(value: UInt64.max).int64Value, -1) XCTAssertEqual(NSNumber(value: UInt64.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt64.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: UInt64.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt64.max).uint64Value, 18446744073709551615) XCTAssertEqual(NSNumber(value: UInt64.max).intValue, -1) let uintSize = MemoryLayout<UInt>.size switch uintSize { case 4: XCTAssertEqual(NSNumber(value: UInt64.max).uintValue, 4294967295) case 8: #if arch(arm) break #else XCTAssertEqual(NSNumber(value: UInt64.max).uintValue, 18446744073709551615) #endif default: XCTFail("Unexpected UInt size: \(uintSize)") } XCTAssertEqual(NSNumber(value: UInt64.max).floatValue, Float(UInt64.max)) XCTAssertEqual(NSNumber(value: UInt64.max).doubleValue, Double(UInt64.max)) } func test_numberWithInt() { XCTAssertEqual(NSNumber(value: Int(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Int(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: Int(0)).intValue, 0) XCTAssertEqual(NSNumber(value: Int(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: Int(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: Int(0)).doubleValue, 0) //------ let intSize = MemoryLayout<Int>.size let uintSize = MemoryLayout<UInt>.size switch (intSize, uintSize) { case (4, 4): XCTAssertEqual(NSNumber(value: Int.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int.min).int8Value, 0) XCTAssertEqual(NSNumber(value: Int.min).int16Value, 0) XCTAssertEqual(NSNumber(value: Int.min).int32Value, -2147483648) XCTAssertEqual(NSNumber(value: Int.min).int64Value, -2147483648) XCTAssertEqual(NSNumber(value: Int.min).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int.min).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int.min).uint32Value, 2147483648) XCTAssertEqual(NSNumber(value: Int.min).uint64Value, 18446744071562067968) XCTAssertEqual(NSNumber(value: Int.min).intValue, -2147483648) #if !arch(arm) XCTAssertEqual(NSNumber(value: Int.min).uintValue, 18446744071562067968) #endif XCTAssertEqual(NSNumber(value: Int.min).floatValue, Float(Int.min)) XCTAssertEqual(NSNumber(value: Int.min).doubleValue, Double(Int.min)) //-------- XCTAssertEqual(NSNumber(value: Int.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int.max).int8Value, -1) XCTAssertEqual(NSNumber(value: Int.max).int16Value, -1) XCTAssertEqual(NSNumber(value: Int.max).int32Value, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).int64Value, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: Int.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: Int.max).uint32Value, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).uint64Value, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).intValue, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).uintValue, 2147483647) XCTAssertEqual(NSNumber(value: Int.max).floatValue, Float(Int.max)) XCTAssertEqual(NSNumber(value: Int.max).doubleValue, Double(Int.max)) case (8, 8): #if arch(arm) break #else XCTAssertEqual(NSNumber(value: Int.min).boolValue, false) XCTAssertEqual(NSNumber(value: Int.min).int8Value, 0) XCTAssertEqual(NSNumber(value: Int.min).int16Value, 0) XCTAssertEqual(NSNumber(value: Int.min).int32Value, 0) XCTAssertEqual(NSNumber(value: Int.min).int64Value, -9223372036854775808) XCTAssertEqual(NSNumber(value: Int.min).uint8Value, 0) XCTAssertEqual(NSNumber(value: Int.min).uint16Value, 0) XCTAssertEqual(NSNumber(value: Int.min).uint32Value, 0) XCTAssertEqual(NSNumber(value: Int.min).uint64Value, 9223372036854775808) XCTAssertEqual(NSNumber(value: Int.min).intValue, -9223372036854775808) XCTAssertEqual(NSNumber(value: Int.min).uintValue, 9223372036854775808) XCTAssertEqual(NSNumber(value: Int.min).floatValue, Float(Int.min)) XCTAssertEqual(NSNumber(value: Int.min).doubleValue, Double(Int.min)) //-------- XCTAssertEqual(NSNumber(value: Int.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int.max).int8Value, -1) XCTAssertEqual(NSNumber(value: Int.max).int16Value, -1) XCTAssertEqual(NSNumber(value: Int.max).int32Value, -1) XCTAssertEqual(NSNumber(value: Int.max).int64Value, 9223372036854775807) XCTAssertEqual(NSNumber(value: Int.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: Int.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: Int.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: Int.max).uint64Value, 9223372036854775807) XCTAssertEqual(NSNumber(value: Int.max).intValue, 9223372036854775807) XCTAssertEqual(NSNumber(value: Int.max).uintValue, 9223372036854775807) XCTAssertEqual(NSNumber(value: Int.max).floatValue, Float(Int.max)) XCTAssertEqual(NSNumber(value: Int.max).doubleValue, Double(Int.max)) #endif default: XCTFail("Unexpected mismatched Int & UInt sizes: \(intSize) & \(uintSize)") } } func test_numberWithUInt() { XCTAssertEqual(NSNumber(value: UInt(0)).boolValue, false) XCTAssertEqual(NSNumber(value: UInt(0)).int8Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).int16Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).int32Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).int64Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).uint8Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).uint16Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).uint32Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).uint64Value, 0) XCTAssertEqual(NSNumber(value: UInt(0)).intValue, 0) XCTAssertEqual(NSNumber(value: UInt(0)).uintValue, 0) XCTAssertEqual(NSNumber(value: UInt(0)).floatValue, 0) XCTAssertEqual(NSNumber(value: UInt(0)).doubleValue, 0) //------ let intSize = MemoryLayout<Int>.size let uintSize = MemoryLayout<UInt>.size switch (intSize, uintSize) { case (4, 4): XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int16Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int32Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int64Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: UInt.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt.max).uint64Value, 4294967295) #if !arch(arm) XCTAssertEqual(NSNumber(value: UInt.max).intValue, 4294967295) #endif XCTAssertEqual(NSNumber(value: UInt.max).uintValue, 4294967295) XCTAssertEqual(NSNumber(value: UInt.max).floatValue, Float(UInt.max)) XCTAssertEqual(NSNumber(value: UInt.max).doubleValue, Double(UInt.max)) case (8, 8): XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt.max).int8Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int16Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int32Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).int64Value, -1) XCTAssertEqual(NSNumber(value: UInt.max).uint8Value, 255) XCTAssertEqual(NSNumber(value: UInt.max).uint16Value, 65535) XCTAssertEqual(NSNumber(value: UInt.max).uint32Value, 4294967295) XCTAssertEqual(NSNumber(value: UInt.max).uint64Value, 18446744073709551615) XCTAssertEqual(NSNumber(value: UInt.max).intValue, -1) #if !arch(arm) XCTAssertEqual(NSNumber(value: UInt.max).uintValue, 18446744073709551615) #endif XCTAssertEqual(NSNumber(value: UInt.max).floatValue, Float(UInt.max)) XCTAssertEqual(NSNumber(value: UInt.max).doubleValue, Double(UInt.max)) default: XCTFail("Unexpected mismatched Int & UInt sizes: \(intSize) & \(uintSize)") } } func test_numberWithFloat() { XCTAssertEqual(NSNumber(value: Float(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Float(0)).int8Value, Int8(0)) XCTAssertEqual(NSNumber(value: Float(0)).uint8Value, UInt8(0)) XCTAssertEqual(NSNumber(value: Float(0)).int16Value, Int16(0)) XCTAssertEqual(NSNumber(value: Float(0)).uint16Value, UInt16(0)) XCTAssertEqual(NSNumber(value: Float(0)).int32Value, Int32(0)) XCTAssertEqual(NSNumber(value: Float(0)).uint32Value, UInt32(0)) XCTAssertEqual(NSNumber(value: Float(0)).int64Value, Int64(0)) XCTAssertEqual(NSNumber(value: Float(0)).uint64Value, UInt64(0)) XCTAssertEqual(NSNumber(value: Float(1)).boolValue, true) XCTAssertEqual(NSNumber(value: Float(1)).int8Value, Int8(1)) XCTAssertEqual(NSNumber(value: Float(1)).uint8Value, UInt8(1)) XCTAssertEqual(NSNumber(value: Float(1)).int16Value, Int16(1)) XCTAssertEqual(NSNumber(value: Float(1)).uint16Value, UInt16(1)) XCTAssertEqual(NSNumber(value: Float(1)).int32Value, Int32(1)) XCTAssertEqual(NSNumber(value: Float(1)).uint32Value, UInt32(1)) XCTAssertEqual(NSNumber(value: Float(1)).int64Value, Int64(1)) XCTAssertEqual(NSNumber(value: Float(1)).uint64Value, UInt64(1)) XCTAssertEqual(NSNumber(value: Float(-37)).boolValue, true) XCTAssertEqual(NSNumber(value: Float(-37)).int8Value, Int8(-37)) XCTAssertEqual(NSNumber(value: Float(-37)).int16Value, Int16(-37)) XCTAssertEqual(NSNumber(value: Float(-37)).int32Value, Int32(-37)) XCTAssertEqual(NSNumber(value: Float(-37)).int64Value, Int64(-37)) XCTAssertEqual(NSNumber(value: Float(42)).boolValue, true) XCTAssertEqual(NSNumber(value: Float(42)).int8Value, Int8(42)) XCTAssertEqual(NSNumber(value: Float(42)).uint8Value, UInt8(42)) XCTAssertEqual(NSNumber(value: Float(42)).int16Value, Int16(42)) XCTAssertEqual(NSNumber(value: Float(42)).uint16Value, UInt16(42)) XCTAssertEqual(NSNumber(value: Float(42)).int32Value, Int32(42)) XCTAssertEqual(NSNumber(value: Float(42)).uint32Value, UInt32(42)) XCTAssertEqual(NSNumber(value: Float(42)).int64Value, Int64(42)) XCTAssertEqual(NSNumber(value: Float(42)).uint64Value, UInt64(42)) XCTAssertEqual(NSNumber(value: Float(0)).floatValue, Float(0)) XCTAssertEqual(NSNumber(value: Float(1)).floatValue, Float(1)) XCTAssertEqual(NSNumber(value: Float(-37.5)).floatValue, Float(-37.5)) XCTAssertEqual(NSNumber(value: Float(42.1)).floatValue, Float(42.1)) XCTAssertEqual(NSNumber(value: Float(0)).doubleValue, Double(0)) XCTAssertEqual(NSNumber(value: Float(1)).doubleValue, Double(1)) XCTAssertEqual(NSNumber(value: Float(-37.5)).doubleValue, Double(-37.5)) XCTAssertEqual(NSNumber(value: Float(42.5)).doubleValue, Double(42.5)) let nanFloat = NSNumber(value: Float.nan) XCTAssertTrue(nanFloat.doubleValue.isNaN) } func test_numberWithDouble() { XCTAssertEqual(NSNumber(value: Double(0)).boolValue, false) XCTAssertEqual(NSNumber(value: Double(0)).int8Value, Int8(0)) XCTAssertEqual(NSNumber(value: Double(0)).uint8Value, UInt8(0)) XCTAssertEqual(NSNumber(value: Double(0)).int16Value, Int16(0)) XCTAssertEqual(NSNumber(value: Double(0)).uint16Value, UInt16(0)) XCTAssertEqual(NSNumber(value: Double(0)).int32Value, Int32(0)) XCTAssertEqual(NSNumber(value: Double(0)).uint32Value, UInt32(0)) XCTAssertEqual(NSNumber(value: Double(0)).int64Value, Int64(0)) XCTAssertEqual(NSNumber(value: Double(0)).uint64Value, UInt64(0)) XCTAssertEqual(NSNumber(value: Double(-37)).boolValue, true) XCTAssertEqual(NSNumber(value: Double(-37)).int8Value, Int8(-37)) XCTAssertEqual(NSNumber(value: Double(-37)).int16Value, Int16(-37)) XCTAssertEqual(NSNumber(value: Double(-37)).int32Value, Int32(-37)) XCTAssertEqual(NSNumber(value: Double(-37)).int64Value, Int64(-37)) XCTAssertEqual(NSNumber(value: Double(42)).boolValue, true) XCTAssertEqual(NSNumber(value: Double(42)).int8Value, Int8(42)) XCTAssertEqual(NSNumber(value: Double(42)).uint8Value, UInt8(42)) XCTAssertEqual(NSNumber(value: Double(42)).int16Value, Int16(42)) XCTAssertEqual(NSNumber(value: Double(42)).uint16Value, UInt16(42)) XCTAssertEqual(NSNumber(value: Double(42)).int32Value, Int32(42)) XCTAssertEqual(NSNumber(value: Double(42)).uint32Value, UInt32(42)) XCTAssertEqual(NSNumber(value: Double(42)).int64Value, Int64(42)) XCTAssertEqual(NSNumber(value: Double(42)).uint64Value, UInt64(42)) XCTAssertEqual(NSNumber(value: Double(0)).floatValue, Float(0)) XCTAssertEqual(NSNumber(value: Double(-37.5)).floatValue, Float(-37.5)) XCTAssertEqual(NSNumber(value: Double(42.1)).floatValue, Float(42.1)) XCTAssertEqual(NSNumber(value: Double(0)).doubleValue, Double(0)) XCTAssertEqual(NSNumber(value: Double(-37.5)).doubleValue, Double(-37.5)) XCTAssertEqual(NSNumber(value: Double(42.1)).doubleValue, Double(42.1)) let nanDouble = NSNumber(value: Double.nan) XCTAssertTrue(nanDouble.floatValue.isNaN) } func test_compareNumberWithBool() { XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: false)), .orderedDescending) XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: true)), .orderedAscending) XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(0))), .orderedSame) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(-1))), .orderedDescending) #endif XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Int8(1))), .orderedAscending) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(1))), .orderedSame) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Int8(2))), .orderedAscending) XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(0))), .orderedSame) XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(-0.1))), .orderedDescending) XCTAssertEqual(NSNumber(value: false).compare(NSNumber(value: Double(0.1))), .orderedAscending) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(1))), .orderedSame) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(0.9))), .orderedDescending) XCTAssertEqual(NSNumber(value: true).compare(NSNumber(value: Double(1.1))), .orderedAscending) } func test_compareNumberWithChar() { XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Int8(0))), .orderedDescending) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: Int8(16))), .orderedAscending) #endif XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: Int8(1)).compare(NSNumber(value: false)), .orderedDescending) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: true)), .orderedAscending) #endif XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: UInt8(16))), .orderedDescending) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-37)).compare(NSNumber(value: UInt8(255))), .orderedAscending) #endif XCTAssertEqual(NSNumber(value: Int8(42)).compare(NSNumber(value: Float(42))), .orderedSame) #if !(os(Linux) && (arch(arm) || arch(powerpc64) || arch(powerpc64le))) // Linux/arm and Linux/power chars are unsigned, so Int8 in Swift, until this issue is resolved, these tests will always fail. XCTAssertEqual(NSNumber(value: Int8(-16)).compare(NSNumber(value: Float(-37.5))), .orderedDescending) #endif XCTAssertEqual(NSNumber(value: Int8(16)).compare(NSNumber(value: Float(16.1))), .orderedAscending) } func test_compareNumberWithUnsignedChar() { XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(0))), .orderedDescending) // XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: UInt8(255))), .orderedAscending) XCTAssertEqual(NSNumber(value: UInt8(1)).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: UInt8(1)).compare(NSNumber(value: false)), .orderedDescending) XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: true)), .orderedAscending) XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: Int16(42))), .orderedSame) XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: Int16(-123))), .orderedDescending) XCTAssertEqual(NSNumber(value: UInt8(255)).compare(NSNumber(value: Int16(12345))), .orderedAscending) XCTAssertEqual(NSNumber(value: UInt8(42)).compare(NSNumber(value: Float(42))), .orderedSame) XCTAssertEqual(NSNumber(value: UInt8(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending) XCTAssertEqual(NSNumber(value: UInt8(255)).compare(NSNumber(value: Float(1234.5))), .orderedAscending) } func test_compareNumberWithShort() { XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Int16(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Int16(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Int16(-37)).compare(NSNumber(value: Int16(12345))), .orderedAscending) XCTAssertEqual(NSNumber(value: Int16(1)).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: Int16(1)).compare(NSNumber(value: false)), .orderedDescending) XCTAssertEqual(NSNumber(value: Int16(0)).compare(NSNumber(value: true)), .orderedAscending) XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: UInt8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: UInt8(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Int16(-37)).compare(NSNumber(value: UInt8(255))), .orderedAscending) XCTAssertEqual(NSNumber(value: Int16(42)).compare(NSNumber(value: Float(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Int16(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending) XCTAssertEqual(NSNumber(value: Int16(255)).compare(NSNumber(value: Float(1234.5))), .orderedAscending) } func test_compareNumberWithFloat() { XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Float(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Float(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Float(-37)).compare(NSNumber(value: Float(12345))), .orderedAscending) XCTAssertEqual(NSNumber(value: Float(1)).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: Float(0.1)).compare(NSNumber(value: false)), .orderedDescending) XCTAssertEqual(NSNumber(value: Float(0.9)).compare(NSNumber(value: true)), .orderedAscending) XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: UInt8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Float(0.1)).compare(NSNumber(value: UInt8(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Float(-254.9)).compare(NSNumber(value: UInt8(255))), .orderedAscending) XCTAssertEqual(NSNumber(value: Float(42)).compare(NSNumber(value: Double(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Float(0)).compare(NSNumber(value: Double(-37.5))), .orderedDescending) XCTAssertEqual(NSNumber(value: Float(-37.5)).compare(NSNumber(value: Double(1234.5))), .orderedAscending) } func test_compareNumberWithDouble() { XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Double(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Double(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Double(-37)).compare(NSNumber(value: Double(12345))), .orderedAscending) XCTAssertEqual(NSNumber(value: Double(1)).compare(NSNumber(value: true)), .orderedSame) XCTAssertEqual(NSNumber(value: Double(0.1)).compare(NSNumber(value: false)), .orderedDescending) XCTAssertEqual(NSNumber(value: Double(0.9)).compare(NSNumber(value: true)), .orderedAscending) XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: UInt8(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Double(0.1)).compare(NSNumber(value: UInt8(0))), .orderedDescending) XCTAssertEqual(NSNumber(value: Double(-254.9)).compare(NSNumber(value: UInt8(255))), .orderedAscending) XCTAssertEqual(NSNumber(value: Double(42)).compare(NSNumber(value: Float(42))), .orderedSame) XCTAssertEqual(NSNumber(value: Double(0)).compare(NSNumber(value: Float(-37.5))), .orderedDescending) XCTAssertEqual(NSNumber(value: Double(-37.5)).compare(NSNumber(value: Float(1234.5))), .orderedAscending) } func test_description() { XCTAssertEqual(NSNumber(value: 1000).description, "1000") XCTAssertEqual(NSNumber(value: 0.001).description, "0.001") XCTAssertEqual(NSNumber(value: Int8.min).description, "-128") XCTAssertEqual(NSNumber(value: Int8.max).description, "127") XCTAssertEqual(NSNumber(value: Int16.min).description, "-32768") XCTAssertEqual(NSNumber(value: Int16.max).description, "32767") XCTAssertEqual(NSNumber(value: Int32.min).description, "-2147483648") XCTAssertEqual(NSNumber(value: Int32.max).description, "2147483647") XCTAssertEqual(NSNumber(value: Int64.min).description, "-9223372036854775808") XCTAssertEqual(NSNumber(value: Int64.max).description, "9223372036854775807") XCTAssertEqual(NSNumber(value: UInt8.min).description, "0") XCTAssertEqual(NSNumber(value: UInt8.max).description, "255") XCTAssertEqual(NSNumber(value: UInt16.min).description, "0") XCTAssertEqual(NSNumber(value: UInt16.max).description, "65535") XCTAssertEqual(NSNumber(value: UInt32.min).description, "0") XCTAssertEqual(NSNumber(value: UInt32.max).description, "4294967295") XCTAssertEqual(NSNumber(value: UInt64.min).description, "0") XCTAssertEqual(NSNumber(value: UInt64.max).description, "18446744073709551615") XCTAssertEqual(NSNumber(value: 1.2 as Float).description, "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description, "1e+09") XCTAssertEqual(NSNumber(value: -0.99 as Float).description, "-0.99") XCTAssertEqual(NSNumber(value: Float.zero).description, "0.0") XCTAssertEqual(NSNumber(value: Float.nan).description, "nan") XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description, "1.1754944e-38") XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description, "1e-45") XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description, "3.4028235e+38") XCTAssertEqual(NSNumber(value: Float.pi).description, "3.1415925") XCTAssertEqual(NSNumber(value: 1.2 as Double).description, "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description, "1000000000.0") XCTAssertEqual(NSNumber(value: -0.99 as Double).description, "-0.99") XCTAssertEqual(NSNumber(value: Double.zero).description, "0.0") XCTAssertEqual(NSNumber(value: Double.nan).description, "nan") XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description, "2.2250738585072014e-308") XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description, "5e-324") XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description, "1.7976931348623157e+308") XCTAssertEqual(NSNumber(value: Double.pi).description, "3.141592653589793") } func test_descriptionWithLocale() { // nil Locale XCTAssertEqual(NSNumber(value: 1000).description(withLocale: nil), "1000") XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: nil), "0.001") XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: nil), "-128") XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: nil), "127") XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: nil), "-32768") XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: nil), "32767") XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: nil), "-2147483648") XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: nil), "2147483647") XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: nil), "-9223372036854775808") XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: nil), "9223372036854775807") XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: nil), "0") XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: nil), "255") XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: nil), "0") XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: nil), "65535") XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: nil), "0") XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: nil), "4294967295") XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: nil), "0") XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: nil), "18446744073709551615") XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: nil), "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: nil), "1e+09") XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: nil), "-0.99") XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: nil), "0.0") XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: nil), "nan") XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: nil), "1.1754944e-38") XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: nil), "1e-45") XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: nil), "3.4028235e+38") XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: nil), "3.1415925") XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: nil), "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: nil), "1000000000.0") XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: nil), "-0.99") XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: nil), "0.0") XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: nil), "nan") XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: nil), "2.2250738585072014e-308") XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: nil), "5e-324") XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: nil), "1.7976931348623157e+308") XCTAssertEqual(NSNumber(value: Double.pi).description(withLocale: nil), "3.141592653589793") // en_GB Locale XCTAssertEqual(NSNumber(value: 1000).description(withLocale: Locale(identifier: "en_GB")), "1,000") XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: Locale(identifier: "en_GB")), "0.001") XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: Locale(identifier: "en_GB")), "-128") XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: Locale(identifier: "en_GB")), "127") XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: Locale(identifier: "en_GB")), "-32,768") XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: Locale(identifier: "en_GB")), "32,767") XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: Locale(identifier: "en_GB")), "-2,147,483,648") XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: Locale(identifier: "en_GB")), "2,147,483,647") XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: Locale(identifier: "en_GB")), "-9,223,372,036,854,775,808") XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: Locale(identifier: "en_GB")), "9,223,372,036,854,775,807") XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: Locale(identifier: "en_GB")), "0") XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: Locale(identifier: "en_GB")), "255") XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: Locale(identifier: "en_GB")), "0") XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: Locale(identifier: "en_GB")), "65,535") XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: Locale(identifier: "en_GB")), "0") XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: Locale(identifier: "en_GB")), "4,294,967,295") XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: Locale(identifier: "en_GB")), "0") // This is the correct value but currently buggy and the locale is not used // XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "en_GB")), "18,446,744,073,709,551,615") XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "en_GB")), "18446744073709551615") XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: Locale(identifier: "en_GB")), "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: Locale(identifier: "en_GB")), "1E+09") XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: Locale(identifier: "en_GB")), "-0.99") XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: Locale(identifier: "en_GB")), "0") XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: Locale(identifier: "en_GB")), "NaN") XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.175494E-38") XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.401298E-45") XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "en_GB")), "3.402823E+38") XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: Locale(identifier: "en_GB")), "3.141593") XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: Locale(identifier: "en_GB")), "1.2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: Locale(identifier: "en_GB")), "1,000,000,000") XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: Locale(identifier: "en_GB")), "-0.99") XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: Locale(identifier: "en_GB")), "0") XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: Locale(identifier: "en_GB")), "NaN") XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: Locale(identifier: "en_GB")), "2.225073858507201E-308") XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "en_GB")), "5E-324") XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "en_GB")), "1.797693134862316E+308") // de_DE Locale XCTAssertEqual(NSNumber(value: 1000).description(withLocale: Locale(identifier: "de_DE")), "1.000") XCTAssertEqual(NSNumber(value: 0.001).description(withLocale: Locale(identifier: "de_DE")), "0,001") XCTAssertEqual(NSNumber(value: Int8.min).description(withLocale: Locale(identifier: "de_DE")), "-128") XCTAssertEqual(NSNumber(value: Int8.max).description(withLocale: Locale(identifier: "de_DE")), "127") XCTAssertEqual(NSNumber(value: Int16.min).description(withLocale: Locale(identifier: "de_DE")), "-32.768") XCTAssertEqual(NSNumber(value: Int16.max).description(withLocale: Locale(identifier: "de_DE")), "32.767") XCTAssertEqual(NSNumber(value: Int32.min).description(withLocale: Locale(identifier: "de_DE")), "-2.147.483.648") XCTAssertEqual(NSNumber(value: Int32.max).description(withLocale: Locale(identifier: "de_DE")), "2.147.483.647") XCTAssertEqual(NSNumber(value: Int64.min).description(withLocale: Locale(identifier: "de_DE")), "-9.223.372.036.854.775.808") XCTAssertEqual(NSNumber(value: Int64.max).description(withLocale: Locale(identifier: "de_DE")), "9.223.372.036.854.775.807") XCTAssertEqual(NSNumber(value: UInt8.min).description(withLocale: Locale(identifier: "de_DE")), "0") XCTAssertEqual(NSNumber(value: UInt8.max).description(withLocale: Locale(identifier: "de_DE")), "255") XCTAssertEqual(NSNumber(value: UInt16.min).description(withLocale: Locale(identifier: "de_DE")), "0") XCTAssertEqual(NSNumber(value: UInt16.max).description(withLocale: Locale(identifier: "de_DE")), "65.535") XCTAssertEqual(NSNumber(value: UInt32.min).description(withLocale: Locale(identifier: "de_DE")), "0") XCTAssertEqual(NSNumber(value: UInt32.max).description(withLocale: Locale(identifier: "de_DE")), "4.294.967.295") XCTAssertEqual(NSNumber(value: UInt64.min).description(withLocale: Locale(identifier: "de_DE")), "0") // This is the correct value but currently buggy and the locale is not used //XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "de_DE")), "18.446.744.073.709.551.615") XCTAssertEqual(NSNumber(value: UInt64.max).description(withLocale: Locale(identifier: "de_DE")), "18446744073709551615") XCTAssertEqual(NSNumber(value: 1.2 as Float).description(withLocale: Locale(identifier: "de_DE")), "1,2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Float).description(withLocale: Locale(identifier: "de_DE")), "1E+09") XCTAssertEqual(NSNumber(value: -0.99 as Float).description(withLocale: Locale(identifier: "de_DE")), "-0,99") XCTAssertEqual(NSNumber(value: Float.pi).description(withLocale: Locale(identifier: "de_DE")), "3,141593") XCTAssertEqual(NSNumber(value: Float.zero).description(withLocale: Locale(identifier: "de_DE")), "0") XCTAssertEqual(NSNumber(value: Float.nan).description(withLocale: Locale(identifier: "de_DE")), "NaN") XCTAssertEqual(NSNumber(value: Float.leastNormalMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,175494E-38") XCTAssertEqual(NSNumber(value: Float.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,401298E-45") XCTAssertEqual(NSNumber(value: Float.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "de_DE")), "3,402823E+38") XCTAssertEqual(NSNumber(value: 1.2 as Double).description(withLocale: Locale(identifier: "de_DE")), "1,2") XCTAssertEqual(NSNumber(value: 1000_000_000 as Double).description(withLocale: Locale(identifier: "de_DE")), "1.000.000.000") XCTAssertEqual(NSNumber(value: -0.99 as Double).description(withLocale: Locale(identifier: "de_DE")), "-0,99") XCTAssertEqual(NSNumber(value: Double.zero).description(withLocale: Locale(identifier: "de_DE")), "0") XCTAssertEqual(NSNumber(value: Double.nan).description(withLocale: Locale(identifier: "de_DE")), "NaN") XCTAssertEqual(NSNumber(value: Double.leastNormalMagnitude).description(withLocale: Locale(identifier: "de_DE")), "2,225073858507201E-308") XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).description(withLocale: Locale(identifier: "de_DE")), "5E-324") XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).description(withLocale: Locale(identifier: "de_DE")), "1,797693134862316E+308") } func test_objCType() { let objCType: (NSNumber) -> UnicodeScalar = { number in return UnicodeScalar(UInt8(number.objCType.pointee)) } XCTAssertEqual("c" /* 0x63 */, objCType(NSNumber(value: true))) XCTAssertEqual("c" /* 0x63 */, objCType(NSNumber(value: Int8.max))) XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: UInt8(Int8.max)))) XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: UInt8(Int8.max) + 1))) XCTAssertEqual("s" /* 0x73 */, objCType(NSNumber(value: Int16.max))) XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: UInt16(Int16.max)))) XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: UInt16(Int16.max) + 1))) XCTAssertEqual("i" /* 0x69 */, objCType(NSNumber(value: Int32.max))) XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt32(Int32.max)))) XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt32(Int32.max) + 1))) XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: Int64.max))) // When value is lower equal to `Int64.max`, it returns 'q' even if using `UInt64` XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt64(Int64.max)))) XCTAssertEqual("Q" /* 0x51 */, objCType(NSNumber(value: UInt64(Int64.max) + 1))) // Depends on architectures #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: Int.max))) // When value is lower equal to `Int.max`, it returns 'q' even if using `UInt` XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt(Int.max)))) XCTAssertEqual("Q" /* 0x51 */, objCType(NSNumber(value: UInt(Int.max) + 1))) #elseif arch(i386) || arch(arm) XCTAssertEqual("i" /* 0x71 */, objCType(NSNumber(value: Int.max))) XCTAssertEqual("q" /* 0x71 */, objCType(NSNumber(value: UInt(Int.max)))) XCTAssertEqual("q" /* 0x51 */, objCType(NSNumber(value: UInt(Int.max) + 1))) #endif XCTAssertEqual("f" /* 0x66 */, objCType(NSNumber(value: Float.greatestFiniteMagnitude))) XCTAssertEqual("d" /* 0x64 */, objCType(NSNumber(value: Double.greatestFiniteMagnitude))) } func test_stringValue() { if UInt.max == UInt32.max { XCTAssertEqual(NSNumber(value: UInt.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt.max).stringValue, "4294967295") XCTAssertEqual(NSNumber(value: UInt.max - 1).stringValue, "4294967294") } else if UInt.max == UInt64.max { XCTAssertEqual(NSNumber(value: UInt.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt.max).stringValue, "18446744073709551615") XCTAssertEqual(NSNumber(value: UInt.max - 1).stringValue, "18446744073709551614") } XCTAssertEqual(NSNumber(value: UInt8.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt8.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt8.max).stringValue, "255") XCTAssertEqual(NSNumber(value: UInt8.max - 1).stringValue, "254") XCTAssertEqual(NSNumber(value: UInt16.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt16.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt16.max).stringValue, "65535") XCTAssertEqual(NSNumber(value: UInt16.max - 1).stringValue, "65534") XCTAssertEqual(NSNumber(value: UInt32.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt32.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt32.max).stringValue, "4294967295") XCTAssertEqual(NSNumber(value: UInt32.max - 1).stringValue, "4294967294") XCTAssertEqual(NSNumber(value: UInt64.min).stringValue, "0") XCTAssertEqual(NSNumber(value: UInt64.min + 1).stringValue, "1") XCTAssertEqual(NSNumber(value: UInt64.max).stringValue, "18446744073709551615") XCTAssertEqual(NSNumber(value: UInt64.max - 1).stringValue, "18446744073709551614") if Int.max == Int32.max { XCTAssertEqual(NSNumber(value: Int.min).stringValue, "-2147483648") XCTAssertEqual(NSNumber(value: Int.min + 1).stringValue, "-2147483647") XCTAssertEqual(NSNumber(value: Int.max).stringValue, "2147483647") XCTAssertEqual(NSNumber(value: Int.max - 1).stringValue, "2147483646") } else if Int.max == Int64.max { XCTAssertEqual(NSNumber(value: Int.min).stringValue, "-9223372036854775808") XCTAssertEqual(NSNumber(value: Int.min + 1).stringValue, "-9223372036854775807") XCTAssertEqual(NSNumber(value: Int.max).stringValue, "9223372036854775807") XCTAssertEqual(NSNumber(value: Int.max - 1).stringValue, "9223372036854775806") } XCTAssertEqual(NSNumber(value: Int8.min).stringValue, "-128") XCTAssertEqual(NSNumber(value: Int8.min + 1).stringValue, "-127") XCTAssertEqual(NSNumber(value: Int8.max).stringValue, "127") XCTAssertEqual(NSNumber(value: Int8.max - 1).stringValue, "126") XCTAssertEqual(NSNumber(value: Int16.min).stringValue, "-32768") XCTAssertEqual(NSNumber(value: Int16.min + 1).stringValue, "-32767") XCTAssertEqual(NSNumber(value: Int16.max).stringValue, "32767") XCTAssertEqual(NSNumber(value: Int16.max - 1).stringValue, "32766") XCTAssertEqual(NSNumber(value: Int32.min).stringValue, "-2147483648") XCTAssertEqual(NSNumber(value: Int32.min + 1).stringValue, "-2147483647") XCTAssertEqual(NSNumber(value: Int32.max).stringValue, "2147483647") XCTAssertEqual(NSNumber(value: Int32.max - 1).stringValue, "2147483646") XCTAssertEqual(NSNumber(value: Int64.min).stringValue, "-9223372036854775808") XCTAssertEqual(NSNumber(value: Int64.min + 1).stringValue, "-9223372036854775807") XCTAssertEqual(NSNumber(value: Int64.max).stringValue, "9223372036854775807") XCTAssertEqual(NSNumber(value: Int64.max - 1).stringValue, "9223372036854775806") } func test_Equals() { // Booleans: false only equals 0, true only equals 1 XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Bool(true))) XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Int(1))) XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Float(1))) XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Double(1))) XCTAssertTrue(NSNumber(value: true) == NSNumber(value: Int8(1))) XCTAssertTrue(NSNumber(value: true) != NSNumber(value: false)) XCTAssertTrue(NSNumber(value: true) != NSNumber(value: Int8(-1))) let f: Float = 1.01 let floatNum = NSNumber(value: f) XCTAssertTrue(NSNumber(value: true) != floatNum) let d: Double = 1234.56 let doubleNum = NSNumber(value: d) XCTAssertTrue(NSNumber(value: true) != doubleNum) XCTAssertTrue(NSNumber(value: true) != NSNumber(value: 2)) XCTAssertTrue(NSNumber(value: true) != NSNumber(value: Int.max)) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Bool(false))) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Int(0))) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Float(0))) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Double(0))) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: Int8(0))) XCTAssertTrue(NSNumber(value: false) == NSNumber(value: UInt64(0))) XCTAssertTrue(NSNumber(value: false) != NSNumber(value: 1)) XCTAssertTrue(NSNumber(value: false) != NSNumber(value: 2)) XCTAssertTrue(NSNumber(value: false) != NSNumber(value: Int.max)) XCTAssertTrue(NSNumber(value: Int8(-1)) == NSNumber(value: Int16(-1))) XCTAssertTrue(NSNumber(value: Int16(-1)) == NSNumber(value: Int32(-1))) XCTAssertTrue(NSNumber(value: Int32(-1)) == NSNumber(value: Int64(-1))) XCTAssertTrue(NSNumber(value: Int8.max) != NSNumber(value: Int16.max)) XCTAssertTrue(NSNumber(value: Int16.max) != NSNumber(value: Int32.max)) XCTAssertTrue(NSNumber(value: Int32.max) != NSNumber(value: Int64.max)) XCTAssertTrue(NSNumber(value: UInt8.min) == NSNumber(value: UInt16.min)) XCTAssertTrue(NSNumber(value: UInt16.min) == NSNumber(value: UInt32.min)) XCTAssertTrue(NSNumber(value: UInt32.min) == NSNumber(value: UInt64.min)) XCTAssertTrue(NSNumber(value: UInt8.max) != NSNumber(value: UInt16.max)) XCTAssertTrue(NSNumber(value: UInt16.max) != NSNumber(value: UInt32.max)) XCTAssertTrue(NSNumber(value: UInt32.max) != NSNumber(value: UInt64.max)) XCTAssertTrue(NSNumber(value: Int8(0)) == NSNumber(value: UInt16(0))) XCTAssertTrue(NSNumber(value: UInt16(0)) == NSNumber(value: Int32(0))) XCTAssertTrue(NSNumber(value: Int32(0)) == NSNumber(value: UInt64(0))) XCTAssertTrue(NSNumber(value: Int(0)) == NSNumber(value: UInt(0))) XCTAssertTrue(NSNumber(value: Int8.min) == NSNumber(value: Float(-128))) XCTAssertTrue(NSNumber(value: Int8.max) == NSNumber(value: Double(127))) XCTAssertTrue(NSNumber(value: UInt16.min) == NSNumber(value: Float(0))) XCTAssertTrue(NSNumber(value: UInt16.max) == NSNumber(value: Double(65535))) XCTAssertTrue(NSNumber(value: 1.1) != NSNumber(value: Int64(1))) let num = NSNumber(value: Int8.min) XCTAssertFalse(num == NSNumber(value: num.uint64Value)) let zero = NSNumber(value: 0) let one = NSNumber(value: 1) let minusOne = NSNumber(value: -1) let intMin = NSNumber(value: Int.min) let intMax = NSNumber(value: Int.max) let nanFloat = NSNumber(value: Float.nan) XCTAssertEqual(nanFloat.compare(nanFloat), .orderedSame) XCTAssertFalse(nanFloat == zero) XCTAssertFalse(zero == nanFloat) XCTAssertEqual(nanFloat.compare(zero), .orderedAscending) XCTAssertEqual(zero.compare(nanFloat), .orderedDescending) XCTAssertEqual(nanFloat.compare(one), .orderedAscending) XCTAssertEqual(one.compare(nanFloat), .orderedDescending) XCTAssertEqual(nanFloat.compare(intMax), .orderedAscending) XCTAssertEqual(intMax.compare(nanFloat), .orderedDescending) XCTAssertEqual(nanFloat.compare(minusOne), .orderedDescending) XCTAssertEqual(minusOne.compare(nanFloat), .orderedAscending) XCTAssertEqual(nanFloat.compare(intMin), .orderedDescending) XCTAssertEqual(intMin.compare(nanFloat), .orderedAscending) let nanDouble = NSNumber(value: Double.nan) XCTAssertEqual(nanDouble.compare(nanDouble), .orderedSame) XCTAssertFalse(nanDouble == zero) XCTAssertFalse(zero == nanDouble) XCTAssertEqual(nanDouble.compare(zero), .orderedAscending) XCTAssertEqual(zero.compare(nanDouble), .orderedDescending) XCTAssertEqual(nanDouble.compare(one), .orderedAscending) XCTAssertEqual(one.compare(nanDouble), .orderedDescending) XCTAssertEqual(nanDouble.compare(intMax), .orderedAscending) XCTAssertEqual(intMax.compare(nanDouble), .orderedDescending) XCTAssertEqual(nanDouble.compare(minusOne), .orderedDescending) XCTAssertEqual(minusOne.compare(nanDouble), .orderedAscending) XCTAssertEqual(nanDouble.compare(intMin), .orderedDescending) XCTAssertEqual(intMin.compare(nanDouble), .orderedAscending) XCTAssertEqual(nanDouble, nanFloat) XCTAssertEqual(nanFloat, nanDouble) XCTAssertEqual(NSNumber(value: Double.leastNonzeroMagnitude).compare(NSNumber(value: 0)), .orderedDescending) XCTAssertEqual(NSNumber(value: Double.greatestFiniteMagnitude).compare(NSNumber(value: 0)), .orderedDescending) XCTAssertTrue(NSNumber(value: Double(-0.0)) == NSNumber(value: Double(0.0))) } func test_boolValue() { XCTAssertEqual(NSNumber(value: UInt8.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt8.min).boolValue, false) XCTAssertEqual(NSNumber(value: UInt16.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt16.min).boolValue, false) XCTAssertEqual(NSNumber(value: UInt32.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt32.min).boolValue, false) XCTAssertEqual(NSNumber(value: UInt64.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt64.min).boolValue, false) XCTAssertEqual(NSNumber(value: UInt.max).boolValue, true) XCTAssertEqual(NSNumber(value: UInt.min).boolValue, false) XCTAssertEqual(NSNumber(value: Int8.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int8.max - 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int8.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int8.min + 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int8(-1)).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.max - 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int16.min + 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int16(-1)).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.max - 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.min).boolValue, true) XCTAssertEqual(NSNumber(value: Int32.min + 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int32(-1)).boolValue, true) XCTAssertEqual(NSNumber(value: Int64.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int64.max - 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int64.min).boolValue, false) // Darwin compatibility XCTAssertEqual(NSNumber(value: Int64.min + 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int64(-1)).boolValue, true) XCTAssertEqual(NSNumber(value: Int.max).boolValue, true) XCTAssertEqual(NSNumber(value: Int.max - 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int.min).boolValue, false) // Darwin compatibility XCTAssertEqual(NSNumber(value: Int.min + 1).boolValue, true) XCTAssertEqual(NSNumber(value: Int(-1)).boolValue, true) } func test_hash() { // A zero double hashes as zero. XCTAssertEqual(NSNumber(value: 0 as Double).hash, 0) // A positive double without fractional part should hash the same as the // equivalent 64 bit number. XCTAssertEqual(NSNumber(value: 123456 as Double).hash, NSNumber(value: 123456 as Int64).hash) // A negative double without fractional part should hash the same as the // equivalent 64 bit number. XCTAssertEqual(NSNumber(value: -123456 as Double).hash, NSNumber(value: -123456 as Int64).hash) #if arch(i386) || arch(arm) // This test used to fail in 32 bit platforms. XCTAssertNotEqual(NSNumber(value: 551048378.24883795 as Double).hash, 0) // Some hashes are correctly zero, though. Like the following which // was found by trial and error. XCTAssertEqual(NSNumber(value: 1.3819660135 as Double).hash, 0) #endif } }
e6a69955f4bb7f607637f7acfff8773d
56.36714
150
0.688129
false
true
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Test Doubles/Observers/CapturingPrivateMessagesObserver.swift
mit
2
import EurofurenceModel import Foundation class CapturingPrivateMessagesObserver: PrivateMessagesObserver { // MARK: New var wasToldSuccessfullyLoadedPrivateMessages = false private(set) var observedMessages: [Message] = [] func privateMessagesServiceDidFinishRefreshingMessages(messages: [Message]) { observedMessages = messages self.wasToldSuccessfullyLoadedPrivateMessages = true } private(set) var observedUnreadMessageCount: Int? func privateMessagesServiceDidUpdateUnreadMessageCount(to unreadCount: Int) { observedUnreadMessageCount = unreadCount } private(set) var wasToldFailedToLoadPrivateMessages = false func privateMessagesServiceDidFailToLoadMessages() { wasToldFailedToLoadPrivateMessages = true } }
d45b6d9ea3259225bd2e556952dfdc2b
30.88
81
0.770389
false
false
false
false
lrappaport87/VIPBGapp
refs/heads/test
VIPBGapp/ConsentTask.swift
bsd-3-clause
1
// // ConsentTask.swift // VIPBGapp // // Created by Lance Rappaport on 9/16/16. // Copyright © 2016 Lance Rappaport. All rights reserved. // import Foundation public var ConsentTask: ORKOrderedTask { var steps = [ORKStep]() let consentDocument = ConsentDocument let visualConsentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument) steps += [visualConsentStep] let participantSignature = ORKConsentSignature(forPersonWithTitle: "Participant", dateFormatString: nil, identifier: "participant") participantSignature.requiresName = true participantSignature.requiresSignatureImage = true consentDocument.addSignature(participantSignature) let investigatorSignature = ORKConsentSignature(forPersonWithTitle: "Investigator", dateFormatString: nil, identifier: "investigatorSignature", givenName: "Lance", familyName: "Rappaport, Ph.D.", signatureImage: UIImage(named: "signature.jpg"), dateString: "03/20/16") consentDocument.addSignature(investigatorSignature) let signature = consentDocument.signatures!.first let consentReviewStep = ORKConsentReviewStep(identifier: "consentReview", signature: signature, inDocument: consentDocument) consentReviewStep.text = "Please enter your name. This will be kept separate from the data you provide in this study." consentReviewStep.reasonForConsent = "Please indicate whether you agree to participate." steps += [consentReviewStep] return ORKOrderedTask(identifier: "ConsentTask", steps: steps) }
090c0a8bd566830e4bef86af44adddd7
41.891892
272
0.755514
false
false
false
false
scottsievert/Pythonic.swift
refs/heads/master
src/Pythonic.re.swift
mit
1
// Python docs: https://docs.python.org/2/library/re.html // // Most frequently used: // 346 re.search // 252 re.match // 218 re.compile // 217 re.sub // 28 re.split // 26 re.findall // 26 re.IGNORECASE // 17 re.escape // 16 re.VERBOSE // 9 re.finditer // // >>> filter(lambda s: not s.startswith("_"), dir(re)) // DEBUG // DOTALL // I // IGNORECASE // L // LOCALE // M // MULTILINE // S // Scanner // T // TEMPLATE // U // UNICODE // VERBOSE // X // compile // copy_reg // error // escape // findall // finditer // match // purge // search // split // sre_compile // sre_parse // sub // subn // sys // template import Foundation public class RegularExpressionMatch: BooleanType { private var matchedStrings = [String]() public init(_ matchedStrings: [String]) { self.matchedStrings.extend(matchedStrings) } public func groups() -> [String] { return Array(dropFirst(self.matchedStrings)) } public func group(i: Int) -> String? { return self.matchedStrings[i] } public var boolValue: Bool { return self.matchedStrings.count != 0 } public subscript (index: Int) -> String? { return self.group(index) } } public class re { public class func search(pattern: String, _ string: String) -> RegularExpressionMatch { var matchedStrings = [String]() if pattern == "" { return RegularExpressionMatch(matchedStrings) } // NOTE: Must use NSString:s below to avoid off-by-one issues when countElements(swiftString) != nsString.length. // Example case: countElements("\r\n") [1] != ("\r\n" as NSString).length [2] if let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil) { if let matches = regex.matchesInString(string, options: nil, range: NSMakeRange(0, (string as NSString).length)) as? [NSTextCheckingResult] { for match in matches { for i in 0..<match.numberOfRanges { var range = match.rangeAtIndex(i) var matchString = "" if range.location != Int.max { matchString = (string as NSString).substringWithRange(range) } matchedStrings += [matchString] } } } } return RegularExpressionMatch(matchedStrings) } public class func match(pattern: String, _ string: String) -> RegularExpressionMatch { return re.search(pattern.startsWith("^") ? pattern : "^" + pattern, string) } public class func split(pattern: String, _ string: String) -> [String] { if pattern == "" { return [string] } var returnedMatches = [String]() // NOTE: Must use NSString:s below to avoid off-by-one issues when countElements(swiftString) != nsString.length. // Example case: countElements("\r\n") [1] != ("\r\n" as NSString).length [2] if let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil) { if let matches = regex.matchesInString(string, options: nil, range: NSMakeRange(0, (string as NSString).length)) as? [NSTextCheckingResult] { var includeDelimiters = false // Heuristic detection of capture group(s) to try matching behaviour of Python's re.split. Room for improvement. if "(".`in`(pattern.replace("\\(", "").replace("(?", "")) { includeDelimiters = true } var previousRange: NSRange? var lastLocation = 0 for match in matches { if includeDelimiters { if let previousRange = previousRange { var previousString: String = (string as NSString).substringWithRange(NSMakeRange(previousRange.location, previousRange.length)) returnedMatches += [previousString] } } var matchedString: String = (string as NSString).substringWithRange(NSMakeRange(lastLocation, match.range.location - lastLocation)) returnedMatches += [matchedString] lastLocation = match.range.location + match.range.length previousRange = match.range } if includeDelimiters { if let previousRange = previousRange { var previousString: String = (string as NSString).substringWithRange(NSMakeRange(previousRange.location, previousRange.length)) returnedMatches += [previousString] } } var matchedString: String = (string as NSString).substringWithRange(NSMakeRange(lastLocation, (string as NSString).length - lastLocation)) returnedMatches += [matchedString] } } return returnedMatches } public class func sub(pattern: String, _ repl: String, _ string: String) -> String { var replaceWithString = repl for i in 0...9 { replaceWithString = replaceWithString.replace("\\\(i)", "$\(i)") } if let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil) { return regex.stringByReplacingMatchesInString(string, options: nil, range: NSMakeRange(0, (string as NSString).length), withTemplate: replaceWithString) } return string } }
2927912d08e6a2f3d760cc83709edcdb
35.490323
164
0.570545
false
false
false
false
BruceFight/JHB_HUDView
refs/heads/master
JHB_HUDViewExample/ExampleMainPart/ExampleNaviController.swift
mit
1
// // ExampleNaviController.swift // JHB_HUDViewExample // // Created by Leon_pan on 16/8/23. // Copyright © 2016年 bruce. All rights reserved. // import UIKit class ExampleNaviController: UINavigationController ,UIGestureRecognizerDelegate,UINavigationControllerDelegate{ override func viewDidLoad() { super.viewDidLoad() // ❤️通过这一步,可以实现被删除掉的侧滑功能!!!!❤️ if self.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) { self.interactivePopGestureRecognizer!.delegate = self } } // ❤️1⃣️在重写pushViewController方法中来设置NavigationController下的根控制器的返回按钮 override func pushViewController(_ viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: true) // ❤️重写返回按钮 if viewController.isKind(of: ExampleMainController.self) { }else { let newBackButton = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ExampleNaviController.back(_:))) viewController.navigationItem.leftBarButtonItem = newBackButton; } } // ❤️2⃣️当然也可以在各个跟控制器中来设置新样式的navigationItem来代替原有的 /* // ①隐藏原有 self.navigationItem.hidesBackButton = true // ②创建新的 let newBackButton = UIBarButtonItem(title: "<Back", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(publicNavController.back(_:))) // ③赋值替换 self.navigationItem.leftBarButtonItem = newBackButton; */ func back(_ sender: UIBarButtonItem) { // Perform your custom actions // ... // Go back to the previous ViewController self.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ed8b619404e3c36ed2479ec491159ba9
38.711538
164
0.628571
false
false
false
false
sandeep-chhabra/SDSegmentController
refs/heads/master
SDSegmentController/Classes/SDSegmentControl.swift
mit
1
// // SDSegmentControl.swift // SDSegmentController // // Created by Sandeep Chhabra on 29/05/17. // Copyright © 2017 Sandeep Chhabra. All rights reserved. // //TODO : ERROR HANDLING FOR WRONG OR NOT INPUT //TODO: HANDLING FOR IMAGE SIZE BIGGER THAN OWN SIZE import UIKit public enum SDSegmentWidth { case dynamic case fixed } public enum SDSegmentControlType{ case text case image case imageText } public enum SDMoveDirection{ case forward case backward } fileprivate extension UIButton { func centerVeticallyWith(padding:CGFloat){ guard let imageSize = self.imageView?.image?.size, let text = self.titleLabel?.text, let font = self.titleLabel?.font else { return } self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + padding), right: 0.0) let labelString = NSString(string: text) let titleSize = labelString.size(attributes: [NSFontAttributeName: font]) self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + padding), left: 0.0, bottom: 0.0, right: -titleSize.width) let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0; self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0) } func centerVertically() { centerVeticallyWith(padding:5) } } public class SDButton:UIButton{ override public var isSelected: Bool{ set (val){ super.isSelected = val centerVertically() } get{ return super.isSelected } } } fileprivate extension UIImage{ func resizeImage( newHeight: CGFloat) -> UIImage { let scale = newHeight / self.size.height let newWidth = self.size.width * scale UIGraphicsBeginImageContext(CGSize.init(width: newWidth, height: newHeight)) self.draw(in: CGRect.init(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize.init(width: newWidth, height: newHeight)) image.draw(in: CGRect.init(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } public protocol SDSegmentControlDelegate { //delegate method called aways even when user selects segment func segmentControl(segmentControl:SDSegmentControl, willSelectSegmentAt index:Int) func segmentControl(segmentControl:SDSegmentControl, didSelectSegmentAt index:Int) } open class SDSegmentControl: UIControl { override open func awakeFromNib() { // NSLog("awwake from nib") } public var delegate: SDSegmentControlDelegate? //set these values accordingly if using default init or to change segments at runtime public var _sectionTitles:[String]? public var _sectionImages:[UIImage]? public var _selectedSectionImages:[UIImage]? public var _controlType:SDSegmentControlType = .text private var _scrollView:UIScrollView! private var _selectionIndicator : UIView //movement to next segment private var _currentProgress : CGFloat = 0 private var _currentDirection : SDMoveDirection = .forward public var selectionIndicatorHeight :CGFloat = 4 public var segmentWidthStyle : SDSegmentWidth = .fixed public var selectionIndicatorColor:UIColor = UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1) public var sectionColor:UIColor = UIColor.white public var titleTextAttributes : [String: AnyObject] public var selectedTitleTextAttributes : [String: AnyObject] public var selectedSectionIndex : Int = 0 public var lastSelectedSectionIndex :Int = 0 // inset applied to left and right of section each public var sectionInset:CGFloat = 0 public var numberOfSegments : Int { get{ var count = 0 switch _controlType { case .image: count = (_sectionImages?.count)! break case .imageText: count = (_sectionTitles?.count)! break case .text: count = (_sectionTitles?.count)! break } return count } } public var moveDirection : SDMoveDirection { get{ return lastSelectedSectionIndex > selectedSectionIndex ? .backward : .forward } } //MARK: - Initialization public init(){ sectionInset = 10 _scrollView = UIScrollView() _selectionIndicator = UIView() _sectionTitles = ["this","is","test","for","segments"] titleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 67/255, green: 67/255, blue: 67/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] super.init(frame: CGRect()) } convenience public init(sectionTitles:[String]){ self.init() _sectionTitles = sectionTitles _controlType = .text } convenience public init(sectionImages:[UIImage],selectedSectionImages:[UIImage]) { self.init() _sectionImages = sectionImages _selectedSectionImages = selectedSectionImages _controlType = .image } convenience public init(sectionImages:[UIImage],selectedSectionImages:[UIImage],sectionTitles:[String]) { self.init() _sectionImages = sectionImages _selectedSectionImages = selectedSectionImages _sectionTitles = sectionTitles _controlType = .imageText } required public init?(coder aDecoder: NSCoder) { sectionInset = 10 _scrollView = UIScrollView() _selectionIndicator = UIView() _sectionTitles = ["this","is","test","for","segments"] titleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 67/255, green: 67/255, blue: 67/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] super.init(coder : aDecoder) } // MARK: - Draw segments open func drawSegments(){ NSLog("draw segments") _scrollView.removeFromSuperview() _scrollView = UIScrollView() //Add scroll view _scrollView.isDirectionalLockEnabled = true _scrollView.showsVerticalScrollIndicator = false _scrollView.showsHorizontalScrollIndicator = false _scrollView.frame = self.bounds self.addSubview(_scrollView) //temp _scrollView.backgroundColor = sectionColor self.backgroundColor = UIColor.gray rescaleImagesIfNeeded() //Add sections let maxWidth = self.maxWidth() var x:CGFloat = 0 //sectionMargin let count = numberOfSegments for index in 0...count-1 { let btnWidth = ( segmentWidthStyle == .fixed ? maxWidth : widthAt(index: index)) + (sectionInset * 2) let rect = CGRect(x: x, y: CGFloat(0), width: btnWidth ,height: self.frame.size.height - selectionIndicatorHeight ) let button = SDButton(frame:rect ) button.addTarget(self, action: #selector(sectionSlected(button:)), for: UIControlEvents.touchUpInside) button.tag = index + 999 //temp button.backgroundColor = sectionColor // switch _controlType { case .image: if var image = _sectionImages?[index] { let height = image.size.height if height > self.frame.size.height{ image = image.resizeImage( newHeight: self.frame.size.height) } button.setImage(image, for: .normal) } if var selectedImage = _selectedSectionImages?[index] { let height = selectedImage.size.height if height > self.frame.size.height{ selectedImage = selectedImage.resizeImage( newHeight: self.frame.size.height) } button.setImage(selectedImage, for: .selected) } break case .imageText: let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) button.setAttributedTitle(attrTitle, for: .normal) button.setAttributedTitle(attrTitleSelected, for: .selected) button.setImage(_sectionImages?[index], for: .normal) button.setImage(_selectedSectionImages?[index], for: .selected) //call after setting image and text button.centerVertically() break case .text: let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) button.setAttributedTitle(attrTitle, for: .normal) button.setAttributedTitle(attrTitleSelected, for: .selected) break } _scrollView.addSubview(button) x = x+btnWidth //+ sectionMargin } _scrollView.contentSize = CGSize(width: x, height: self.frame.size.height) //check selected section less than total section selectedSectionIndex = selectedSectionIndex < numberOfSegments ? selectedSectionIndex : 0 //Add Selection indicator let selectedView = (_scrollView.viewWithTag(selectedSectionIndex + 999)) as! UIButton var frame = selectedView.frame frame.origin.y += (frame.size.height) frame.size.height = selectionIndicatorHeight _selectionIndicator.frame = frame _scrollView.addSubview(_selectionIndicator) _selectionIndicator.backgroundColor = selectionIndicatorColor // //change state of selected section selectedView.isSelected = true _scrollView.scrollRectToVisible(selectedView.frame, animated: true) } func rescaleImagesIfNeeded(){ if _controlType != .imageText && _controlType != .image { return } let padding : CGFloat = 5 let topInset : CGFloat = 7 let bottomInset : CGFloat = 7 for index in 0..<numberOfSegments{ var titleHeight : CGFloat = 0 var selectedTitleHeight : CGFloat = 0 if _controlType == .imageText { let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) titleHeight = attrTitle.size().height + padding selectedTitleHeight = attrTitleSelected.size().height + padding } if let image = _sectionImages?[index] , let selectedImage = _selectedSectionImages?[index] { //Match heights of images and selected images by taking min so that chances of rescaling are reduced in next step let minHeight = min(image.size.height, selectedImage.size.height) if image.size.height != selectedImage.size.height { if image.size.height > selectedImage.size.height{ _sectionImages?[index] = image.resizeImage( newHeight: minHeight) } else{ _selectedSectionImages?[index] = selectedImage.resizeImage( newHeight: minHeight) } } //rescale section images if they do not fit in button let totalHeight = minHeight + titleHeight + topInset + bottomInset let totalSelectedHeight = minHeight + selectedTitleHeight + topInset + bottomInset if totalHeight > self.frame.size.height{ _sectionImages?[index] = image.resizeImage( newHeight: self.frame.size.height - titleHeight - topInset - bottomInset) } if totalSelectedHeight > self.frame.size.height{ _selectedSectionImages?[index] = selectedImage.resizeImage( newHeight: self.frame.size.height - selectedTitleHeight - topInset - bottomInset) } } } } //MARK: Drawing helpers func attributedTitleAt(index:Int) -> NSAttributedString { let title = _sectionTitles?[index] let textAtt = selectedSectionIndex == index ? selectedTitleTextAttributes : titleTextAttributes return NSAttributedString.init(string: title!, attributes: textAtt) } func maxWidth() -> CGFloat { var maxWidth:CGFloat = 0 let count = numberOfSegments for i in 0...count-1{ let currentWidth = widthAt(index: i) maxWidth = currentWidth > maxWidth ? currentWidth : maxWidth } //IF the max width can be increased to fill screen // let calcMaxScrWidth = (self.frame.size.width - (CGFloat(numberOfSegments+1) * sectionMargin))/CGFloat( numberOfSegments) let calcMaxScrWidth = (self.frame.size.width - (CGFloat(numberOfSegments) * (sectionInset*2)))/CGFloat( numberOfSegments) maxWidth = calcMaxScrWidth > maxWidth ? calcMaxScrWidth : maxWidth return maxWidth } func widthAt(index:Int) -> CGFloat { switch _controlType { case .image: let image = _sectionImages?[index] return image!.size.width case .imageText: let attrStr = self.attributedTitleAt(index: index) let image = _sectionImages![index] let selectedImage = _selectedSectionImages![index] return max(attrStr.size().width,image.size.width, selectedImage.size.width) case .text: let attrStr = self.attributedTitleAt(index: index) return attrStr.size().width } } public func viewAt(segmentIndex:Int) -> UIView? { return self.viewWithTag(segmentIndex+999) } //MARK: - Action for sections tap func sectionSlected(button:UIButton) { selectSegment(segmentbButton: button,index: nil, shouldSendAction: true) } open func selectSegment(segmentbButton:UIButton?,index:Int?) { selectSegment(segmentbButton: segmentbButton, index: index, shouldSendAction: false) } private func selectSegment(segmentbButton:UIButton?,index:Int? , shouldSendAction:Bool) { selectSegment(segmentbButton: segmentbButton, index: index, shouldSendAction: shouldSendAction, isReselect: false) } private func selectSegment(segmentbButton:UIButton?,index:Int? , shouldSendAction:Bool, isReselect:Bool){ switch (index , segmentbButton) { case let (x,y) where x == nil && y == nil: return case ( let x , _) where x != nil : if x! > numberOfSegments - 1 || x! < 0 { return } default: break } let currentSelectionView = segmentbButton != nil ? segmentbButton : (_scrollView.viewWithTag(index! + 999) as! UIButton) let currentSectionIndex = (currentSelectionView?.tag)! - 999 if currentSectionIndex == self.selectedSectionIndex && isReselect == false { return } if isReselect == false { lastSelectedSectionIndex = self.selectedSectionIndex self.selectedSectionIndex = currentSectionIndex } //delegate method called always even when user selects segment self.delegate?.segmentControl(segmentControl: self, willSelectSegmentAt: currentSectionIndex) if shouldSendAction { self.sendActions(for: .valueChanged) } _selectionIndicator.layer.removeAllAnimations() _scrollView.scrollRectToVisible((currentSelectionView?.frame)!, animated: true) UIView.animate(withDuration: 0.2, animations: { let newPosition = CGRect(x: (currentSelectionView?.frame.origin.x)!, y: self._selectionIndicator.frame.origin.y, width: (currentSelectionView?.frame.size.width)!, height: self.selectionIndicatorHeight) self._selectionIndicator.frame = newPosition }) { (completed) in if isReselect == false{ currentSelectionView?.isSelected = true let lastSelectedView = self._scrollView.viewWithTag(self.lastSelectedSectionIndex+999) as! UIButton lastSelectedView.isSelected = false } //delegate method called always even when user selects segment self.delegate?.segmentControl(segmentControl: self, didSelectSegmentAt: currentSectionIndex) } } //MARK: - Refresh open func refreshSegemts() { // self.setNeedsDisplay() self.drawSegments() } //MARK: - Drag to next open func beginMoveToNextSegment(){ //disable touch } open func endMoveToNextSegment(){ switch (selectedSectionIndex,_currentDirection) { case (0, .backward): return case (numberOfSegments - 1,.forward): return default: // print("Default case endMoveToNextSegment \(selectedSectionIndex), \(_currentDirection), \(_currentProgress)") break } if _currentProgress > 0.5 { //move to next section selectSegment(segmentbButton: nil, index: selectedSectionIndex + (_currentDirection == .forward ? 1 : -1) , shouldSendAction: false) } else{ //move back to deafult pos selectSegment(segmentbButton: nil, index: selectedSectionIndex , shouldSendAction: false, isReselect: true) } //enable touch } open func setProgressToNextSegment(progress:CGFloat , direction : SDMoveDirection){ _currentDirection = direction switch (selectedSectionIndex,direction) { case (0,.backward): return case (numberOfSegments - 1,.forward): return default: break } switch progress { case let p where p <= 0: _currentProgress = 0 return case let p where p >= 1: _currentProgress = 1 // case let p where p > 0.5: // //TODO:select segment and deselect previous // break // case let p where p <= 0.5: // //TODO:deselect segment and select previous // break default: _currentProgress = progress break } let viewTag = selectedSectionIndex + (direction == .forward ? 1 : -1) + 999 let nxtSegmentView = _scrollView.viewWithTag(viewTag) as! UIButton let nxtFrame = nxtSegmentView.frame let currentView = _scrollView.viewWithTag(selectedSectionIndex + 999) as! UIButton let currentFrame = currentView.frame var x : CGFloat = 0 var width : CGFloat = 0 let y = _selectionIndicator.frame.origin.y switch (direction , segmentWidthStyle) { case (.forward , .fixed): x = currentFrame.origin.x + ((currentFrame.size.width ) * _currentProgress) width = nxtFrame.size.width break case (.forward , .dynamic): x = currentFrame.origin.x + ((currentFrame.size.width ) * _currentProgress) width = currentFrame.size.width + (nxtFrame.size.width - currentFrame.size.width) * _currentProgress break case (.backward , .fixed): x = currentFrame.origin.x - ((currentFrame.size.width ) * _currentProgress) width = nxtFrame.size.width break case (.backward , .dynamic): x = currentFrame.origin.x - ((nxtFrame.size.width ) * _currentProgress) width = currentFrame.size.width + (nxtFrame.size.width - currentFrame.size.width) * _currentProgress break } _selectionIndicator.frame = CGRect(x:x , y: y, width:width, height:selectionIndicatorHeight) // switch direction { // case .forward: // let x = currentFrame.origin.x + (nxtFrame.size.width * _currentProgress) // _selectionIndicator.frame = CGRect(x:x , y: _selectionIndicator.frame.origin.y, width:nxtFrame.size.width * (segmentWidthStyle == .fixed ? 1 : _currentProgress), height:selectionIndicatorHeight) // break // default: // let x = currentFrame.origin.x - (nxtFrame.size.width * _currentProgress) // NSLog("backx = \(x)") // _selectionIndicator.frame = CGRect(x:x , y: _selectionIndicator.frame.origin.y, width:nxtFrame.size.width * (segmentWidthStyle == .fixed ? 1 : _currentProgress), height:selectionIndicatorHeight) // // break // } } }
97e383a20519e57d47b79b999d52e75f
35.274882
213
0.597596
false
false
false
false
practicalswift/swift
refs/heads/master
test/Constraints/tuple_arguments.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -swift-version 5 // See test/Compatibility/tuple_arguments_3.swift for the Swift 3 behavior. // See test/Compatibility/tuple_arguments_4.swift for the Swift 4 behavior. func concrete(_ x: Int) {} func concreteLabeled(x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} do { concrete(3) concrete((3)) concreteLabeled(x: 3) concreteLabeled(x: (3)) concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}} concreteTwo(3, 4) concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} do { generic(3) generic(3, 4) // expected-error {{extra argument in call}} generic((3)) generic((3, 4)) genericLabeled(x: 3) genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} genericLabeled(x: (3)) genericLabeled(x: (3, 4)) genericTwo(3, 4) genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } var function: (Int) -> () var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () do { function(3) function((3)) functionTwo(3, 4) functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } struct Concrete {} extension Concrete { func concrete(_ x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} } do { let s = Concrete() s.concrete(3) s.concrete((3)) s.concreteTwo(3, 4) s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } extension Concrete { func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} } do { let s = Concrete() s.generic(3) s.generic(3, 4) // expected-error {{extra argument in call}} s.generic((3)) s.generic((3, 4)) s.genericLabeled(x: 3) s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.genericLabeled(x: (3)) s.genericLabeled(x: (3, 4)) s.genericTwo(3, 4) s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } extension Concrete { mutating func mutatingConcrete(_ x: Int) {} mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}} mutating func mutatingConcreteTuple(_ x: (Int, Int)) {} } do { var s = Concrete() s.mutatingConcrete(3) s.mutatingConcrete((3)) s.mutatingConcreteTwo(3, 4) s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } extension Concrete { mutating func mutatingGeneric<T>(_ x: T) {} mutating func mutatingGenericLabeled<T>(x: T) {} mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {} } do { var s = Concrete() s.mutatingGeneric(3) s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}} s.mutatingGeneric((3)) s.mutatingGeneric((3, 4)) s.mutatingGenericLabeled(x: 3) s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.mutatingGenericLabeled(x: (3)) s.mutatingGenericLabeled(x: (3, 4)) s.mutatingGenericTwo(3, 4) s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } extension Concrete { var function: (Int) -> () { return concrete } var functionTwo: (Int, Int) -> () { return concreteTwo } var functionTuple: ((Int, Int)) -> () { return concreteTuple } } do { let s = Concrete() s.function(3) s.function((3)) s.functionTwo(3, 4) s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(3, 4) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}} s.functionTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}} s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } struct InitTwo { init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init(_:_:)' declared here}} } struct InitTuple { init(_ x: (Int, Int)) {} } struct InitLabeledTuple { init(x: (Int, Int)) {} } do { _ = InitTwo(3, 4) _ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((3, 4)) _ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = InitLabeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } struct SubscriptTwo { subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct SubscriptTuple { subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } } } struct SubscriptLabeledTuple { subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } } } do { let s1 = SubscriptTwo() _ = s1[3, 4] _ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}} let s2 = SubscriptTuple() _ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(3, 4)] } do { let a = 3 let b = 4 let d = (a, b) let s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s1[d] // expected-error {{missing argument for parameter #2 in call}} let s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] let s3 = SubscriptLabeledTuple() _ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} _ = s3[x: (3, 4)] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s1[d] // expected-error {{missing argument for parameter #2 in call}} var s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] } enum Enum { case two(Int, Int) // expected-note 6 {{'two' declared here}} case tuple((Int, Int)) case labeledTuple(x: (Int, Int)) } do { _ = Enum.two(3, 4) _ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((3, 4)) _ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}} _ = Enum.labeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } struct Generic<T> {} extension Generic { func generic(_ x: T) {} func genericLabeled(x: T) {} func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}} func genericTuple(_ x: (T, T)) {} } do { let s = Generic<Double>() s.generic(3.0) s.generic((3.0)) s.genericLabeled(x: 3.0) s.genericLabeled(x: (3.0)) s.genericTwo(3.0, 4.0) s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}} s.genericTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}} sTwo.generic((3.0, 4.0)) sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.genericLabeled(x: (3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } extension Generic { mutating func mutatingGeneric(_ x: T) {} mutating func mutatingGenericLabeled(x: T) {} mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple(_ x: (T, T)) {} } do { var s = Generic<Double>() s.mutatingGeneric(3.0) s.mutatingGeneric((3.0)) s.mutatingGenericLabeled(x: 3.0) s.mutatingGenericLabeled(x: (3.0)) s.mutatingGenericTwo(3.0, 4.0) s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.mutatingGenericTuple((3.0, 4.0)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.mutatingGeneric((3.0, 4.0)) sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.mutatingGenericLabeled(x: (3.0, 4.0)) } do { var s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } extension Generic { var genericFunction: (T) -> () { return generic } var genericFunctionTwo: (T, T) -> () { return genericTwo } var genericFunctionTuple: ((T, T)) -> () { return genericTuple } } do { let s = Generic<Double>() s.genericFunction(3.0) s.genericFunction((3.0)) s.genericFunctionTwo(3.0, 4.0) s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{34-34=)}} s.genericFunctionTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{32-32=)}} sTwo.genericFunction((3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } struct GenericInit<T> { init(_ x: T) {} } struct GenericInitLabeled<T> { init(x: T) {} } struct GenericInitTwo<T> { init(_ x: T, _ y: T) {} // expected-note 10 {{'init(_:_:)' declared here}} } struct GenericInitTuple<T> { init(_ x: (T, T)) {} } struct GenericInitLabeledTuple<T> { init(x: (T, T)) {} } do { _ = GenericInit(3, 4) // expected-error {{extra argument in call}} _ = GenericInit((3, 4)) _ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled(x: (3, 4)) _ = GenericInitTwo(3, 4) _ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((3, 4)) _ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} _ = GenericInitLabeledTuple(x: (3, 4)) } do { _ = GenericInit<(Int, Int)>(3, 4) // expected-error {{extra argument in call}} _ = GenericInit<(Int, Int)>((3, 4)) _ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled<(Int, Int)>(x: (3, 4)) _ = GenericInitTwo<Int>(3, 4) _ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((3, 4)) _ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} _ = GenericInitLabeledTuple<Int>(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } struct GenericSubscript<T> { subscript(_ x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeled<T> { subscript(x x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptTwo<T> { subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct GenericSubscriptLabeledTuple<T> { subscript(x x: (T, T)) -> Int { get { return 0 } set { } } } struct GenericSubscriptTuple<T> { subscript(_ x: (T, T)) -> Int { get { return 0 } set { } } } do { let s1 = GenericSubscript<(Double, Double)>() _ = s1[3.0, 4.0] // expected-error {{extra argument in call}} _ = s1[(3.0, 4.0)] let s1a = GenericSubscriptLabeled<(Double, Double)>() _ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}} _ = s1a [x: (3.0, 4.0)] let s2 = GenericSubscriptTwo<Double>() _ = s2[3.0, 4.0] _ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}} let s3 = GenericSubscriptTuple<Double>() _ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{18-18=)}} _ = s3[(3.0, 4.0)] let s3a = GenericSubscriptLabeledTuple<Double>() _ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} _ = s3a[x: (3.0, 4.0)] } do { let a = 3.0 let b = 4.0 let d = (a, b) let s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{extra argument in call}} _ = s1[(a, b)] _ = s1[d] let s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s2[d] // expected-error {{missing argument for parameter #2 in call}} let s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{extra argument in call}} _ = s1[(a, b)] _ = s1[d] var s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}} _ = s2[d] // expected-error {{missing argument for parameter #2 in call}} var s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } enum GenericEnum<T> { case one(T) case labeled(x: T) case two(T, T) // expected-note 10 {{'two' declared here}} case tuple((T, T)) } do { _ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.one((3, 4)) _ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled(x: (3, 4)) _ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum.two(3, 4) _ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((3, 4)) } do { _ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((3, 4)) _ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled(x: (3, 4)) _ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum<Int>.two(3, 4) _ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } protocol Protocol { associatedtype Element } extension Protocol { func requirement(_ x: Element) {} func requirementLabeled(x: Element) {} func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}} func requirementTuple(_ x: (Element, Element)) {} } struct GenericConforms<T> : Protocol { typealias Element = T } do { let s = GenericConforms<Double>() s.requirement(3.0) s.requirement((3.0)) s.requirementLabeled(x: 3.0) s.requirementLabeled(x: (3.0)) s.requirementTwo(3.0, 4.0) s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{30-30=)}} s.requirementTuple((3.0, 4.0)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{28-28=)}} sTwo.requirement((3.0, 4.0)) sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.requirementLabeled(x: (3.0, 4.0)) } do { let s = GenericConforms<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } do { var s = GenericConforms<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) var sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } extension Protocol { func takesClosure(_ fn: (Element) -> ()) {} func takesClosureTwo(_ fn: (Element, Element) -> ()) {} func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {} } do { let s = GenericConforms<Double>() s.takesClosure({ _ = $0 }) s.takesClosure({ x in }) s.takesClosure({ (x: Double) in }) s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ _ = $0; _ = $1 }) s.takesClosureTwo({ (x, y) in }) s.takesClosureTwo({ (x: Double, y:Double) in }) s.takesClosureTuple({ _ = $0 }) s.takesClosureTuple({ x in }) s.takesClosureTuple({ (x: (Double, Double)) in }) s.takesClosureTuple({ _ = $0; _ = $1 }) s.takesClosureTuple({ (x, y) in }) s.takesClosureTuple({ (x: Double, y:Double) in }) let sTwo = GenericConforms<(Double, Double)>() sTwo.takesClosure({ _ = $0 }) sTwo.takesClosure({ x in }) sTwo.takesClosure({ (x: (Double, Double)) in }) sTwo.takesClosure({ _ = $0; _ = $1 }) sTwo.takesClosure({ (x, y) in }) sTwo.takesClosure({ (x: Double, y: Double) in }) } do { let _: ((Int, Int)) -> () = { _ = $0 } let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) } let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) } let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }} let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0, $1) } let _: (Int, Int) -> () = { t, u in _ = (t, u) } } // rdar://problem/28952837 - argument labels ignored when calling function // with single 'Any' parameter func takesAny(_: Any) {} enum HasAnyCase { case any(_: Any) } do { let fn: (Any) -> () = { _ in } fn(123) fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}} takesAny(123) takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}} _ = HasAnyCase.any(123) _ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}} } // rdar://problem/29739905 - protocol extension methods on Array had // ParenType sugar stripped off the element type func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()], f2: [(Bool, Bool) -> ()], c: Bool) { let p = (c, c) f1.forEach { block in block(p) block((c, c)) block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}} } f2.forEach { block in // expected-note@-1 2{{'block' declared here}} block(p) // expected-error {{missing argument for parameter #2 in call}} block((c, c)) // expected-error {{missing argument for parameter #2 in call}} block(c, c) } f2.forEach { (block: ((Bool, Bool)) -> ()) in // expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> ()' to expected argument type '((Bool, Bool) -> ()) -> Void}} block(p) block((c, c)) block(c, c) } f2.forEach { (block: (Bool, Bool) -> ()) in // expected-note@-1 2{{'block' declared here}} block(p) // expected-error {{missing argument for parameter #2 in call}} block((c, c)) // expected-error {{missing argument for parameter #2 in call}} block(c, c) } } // expected-error@+1 {{cannot create a single-element tuple with an element label}} func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) { // TODO: Error could be improved. // expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}} completion((didAdjust: true)) } // SR-4378 final public class MutableProperty<Value> { public init(_ initialValue: Value) {} } enum DataSourcePage<T> { case notLoaded } let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: .notLoaded, totalCount: 0 )) let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage.notLoaded, totalCount: 0 )) let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage<Int>.notLoaded, totalCount: 0 )) // SR-4745 let sr4745 = [1, 2] let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" } // SR-4738 let sr4738 = (1, (2, 3)) [sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-error {{use of undeclared type 'y'}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }} // rdar://problem/31892961 let r31892961_1 = [1: 1, 2: 2] r31892961_1.forEach { (k, v) in print(k + v) } let r31892961_2 = [1, 2, 3] let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }} // expected-error@-2 {{use of undeclared type 'index'}} val + 1 } let r31892961_3 = (x: 1, y: 42) _ = [r31892961_3].map { (x: Int, y: Int) in x + y } _ = [r31892961_3].map { (x, y: Int) in x + y } let r31892961_4 = (1, 2) _ = [r31892961_4].map { x, y in x + y } let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4))) [r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y } // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }} let r31892961_6 = (x: 1, (y: 2, z: 4)) [r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y } // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }} // rdar://problem/32214649 -- these regressed in Swift 4 mode // with SE-0110 because of a problem in associated type inference func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] { return a.map(f) } func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] { return a.filter(f) } func r32214649_3<X>(_ a: [X]) -> [X] { return a.filter { _ in return true } } // rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters func rdar32301091_1(_ :((Int, Int) -> ())!) {} rdar32301091_1 { _ in } // expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '((Int, Int) -> ())?'}} func rdar32301091_2(_ :(Int, Int) -> ()) {} rdar32301091_2 { _ in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }} rdar32301091_2 { x in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }} func rdar32875953() { let myDictionary = ["hi":1] myDictionary.forEach { print("\($0) -> \($1)") } myDictionary.forEach { key, value in print("\(key) -> \(value)") } myDictionary.forEach { (key, value) in print("\(key) -> \(value)") } let array1 = [1] let array2 = [2] _ = zip(array1, array2).map(+) } struct SR_5199 {} extension Sequence where Iterator.Element == (key: String, value: String?) { func f() -> [SR_5199] { return self.map { (key, value) in SR_5199() // Ok } } } func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] { let x: [Int] = records.map { _ in let i = 1 return i } let y: [Int] = other.map { _ in let i = 1 return i } return x + y } func itsFalse(_: Int) -> Bool? { return false } func rdar33159366(s: AnySequence<Int>) { _ = s.compactMap(itsFalse) let a = Array(s) _ = a.compactMap(itsFalse) } func sr5429<T>(t: T) { _ = AnySequence([t]).first(where: { (t: T) in true }) } extension Concrete { typealias T = (Int, Int) typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } extension Generic { typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } func rdar33239714() { Concrete().opt1 { x, y in } Concrete().opt1 { (x, y) in } Concrete().opt2 { x, y in } Concrete().opt2 { (x, y) in } Concrete().opt3 { x, y in } Concrete().opt3 { (x, y) in } Concrete().optAliasT { x, y in } Concrete().optAliasT { (x, y) in } Concrete().optAliasF { x, y in } Concrete().optAliasF { (x, y) in } Generic<(Int, Int)>().opt1 { x, y in } Generic<(Int, Int)>().opt1 { (x, y) in } Generic<(Int, Int)>().opt2 { x, y in } Generic<(Int, Int)>().opt2 { (x, y) in } Generic<(Int, Int)>().opt3 { x, y in } Generic<(Int, Int)>().opt3 { (x, y) in } Generic<(Int, Int)>().optAliasT { x, y in } Generic<(Int, Int)>().optAliasT { (x, y) in } Generic<(Int, Int)>().optAliasF { x, y in } Generic<(Int, Int)>().optAliasF { (x, y) in } } // rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above" do { func foo(_: (() -> Void)?) {} func bar() -> ((()) -> Void)? { return nil } foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} } // https://bugs.swift.org/browse/SR-6509 public extension Optional { func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? { return self.flatMap { value in transform.map { $0(value) } } } func apply<Value, Result>(_ value: Value?) -> Result? where Wrapped == (Value) -> Result { return value.apply(self) } } // https://bugs.swift.org/browse/SR-6837 // FIXME: Can't overlaod local functions so these must be top-level func takePairOverload(_ pair: (Int, Int?)) {} // expected-note {{found this candidate}} func takePairOverload(_: () -> ()) {} // expected-note {{found this candidate}} do { func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {} func takePair(_ pair: (Int, Int?)) {} takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}} takeFn(fn: takePairOverload) // expected-error {{ambiguous reference to member 'takePairOverload'}} takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} } // https://bugs.swift.org/browse/SR-6796 do { func f(a: (() -> Void)? = nil) {} func log<T>() -> ((T) -> Void)? { return nil } f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} func logNoOptional<T>() -> (T) -> Void { } f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '(() -> Void)?'}} func g() {} g(()) // expected-error {{argument passed to call that takes no arguments}} func h(_: ()) {} // expected-note {{'h' declared here}} h() // expected-error {{missing argument for parameter #1 in call}} } // https://bugs.swift.org/browse/SR-7191 class Mappable<T> { init(_: T) { } func map<U>(_ body: (T) -> U) -> U { fatalError() } } let x = Mappable(()) _ = x.map { (_: Void) in return () } // https://bugs.swift.org/browse/SR-9470 do { func f(_: Int...) {} let _ = [(1, 2, 3)].map(f) // expected-error {{cannot invoke 'map' with an argument list of type '((Int...) -> ())'}} }
e364e7dd0acc79a9eea53d3a1e096757
30.797521
187
0.618038
false
false
false
false
rick1307/NeuronFun
refs/heads/master
Machine Learning/Connection.swift
mit
1
// // Connection.swift // Machine Learning // // Created by Rick Calvert on 8/22/15. // Copyright (c) 2015 Rick Calvert. All rights reserved. // import Foundation class Connection: NSObject { var connectionID: Int = 0 var connectionStrength: Double = 0.0 var connectionFrom: Neuron? var connectionTo: Neuron? init (connectionID: Int, connectionStrength: Double, connectionFrom: Neuron, connectionTo: Neuron) { // This line gives each instance of Neuron a unique name self.connectionID = ++self.connectionID self.connectionStrength = connectionStrength self.connectionFrom = connectionFrom self.connectionTo = connectionTo } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(connectionID, forKey: "connectionID") aCoder.encodeObject(connectionStrength, forKey: "connection Strength") aCoder.encodeObject(connectionFrom, forKey: "connectionFrom") aCoder.encodeObject(connectionTo, forKey: "connectionTo") } required init(coder aDecoder: NSCoder) { super.init() connectionID = aDecoder.decodeObjectForKey("connectionID") as! Int connectionStrength = aDecoder.decodeObjectForKey("connectionStrength") as! Double connectionFrom = aDecoder.decodeObjectForKey("connectionFrom") as? Neuron connectionTo = aDecoder.decodeObjectForKey("connectionTo") as? Neuron } }
63e2447d493624e391b09e267e8cfda2
32.454545
104
0.688647
false
false
false
false
kirsteins/BigInteger
refs/heads/master
Source/BigInteger.swift
mit
1
// // File.swift // BigInteger // // Created by Jānis Kiršteins on 16/09/14. // Copyright (c) 2014 Jānis Kiršteins. All rights reserved. // import LibTomMath extension mp_int { init() { self = mp_int(used: 0, alloc: 0, sign: 0, dp: nil) } } public class BigInteger : NSObject, IntegerLiteralConvertible { var value = mp_int() // MARK: - Init / Deinit init(var value: mp_int) { mp_init_copy(&self.value, &value) } public override init() { mp_init_set(&self.value, 0) } public init?(var valueAsString: String, radix: Int) { assert(radix >= 2 && radix <= 36, "Only radix from 2 to 36 are supported") super.init() valueAsString = valueAsString.uppercaseString if !(Utils.canParseBigIntegerFromString(valueAsString, withRadix: radix)) || valueAsString.isEmpty { return nil } let cString = valueAsString.cStringUsingEncoding(NSUTF8StringEncoding)! mp_read_radix(&self.value, cString, Int32(radix)) } public convenience init?(_ valueAsString: String) { self.init(valueAsString: valueAsString, radix: 10) } public convenience init(_ int: Int) { let bigInteger = BigInteger("\(int)")! self.init(bigInteger) } public required convenience init(integerLiteral value: IntegerLiteralType) { self.init(value) } public convenience init(_ bigInteger: BigInteger) { self.init(value: bigInteger.value) } public required init(coder aDecoder: NSCoder) { super.init() let alloc = aDecoder.decodeInt32ForKey(Keys.alloc) mp_init_size(&self.value, alloc) self.value.alloc = alloc self.value.used = aDecoder.decodeInt32ForKey(Keys.used) self.value.sign = aDecoder.decodeInt32ForKey(Keys.sign) let data = aDecoder.decodeObjectForKey(Keys.dp) as NSData var buffer = [mp_digit](count: Int(self.value.alloc), repeatedValue: 0) data.getBytes(&buffer) for var i = 0; i < Int(self.value.alloc); ++i { self.value.dp[i] = buffer[i] } } public func duplicate() -> BigInteger { return BigInteger(value: self.value) } deinit { mp_clear(&self.value); } // MARK: - Operations public func add(bigInteger: BigInteger) -> BigInteger { var sum = BigInteger() mp_add(&self.value, &bigInteger.value, &sum.value); return sum } public func add(primitiveInt: Int) -> BigInteger { return add(BigInteger(primitiveInt)) } public func subtract(bigInteger: BigInteger) -> BigInteger { var difference = BigInteger() mp_sub(&self.value, &bigInteger.value, &difference.value); return difference } public func subtract(primitiveInt: Int) -> BigInteger { return subtract(BigInteger(primitiveInt)) } public func multiplyBy(bigInteger: BigInteger) -> BigInteger { var product = BigInteger() mp_mul(&self.value, &bigInteger.value, &product.value); return product } public func multiplyBy(primitiveInt: Int) -> BigInteger { return multiplyBy(BigInteger(primitiveInt)) } public typealias QuotientAndReminder = (quotient: BigInteger, reminder: BigInteger) public func divideAndRemainder(bigInteger: BigInteger) -> QuotientAndReminder? { var quotient = BigInteger() var remainder = BigInteger() let result = mp_div(&self.value, &bigInteger.value, &quotient.value, &remainder.value) if result == MP_VAL { return nil } return (quotient, remainder) } public func divideAndRemainder(primitiveInt: Int) -> QuotientAndReminder? { return divideAndRemainder(BigInteger(primitiveInt)) } public func divideBy(bigInteger: BigInteger) -> BigInteger? { return divideAndRemainder(bigInteger)?.quotient } public func divideBy(primitiveInt: Int) -> BigInteger? { return divideBy(BigInteger(primitiveInt)) } public func reminder(bigInteger: BigInteger) -> BigInteger? { return divideAndRemainder(bigInteger)?.reminder } public func reminder(primitiveInt: Int) -> BigInteger? { return reminder(BigInteger(primitiveInt)) } public func pow(exponent: mp_digit) -> BigInteger { var power = BigInteger() mp_expt_d(&self.value, exponent, &power.value); return power } public func negate() -> BigInteger { var negated = BigInteger() mp_neg(&self.value, &negated.value) return negated } public func abs() -> BigInteger { var absolute = BigInteger() mp_abs(&self.value, &absolute.value) return absolute } public func bitwiseXor(bigInteger: BigInteger) -> BigInteger { var xor = BigInteger() mp_xor(&self.value, &bigInteger.value, &xor.value); return xor } public func bitwiseXor(primitiveInt: Int) -> BigInteger { return bitwiseXor(BigInteger(primitiveInt)) } public func bitwiseOr(bigInteger: BigInteger) -> BigInteger { var or = BigInteger() mp_or(&self.value, &bigInteger.value, &or.value); return or } public func bitwiseOr(primitiveInt: Int) -> BigInteger { return bitwiseOr(BigInteger(primitiveInt)) } public func bitwiseAnd(bigInteger: BigInteger) -> BigInteger { var and = BigInteger() mp_and(&self.value, &bigInteger.value, &and.value); return and } public func bitwiseAnd(primitiveInt: Int) -> BigInteger { return bitwiseAnd(BigInteger(primitiveInt)) } public func shiftLeft(placesToShift: Int32) -> BigInteger { var leftShifted = BigInteger() mp_mul_2d(&self.value, placesToShift, &leftShifted.value) return leftShifted } public func shiftRight(placesToShift: Int32) -> BigInteger { var rightShifted = BigInteger() mp_div_2d(&self.value, placesToShift, &rightShifted.value, nil) return rightShifted } public func gcd(bigInteger: BigInteger) -> BigInteger? { var gcd = BigInteger() let result = mp_gcd(&self.value, &bigInteger.value, &gcd.value) if result == MP_VAL { return nil } return gcd } public func gcd(primitiveInt: Int) -> BigInteger? { return gcd(BigInteger(primitiveInt)) } public func compare(bigInteger: BigInteger) -> NSComparisonResult { let comparisonResult = mp_cmp(&self.value, &bigInteger.value) switch comparisonResult { case MP_GT: return .OrderedAscending case MP_LT: return .OrderedDescending default: return .OrderedSame } } // MARK: - Output public var asInt: Int? { return (self <= Int.max && self >= Int.min) ? Int(mp_get_int(&self.value)) : nil } public var asString: String { return asString(radix: 10) } public func asString(#radix: Int) -> String { assert(radix >= 2 && radix <= 36, "Only radix from 2 to 36 are supported") var stringLength = Int32() mp_radix_size(&self.value, Int32(radix), &stringLength) var cString = [Int8](count: Int(stringLength), repeatedValue: 0) mp_toradix(&self.value, &cString, Int32(radix)) return NSString(UTF8String: cString)! } public var bytesCount: Int { return Int(mp_unsigned_bin_size(&self.value)) } public var byteArray: [Byte] { var buffer = [Byte](count: bytesCount, repeatedValue: 0) mp_to_signed_bin(&self.value, &buffer) return buffer } } // MARK: - Printable extension BigInteger: Printable { public override var description: String { return asString } } // MARK: - Hashable extension BigInteger: Hashable { public override var hashValue: Int { return asString.hashValue } } // MARK: - NSCoding extension BigInteger: NSCoding { struct Keys { static let dp = "dp" static let alloc = "alloc" static let used = "used" static let sign = "sign" } public func encodeWithCoder(aCoder: NSCoder) { mp_clamp(&self.value) let data = NSData( bytes: self.value.dp, length: Int(self.value.alloc) * sizeof(mp_digit) ) aCoder.encodeObject(data, forKey: Keys.dp) aCoder.encodeInt32(self.value.alloc, forKey: Keys.alloc) aCoder.encodeInt32(self.value.used, forKey: Keys.used) aCoder.encodeInt32(self.value.sign, forKey: Keys.sign) } } // MARK: - NSCopying extension BigInteger: NSCopying { public func copyWithZone(zone: NSZone) -> AnyObject { return self.duplicate() } } // MARK: - Comparable, Equatable extension BigInteger: Comparable, Equatable {} public func == (lhs: BigInteger, rhs: BigInteger) -> Bool { return (lhs.compare(rhs) == .OrderedSame) } public func <= (lhs: BigInteger, rhs: BigInteger) -> Bool { return (lhs.compare(rhs) != .OrderedAscending) } public func >= (lhs: BigInteger, rhs: BigInteger) -> Bool { return (lhs.compare(rhs) != .OrderedDescending) } public func > (lhs: BigInteger, rhs: BigInteger) -> Bool { return (lhs.compare(rhs) == .OrderedAscending) } public func < (lhs: BigInteger, rhs: BigInteger) -> Bool { return (lhs.compare(rhs) == .OrderedDescending) }
17b9faa22d319d742cfbfe0087f612a0
26.695531
108
0.599899
false
false
false
false
trident10/TDMediaPicker
refs/heads/master
TDMediaPicker/Classes/Utils/TDMediaUtil/TDMediaUtil+MediaPermission.swift
mit
1
// // TDMediaUtil+MediaPermission.swift // ImagePicker // // Created by Abhimanu Jindal on 18/07/17. // Copyright © 2017 Abhimanu Jindal. All rights reserved. // import Foundation import Photos extension (TDMediaUtil){ static func hasPermission(accessType : MediaPermissionType) -> Bool { switch accessType { case .Microphone: return isMicAvailable() case .Camera: return isCameraAvailable() case .Gallery: return isGalleryAvailable() } } static func requestForHardwareAccess(accessType : MediaPermissionType, completionBlock: @escaping (_ isGranted: Bool)-> Void) { switch accessType { case .Camera: AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (isGranted) in completionBlock(isGranted) }) case .Microphone: AVCaptureDevice.requestAccess(for: AVMediaType.audio, completionHandler: { (isGranted) in completionBlock(isGranted) }) case .Gallery: PHPhotoLibrary.requestAuthorization({ (authorizationStatus) in if authorizationStatus == .authorized { completionBlock(true) } else{ completionBlock(false) } }) } } //MARK:- Checking User Access private static func isMicAvailable()-> Bool{ if AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) == AVAuthorizationStatus.authorized { return true } else{ return false } } private static func isCameraAvailable()-> Bool{ if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == AVAuthorizationStatus.authorized { return true } else{ return false } } private static func isGalleryAvailable()-> Bool{ let authorizationStatus :PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus() switch authorizationStatus { case .authorized: return true case .notDetermined: return false default: return false } } }
29107213f82b41ea35ef8d517f7a8776
26.430233
129
0.571005
false
false
false
false
bhajian/raspi-remote
refs/heads/master
raspi-remote/FirstViewController.swift
mit
1
// // FirstViewController.swift // raspi-remote // // Created by behnam hajian on 2016-07-13. // Copyright © 2016 behnam hajian. All rights reserved. // import UIKit import TextToSpeechV1 import AVFoundation import SpeechToTextV1 import Foundation class FirstViewController: UIViewController { var player: AVAudioPlayer? var captureSession: AVCaptureSession? var recorder: AVAudioRecorder! @IBOutlet weak var transcribedLabel: UILabel! var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) var baseServiceUrl = "http://behnam.mybluemix.net/" override func viewDidLoad() { super.viewDidLoad() let document = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let fileName = "speechToTextRecording.wav" let filePath = NSURL(fileURLWithPath: document + "/" + fileName) let session = AVAudioSession.sharedInstance() var settings = [String: AnyObject] () settings[AVSampleRateKey] = NSNumber(float: 44100.0) settings[AVNumberOfChannelsKey] = NSNumber(int: 1) do{ try session.setCategory(AVAudioSessionCategoryPlayAndRecord) recorder = try AVAudioRecorder(URL: filePath, settings: settings) } catch{ } guard let recorder = recorder else { return } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func listenTouchDown(sender: UIButton) { if (!recorder.recording) { do { let session = AVAudioSession.sharedInstance() try session.setActive(true) recorder.record() sender.alpha = 1 } catch { } } else { do { recorder.stop() sender.alpha = 0.5 let session = AVAudioSession.sharedInstance() try session.setActive(false) let username = "87bb86cb-61a5-4742-afec-26a7f23c592e" let password = "FxxzwmJ5Dgrj" let speechToText = SpeechToText(username: username, password: password) let settings = TranscriptionSettings(contentType: .WAV) let failure = { (error: NSError) in print(error) } speechToText.transcribe(recorder.url, settings: settings, failure: failure){ result in if let transcription = result.last?.alternatives.last?.transcript{ self.transcribedLabel.text = transcription let command = transcription.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).lowercaseString if(command == "forward"){ self.forwardTouchInside(sender) } if(command == "backward"){ self.backwardTouchInside(sender) } if(command == "turn left"){ self.leftTouchInside(sender) } if(command == "turn right"){ self.rightTouchInside(sender) } if(command == "stop"){ self.stopTouchInside(sender) } if(command == "camera up"){ self.stopTouchInside(sender) } if(command == "camera down"){ self.stopTouchInside(sender) } if(command == "camera laft"){ self.stopTouchInside(sender) } if(command == "camera right"){ self.stopTouchInside(sender) } } } } catch {} } } private func makeGetRequest(request: NSURLRequest){ let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if let data = data { let response = NSString(data: data, encoding: NSUTF8StringEncoding) print(response) } } task.resume() } @IBAction func forwardTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/goForward")!) makeGetRequest(request); } @IBAction func backwardTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/goBackward")!) makeGetRequest(request); } @IBAction func rightTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/turnRight/coarse")!) makeGetRequest(request); } @IBAction func leftTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/turnLeft/coarse")!) makeGetRequest(request); } @IBAction func directionStreightTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/home")!) makeGetRequest(request); } @IBAction func stopTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/stop")!) makeGetRequest(request); } @IBAction func speedValueChanged(sender: UISlider) { let selectedValue = Int(sender.value) let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "car/setSpeed/" + String(selectedValue))!) makeGetRequest(request); } @IBAction func cameraUpTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/up")!) makeGetRequest(request); } @IBAction func cameraDownTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/down")!) makeGetRequest(request); } @IBAction func cameraRightTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/right")!) makeGetRequest(request); } @IBAction func cameraLeftTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/left")!) makeGetRequest(request); } @IBAction func cameraHomeTouchInside(sender: AnyObject) { let request = NSURLRequest(URL: NSURL(string: baseServiceUrl + "camera/home")!) makeGetRequest(request); } }
36c337d51098190fb5ab2477e70f6a6f
35.233161
140
0.566567
false
false
false
false
SandroMachado/SwiftClient
refs/heads/master
SwiftClient/Response.swift
mit
2
// // Response.swift // SwiftClient // // Created by Adam Nalisnick on 10/30/14. // Copyright (c) 2014 Adam Nalisnick. All rights reserved. // import Foundation public class Response{ public var text: String?; public var data: NSData?; public var body: AnyObject?; public var type: String?; public var charset: String?; public let status: Int; public let statusType: Int; public let info: Bool; public let ok: Bool; public let clientError: Bool; public let serverError: Bool; public let error: Bool; public let accepted: Bool; public let noContent: Bool; public let badRequest: Bool; public let unauthorized: Bool; public let notAcceptable: Bool; public let notFound: Bool; public let forbidden: Bool; public let request:Request; public var headers: [String : String]; private func trim(s:String) -> String{ return s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()); } private func splitContentParams(params: [String]) -> [String : String]{ return params.reduce(Dictionary(), combine: {(var map: [String : String], pair: String) -> [String : String] in var pairArray = pair.componentsSeparatedByString("="); if(pairArray.count == 2){ map.updateValue(self.trim(pairArray[1]), forKey: self.trim(pairArray[0]).lowercaseString) } return map; }); } init(_ response: NSHTTPURLResponse, _ request: Request, _ rawData: NSData?){ self.request = request; let status = response.statusCode; let type = response.statusCode / 100 | 0; // status / class self.status = status; self.statusType = type; // basics self.info = 1 == type; self.ok = 2 == type; self.clientError = 4 == type; self.serverError = 5 == type; self.error = 4 == type || 5 == type; // sugar self.accepted = 202 == status; self.noContent = 204 == status self.badRequest = 400 == status; self.unauthorized = 401 == status; self.notAcceptable = 406 == status; self.notFound = 404 == status; self.forbidden = 403 == status; // header filling headers = Dictionary(); for (key, value) in response.allHeaderFields { headers.updateValue(value.description, forKey: key.description.lowercaseString); } if let type = headers["content-type"] { var typeArray = type.componentsSeparatedByString(";"); self.type = trim(typeArray.removeAtIndex(0)); let params = splitContentParams(typeArray); self.charset = params["charset"]; } self.data = rawData; self.body = rawData; if let data = rawData { self.text = dataToString(data); if let type = self.type { if let parser = parsers[type] { self.body = parser(data, self.text!); } } } } }
fcb6f78552e8f62399c87591f38630b9
28.394495
119
0.570849
false
false
false
false
danielallsopp/Charts
refs/heads/master
Source/ChartsRealm/Data/RealmCandleDataSet.swift
apache-2.0
1
// // RealmCandleDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if NEEDS_CHARTS import Charts #endif import Realm import Realm.Dynamic public class RealmCandleDataSet: RealmLineScatterCandleRadarDataSet, ICandleChartDataSet { public override func initialize() { } public required init() { super.init() } public init(results: RLMResults?, highField: String, lowField: String, openField: String, closeField: String, xIndexField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(results: results, yValueField: "", xIndexField: xIndexField, label: label) } public convenience init(results: RLMResults?, highField: String, lowField: String, openField: String, closeField: String, xIndexField: String) { self.init(results: results, highField: highField, lowField: lowField, openField: openField, closeField: closeField, xIndexField: xIndexField, label: "DataSet") } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, highField: String, lowField: String, openField: String, closeField: String, xIndexField: String, label: String?) { _highField = highField _lowField = lowField _openField = openField _closeField = closeField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: "", xIndexField: xIndexField, label: label) } // MARK: - Data functions and accessors internal var _highField: String? internal var _lowField: String? internal var _openField: String? internal var _closeField: String? internal override func buildEntryFromResultObject(object: RLMObject, atIndex: UInt) -> ChartDataEntry { let entry = CandleChartDataEntry( xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int, shadowH: object[_highField!] as! Double, shadowL: object[_lowField!] as! Double, open: object[_openField!] as! Double, close: object[_closeField!] as! Double) return entry } public override func calcMinMax(start start: Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } ensureCache(start, end: endValue) if _cache.count == 0 { return } _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for i in start.stride(through: endValue, by: 1) { let e = _cache[i - _cacheFirst] as! CandleChartDataEntry if (e.low < _yMin) { _yMin = e.low } if (e.high > _yMax) { _yMax = e.high } } } // MARK: - Styling functions and accessors /// the space between the candle entries /// /// **default**: 0.1 (10%) private var _barSpace = CGFloat(0.1) /// the space that is left out on the left and right side of each candle, /// **default**: 0.1 (10%), max 0.45, min 0.0 public var barSpace: CGFloat { set { if (newValue < 0.0) { _barSpace = 0.0 } else if (newValue > 0.45) { _barSpace = 0.45 } else { _barSpace = newValue } } get { return _barSpace } } /// should the candle bars show? /// when false, only "ticks" will show /// /// **default**: true public var showCandleBar: Bool = true /// the width of the candle-shadow-line in pixels. /// /// **default**: 3.0 public var shadowWidth = CGFloat(1.5) /// the color of the shadow line public var shadowColor: NSUIColor? /// use candle color for the shadow public var shadowColorSameAsCandle = false /// Is the shadow color same as the candle color? public var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle } /// color for open == close public var neutralColor: NSUIColor? /// color for open > close public var increasingColor: NSUIColor? /// color for open < close public var decreasingColor: NSUIColor? /// Are increasing values drawn as filled? /// increasing candlesticks are traditionally hollow public var increasingFilled = false /// Are increasing values drawn as filled? public var isIncreasingFilled: Bool { return increasingFilled } /// Are decreasing values drawn as filled? /// descreasing candlesticks are traditionally filled public var decreasingFilled = true /// Are decreasing values drawn as filled? public var isDecreasingFilled: Bool { return decreasingFilled } }
442d9bb107b0ed1072c8d401f5e57b56
26.717822
187
0.575817
false
false
false
false
iitjee/SteppinsSwift
refs/heads/master
Optionals.swift
apache-2.0
1
/* */ /* Optional Chaining as an alternative to Forced Unwrapping */ linkedListNode!.next() //here, if linkedListNode is nil, forced unwrapping triggers a runtime error linkedListNode?.next() //here, if linkedListNode is nil, optional chaining fails gracefully and next() is simply not called //NOTE: To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, **even if the property, method, or subscript you are querying returns a nonoptional value**. //eg: A property that normally returns an Int will now return an Int? when accessed through optional chaining. (i.e Int is now wrapped in an optional) class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() //Forced Unwrapping let roomCount = john.residence!.numberOfRooms // this triggers a runtime error since residence is always nil //Optional Chaining along with optional binding if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } // Prints "Unable to retrieve the number of rooms." //Note again: The fact that numberOfRooms is queried through an optional chain means that the call to numberOfRooms will always return an Int? instead of an Int. john.residence = Residence() //john.residence now contains an actual Residence instance, rather than nil. if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } // Prints "John's residence has 1 room(s)."
b20014e985832a688f0c8164e3f44b0b
23.742857
242
0.732679
false
false
false
false
10533176/TafelTaferelen
refs/heads/master
Tafel Taferelen/NewGroupViewController.swift
mit
1
// // NewGroupViewController.swift // Tafel Taferelen // // Created by Femke van Son on 16-01-17. // Copyright © 2017 Femke van Son. All rights reserved. // import UIKit import Firebase class NewGroupViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var groupsName: UITextField! @IBOutlet weak var newGroupMember: UITextField! @IBOutlet weak var createGroupBtn: UIButton! @IBOutlet weak var newGroupMemBtn: UIButton! @IBOutlet weak var tableView: UITableView! var ref: FIRDatabaseReference! var memberEmails = [String]() var memberIDs = [String]() var memberNames = [String]() var memberProfpic = [String]() var groupEmails = [String]() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isTranslucent = true ref = FIRDatabase.database().reference() self.hideKeyboardWhenTappedAroung() tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Functions to find new member, check if he/ she is not allready in group, if not -> diplaying user information @IBAction func newGroupMemberAdded(_ sender: Any) { if newGroupMember.text != " " { if memberIDs.count < 11 { AppDelegate.instance().showActivityIndicator() findNewUser() } else { self.signupErrorAlert(title: "Oops!", message: "Maximum of ten members in group is reached") } } else { self.signupErrorAlert(title: "Oops!", message: "Fill in email adress to add new member to the group!") } } func doneLoading() { AppDelegate.instance().dismissActivityIndicator() } func findNewUser() { self.groupEmails = [""] self.ref?.child("emailDB").observeSingleEvent(of: .value, with: { (snapshot) in let dictionary = snapshot.value as? NSDictionary if dictionary != nil { let tempKeys = dictionary?.allKeys as! [String] for keys in tempKeys { self.ref?.child("emailDB").child(keys).observeSingleEvent(of: .value, with: { (snapshot) in let email = snapshot.value as! String self.groupEmails.append(email) if self.groupEmails.count == tempKeys.count { self.newUserNotFound() } if email == self.newGroupMember.text { self.newUserFound(newUserID: keys) } }) } } }) } func newUserNotFound() { if self.groupEmails.contains(newGroupMember.text!) == false { self.doneLoading() self.signupErrorAlert(title: "Oops!", message: "We do not have any users with this e-mail address") } } func newUserFound(newUserID: String) { self.ref?.child("users").child(newUserID).child("groupID").observeSingleEvent(of: .value, with: {(snapshot) in let checkCurrentGroup = snapshot.value as? String if checkCurrentGroup == nil { self.findDataNewUser() } else { self.doneLoading() self.signupErrorAlert(title: "Oops, user allready in group!", message: "This member is already having dinner with other friends.. Try if someone else will have dinner with you!") self.newGroupMember.text = "" } }) } func findDataNewUser() { self.ref?.child("emailDB").observeSingleEvent(of: .value, with: { (snapshot) in let dictionary = snapshot.value as? NSDictionary if dictionary != nil { let tempKeys = dictionary?.allKeys as! [String] for keys in tempKeys { self.ref?.child("emailDB").child(keys).observeSingleEvent(of: .value, with: { (snapshot) in let email = snapshot.value as! String if email == self.newGroupMember.text { self.displayNewUser(newUserID: keys) } }) } } else { self.doneLoading() } }) } func displayNewUser(newUserID: String) { self.ref?.child("users").child(newUserID).child("full name").observeSingleEvent(of: .value, with: {(snapshot) in let name = snapshot.value as! String self.memberNames.append(name) }) self.ref?.child("users").child(newUserID).child("urlToImage").observeSingleEvent(of: .value, with: {(snapshot) in let url = snapshot.value as! String self.memberProfpic.append(url) self.tableView.reloadData() }) self.doneLoading() self.memberEmails.append(self.newGroupMember.text!) self.memberIDs.append(newUserID) self.newGroupMember.text = "" } @IBAction func createNewGroupPressed(_ sender: Any) { let groupID = self.ref?.child("groups").childByAutoId().key if groupsName.text != "" { self.ref?.child("groups").child(groupID!).child("name").setValue(groupsName.text) saveCurrentUserAsNewMember(groupID: groupID!) self.noGroupErrorAlert(title: "Yay!", message: "welcome to the club \(groupsName.text!)") } else { self.signupErrorAlert(title: "Oops!", message: "You forgot to fill in a groupsname") } } // MARK: Saving new users to DataBase func saveCurrentUserAsNewMember(groupID: String) { let userID = FIRAuth.auth()?.currentUser?.uid self.ref?.child("users").child(userID!).child("email").observeSingleEvent(of: .value, with: { (snapshot) in let emailCurrentUser = snapshot.value as! String self.memberEmails.append(emailCurrentUser) self.memberIDs.append(userID!) self.ref?.child("groups").child(groupID).child("members").child("email").setValue(self.memberEmails) self.ref?.child("groups").child(groupID).child("members").child("userid").setValue(self.memberIDs) let tableSetting = ["", "", "", "", "", "", "", "", "", ""] self.ref?.child("groups").child(groupID).child("tableSetting").setValue(tableSetting) for keys in self.memberIDs { self.ref?.child("users").child(keys).child("groupID").setValue(groupID) } }) } // MARK: functions to show table view properly func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memberNames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NewGroupTableViewCell cell.newGroupMemberDisplay.text = self.memberNames[indexPath.row] if let url = NSURL(string: self.memberProfpic[indexPath.row]) { if let data = NSData(contentsOf: url as URL) { cell.newGroupMemberProfPic.image = UIImage(data: data as Data) } } return cell } }
40d24fe98e3f4f0b815f58c28a354295
37.166667
194
0.556956
false
false
false
false
soapyigu/LeetCode_Swift
refs/heads/master
Array/ValidSudoku.swift
mit
1
/** * Question Link: https://leetcode.com/problems/valid-sudoku/ * Primary idea: Check rows, columns, and single square separately * * Time Complexity: O(n^2), Space Complexity: O(n) */ class ValidSudoku { let size = 9 func isValidSudoku(board: [[Character]]) -> Bool { return _isRowValid(board) && _isColValid(board) && _isSquareValid(board) } private func _isRowValid(board: [[Character]]) -> Bool { var visited = Array(count: size, repeatedValue: false) for i in 0..<size { visited = Array(count: size, repeatedValue: false) for j in 0..<size { if !_isValidChar(board[i][j], &visited) { return false } } } return true } private func _isColValid(board: [[Character]]) -> Bool { var visited = Array(count: size, repeatedValue: false) for i in 0..<size { visited = Array(count: size, repeatedValue: false) for j in 0..<size { if !_isValidChar(board[j][i], &visited) { return false } } } return true } private func _isSquareValid(board: [[Character]]) -> Bool { var visited = Array(count: size, repeatedValue: false) for i in 0.stride(to: size, by: 3) { for j in 0.stride(to: size, by: 3) { visited = Array(count: size, repeatedValue: false) for m in i..<i + 3 { for n in j..<j + 3 { if !_isValidChar(board[m][n], &visited) { return false } } } } } return true } private func _isValidChar(char: Character, inout _ visited: [Bool]) -> Bool { let current = String(char) if current != "." { if let num = Int(current){ if num < 1 || num > 9 || visited[num - 1] { return false } else { visited[num - 1] = true } } else { return false } } return true } }
7bdf40b3bb995edb68e4f73bda41dd97
27.691358
81
0.446406
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/Math/338_CountingBits.swift
mit
1
// // 338_CountingBits.swift // LeetcodeSwift // // Created by yansong li on 2016-11-12. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:338 Counting Bits URL: https://leetcode.com/problems/counting-bits/ Space: O(N) Time: O(N) */ class CountingBits_Solution { func countBits(_ num: Int) -> [Int] { guard num > 0 else { return [0] } var result = Array(repeating: 0, count: num + 1) var x = 1 for i in 1...num { if i == x { x = x << 1 result[i] = 1 } else { result[i] = result[i - (x >> 1)] + 1 } } return result } }
c8a36da725dc16709e7792f5296851a8
17.4
53
0.545031
false
false
false
false
cozkurt/coframework
refs/heads/main
COFramework/COFramework/Swift/Components/Helpers/DictionaryHelper.swift
gpl-3.0
1
// // DictionaryHelper.swift // FuzFuz // // Created by Cenker Ozkurt on 01/06/20. // Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved. // import Foundation protocol DictionaryHelper { func toDict() -> [String:String] func JSONString() -> String? } extension DictionaryHelper { func toDict() -> [String:String] { var dict = [String:String]() let otherSelf = Mirror(reflecting: self) for child in otherSelf.children { if let key = child.label { dict[key] = "\(child.value)" } } return dict } func JSONString() -> String? { do { let jsonData = try JSONSerialization.data(withJSONObject: self.toDict(), options: JSONSerialization.WritingOptions(rawValue: UInt(0))) return String(data: jsonData, encoding: String.Encoding.utf8) } catch let error { print("error converting to json: \(error)") return nil } } }
21371c6922e15921dec520bf14d0138f
25.025641
146
0.57931
false
false
false
false
exyte/Macaw-Examples
refs/heads/master
AnimationPrinciples/AnimationPrinciples/Examples/FocusViewController.swift
mit
1
// // FocusViewController.swift // Animations // // Created by Alisa Mylnikova on 08/08/2018. // Copyright © 2018 Exyte. All rights reserved. // import Macaw class FocusViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() let radius = 20.0 let rect = Shape( form: RoundRect(rect: Rect(x: 0, y: 0, w: 100, h: 100), rx: 5, ry: 5), fill: color, place: .move(dx: 50, dy: 100) ) let innerCircle = Shape(form: Circle(cx: 0, cy: 0, r: radius), fill: color, place: .move(dx: 250, dy: 50)) let innerAnimation = innerCircle.placeVar.animation(to: innerCircle.place.scale(sx: 0.9, sy: 0.9), during: 0.4).autoreversed() let outerCircle = Shape(form: Circle(cx: 0, cy: 0, r: radius), fill: color) let outerGroup = Group(contents: [outerCircle], place: .move(dx: 250, dy: 50)) let outerAnimation = outerGroup.contentsVar.animation({ t in let newColor = color.with(a: 1 - t) return [Circle(r: (1 + t) * radius).fill(with: newColor)] }, during: 0.8) animation = [innerAnimation, outerAnimation].combine().cycle() svgView.node = [rect, innerCircle, outerGroup].group() } }
1ca8eebae6af2e2be2b43813e3d07755
33.289474
134
0.585572
false
false
false
false
OrdnanceSurvey/OS-Maps-API
refs/heads/master
Sample Code/OS API Response -Swift/OSAPIResponse/Fetch.Parsable+Parsing.swift
apache-2.0
1
// // Fetch.Parsable+Parsing.swift // OSAPIResponse // // Created by Dave Hardiman on 15/03/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import Fetch import OSJSON extension Fetch.Parsable where Self: OSAPIResponse.Parsable { public static func parse(fromData data: NSData?, withStatus status: Int) -> Result<Self> { guard let data = data else { return .Failure(ResponseError.NoDataReceived) } guard let json = JSON(data: data) else { return .Failure(ResponseError.FailedToParseJSON) } switch status { case 200: return parseExpectedResponse(json) case 400: return .Failure(ResponseError.BadRequest(messageFromErrorBody(json))) case 401: return .Failure(ResponseError.Unauthorised(messageFromErrorBody(json))) case 404: return .Failure(ResponseError.NotFound(messageFromErrorBody(json))) case 405: return .Failure(ResponseError.MethodNotAllowed(messageFromErrorBody(json))) case 406: return .Failure(ResponseError.NotAcceptable(messageFromErrorBody(json))) case 500: return .Failure(ResponseError.ServerError(messageFromErrorBody(json))) default: return .Failure(ResponseError.UnknownError) } } private static func parseExpectedResponse(json: JSON) -> Result<Self> { guard let response = Self.create(json) else { return .Failure(ResponseError.FailedToDeserialiseJSON) } return .Success(response) } } private func messageFromErrorBody(json: JSON) -> String { if let error = json.jsonForKey("error"), message = error.stringValueForKey("message") { return message } if let fault = json.jsonForKey("fault"), message = fault.stringValueForKey("faultstring") { return message } if let errorResponse = json.jsonForKey("ErrorResponse") { return messageFromErrorBody(errorResponse) } return "" }
6b7ee0d60e7c247196cb27c0a052db67
33.032787
94
0.649807
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Filters/String Resonator/AKStringResonator.swift
mit
1
// // AKStringResonator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// AKStringResonator passes the input through a network composed of comb, /// low-pass and all-pass filters, similar to the one used in some versions of /// the Karplus-Strong algorithm, creating a string resonator effect. The /// fundamental frequency of the “string” is controlled by the /// fundamentalFrequency. This operation can be used to simulate sympathetic /// resonances to an input signal. /// /// - parameter input: Input node to process /// - parameter fundamentalFrequency: Fundamental frequency of string. /// - parameter feedback: Feedback amount (value between 0-1). A value close to 1 creates a slower decay and a more pronounced resonance. Small values may leave the input signal unaffected. Depending on the filter frequency, typical values are > .9. /// public class AKStringResonator: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKStringResonatorAudioUnit? internal var token: AUParameterObserverToken? private var fundamentalFrequencyParameter: AUParameter? private var feedbackParameter: AUParameter? /// Fundamental frequency of string. public var fundamentalFrequency: Double = 100 { willSet(newValue) { if fundamentalFrequency != newValue { fundamentalFrequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// Feedback amount (value between 0-1). A value close to 1 creates a slower decay and a more pronounced resonance. Small values may leave the input signal unaffected. Depending on the filter frequency, typical values are > .9. public var feedback: Double = 0.95 { willSet(newValue) { if feedback != newValue { feedbackParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter fundamentalFrequency: Fundamental frequency of string. /// - parameter feedback: Feedback amount (value between 0-1). A value close to 1 creates a slower decay and a more pronounced resonance. Small values may leave the input signal unaffected. Depending on the filter frequency, typical values are > .9. /// public init( _ input: AKNode, fundamentalFrequency: Double = 100, feedback: Double = 0.95) { self.fundamentalFrequency = fundamentalFrequency self.feedback = feedback var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x73747265 /*'stre'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKStringResonatorAudioUnit.self, asComponentDescription: description, name: "Local AKStringResonator", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKStringResonatorAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } fundamentalFrequencyParameter = tree.valueForKey("fundamentalFrequency") as? AUParameter feedbackParameter = tree.valueForKey("feedback") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.fundamentalFrequencyParameter!.address { self.fundamentalFrequency = Double(value) } else if address == self.feedbackParameter!.address { self.feedback = Double(value) } } } fundamentalFrequencyParameter?.setValue(Float(fundamentalFrequency), originator: token!) feedbackParameter?.setValue(Float(feedback), originator: token!) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
07abbf1c0120368dc5fd1a82d45721e7
38.507813
253
0.667787
false
false
false
false
hooliooo/Rapid
refs/heads/master
Source/Classes/Collections/SynchronizedDictionary.swift
mit
1
// // Kio // Copyright (c) Julio Miguel Alorro // // Licensed under the MIT license. See LICENSE file. // // import class Foundation.DispatchQueue import struct Foundation.DispatchWorkItemFlags public class SynchronizedDictionary<Key: Hashable, Value> { /** The initializer - parameter dict: Dictionary instance to be managed */ public init(dict: [Key: Value]) { self.dict = dict } /** The queue that handles the read/writes to the dictionary instance. */ private let _queue: DispatchQueue = DispatchQueue( label: "SynchronizedDictionary", attributes: DispatchQueue.Attributes.concurrent ) /** The dictionary instance. */ private var dict: [Key: Value] // MARK: Computed Properties /** The DispatchQueue instance used by the SynchronizedDictionary instance */ public var queue: DispatchQueue { return self._queue } } // MARK: - Read Properties & Methods public extension SynchronizedDictionary { /** Synchronous read of the dictionary's count property. */ var count: Int { var count: Int = 0 self._queue.sync { count = self.dict.count } return count } /** Synchronous read of the dictionary's first property. */ var first: (key: Key, value: Value)? { var first: (key: Key, value: Value)? self._queue.sync { first = self.dict.first } return first } /** Synchronous read of the dictionary's isEmpty property. */ var isEmpty: Bool { var isEmpty: Bool = true self._queue.sync { isEmpty = self.dict.isEmpty } return isEmpty } /** Synchronous read of the dictionary's key property. */ var keys: Dictionary<Key, Value>.Keys { return self._queue.sync { return self.dict.keys } } /** Synchronous read of the dictionary's underestimatedCount property. */ var underestimatedCount: Int { var underestimatedCount: Int = 0 self._queue.sync { underestimatedCount = self.dict.underestimatedCount } return underestimatedCount } /** Synchronous read of the dictionary's values property. */ var values: Dictionary<Key, Value>.Values { return self._queue.sync { return self.dict.values } } /** Synchronous read of the dictionary's contains method. */ func contains(where predicate: (Key, Value) throws -> Bool) rethrows -> Bool { var contains: Bool = false try self._queue.sync { do { contains = try self.dict.contains(where: predicate) } catch let error { throw error } } return contains } /** Synchronous read of the dictionary's enumerated method. */ func enumerated() -> EnumeratedSequence<Dictionary<Key, Value>> { // swiftlint:disable:this syntactic_sugar return self._queue.sync { return self.dict.enumerated() } } /** Synchronous read of the dictionary's filter method. */ func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [(key: Key, value: Value)] { var filtered: [(key: Key, value: Value)] = [] try self._queue.sync { do { filtered = try self.dict.filter(isIncluded) } catch let error { throw error } } return filtered } /** Synchronous read of the dictionary's first method. */ func first(where predicate: ((key: Key, value: Value)) throws -> Bool) rethrows -> (key: Key, value: Value)? { var first: (key: Key, value: Value)? try self._queue.sync { do { first = try self.dict.first(where: predicate) } catch let error { throw error } } return first } /** Synchronous read of the dictionary's flatMap<ElementOfResult> method. */ func flatMap<ElementOfResult>(_ transform: (Key, Value) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] try self._queue.sync { do { result = try self.dict.compactMap(transform) } catch let error { throw error } } return result } /** Synchronous read of the dictionary's flatMap<SegmentOfResult> method. */ func flatMap<SegmentOfResult : Sequence>(_ transform: (Key, Value) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element] { var result: [SegmentOfResult.Iterator.Element] = [] try self._queue.sync { do { result = try self.dict.flatMap(transform) } catch let error { throw error } } return result } /** Synchronous read of the dictionary's forEach method. */ func forEach(_ body: (Key, Value) throws -> Void) rethrows { return try self._queue.sync { do { return try self.dict.forEach(body) } catch let error { throw error } } } /** Synchronous read of the dictionary's firstIndex method. */ func firstIndex(where predicate: (Key, Value) throws -> Bool) rethrows -> DictionaryIndex<Key, Value>? { var index: DictionaryIndex<Key, Value>? try self._queue.sync { do { index = try self.dict.firstIndex(where: predicate) } catch let error { throw error } } return index } /** Synchronous read of the dictionary's map<T> method. */ func map<T>(_ transform: (Key, Value) throws -> T) rethrows -> [T] { var result: [T] = [] try self._queue.sync { do { result = try self.dict.map(transform) } catch let error { throw error } } return result } /** Synchronous read of the dictionary's reduce<Result> method. */ func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, (key: Key, value: Value)) throws -> Result) rethrows -> Result { var result: Result = initialResult try self._queue.sync { do { result = try self.dict.reduce(initialResult, nextPartialResult) } catch let error { throw error } } return result } /** Synchronous read of the dictionary's reversed method. */ func reversed() -> [(key: Key, value: Value)] { var result: [(key: Key, value: Value)] = [] self._queue.sync { result = self.dict.reversed() } return result } } // MARK: - Write Methods public extension SynchronizedDictionary { /** Asynchronous write of the dictionary's popFirst method. */ func popFirst(callback: @escaping ((key: Key, value: Value)?) -> Void) { self._queue.async(flags: DispatchWorkItemFlags.barrier) { DispatchQueue.main.async { callback(self.dict.popFirst()) } } } /** Asynchronous write of the dictionary's removeAll method. */ func removeAll() { self._queue.async(flags: DispatchWorkItemFlags.barrier) { self.dict.removeAll() } } /** Asynchronous write of the dictionary's updateValue method. */ func updateValue(_ value: Value, forKey key: Key, callback: @escaping (Value?) -> Void) { self._queue.async(flags: DispatchWorkItemFlags.barrier) { DispatchQueue.main.async { callback(self.dict.updateValue(value, forKey: key)) } } } /** Asynchronous write of the dictionary's removeValue method. */ func removeValue(forKey key: Key, callback: @escaping (Value?) -> Void) { self._queue.async(flags: DispatchWorkItemFlags.barrier) { DispatchQueue.main.async { callback(self.dict.removeValue(forKey: key)) } } } } // MARK: - Subscript public extension SynchronizedDictionary { /** Synchronous getter subscript. Asynchronous setter subscript. */ subscript(key: Key) -> Value? { get { var value: Value? self._queue.sync { guard let dictValue = self.dict[key] else { return } value = dictValue } return value } set { guard let newValue = newValue else { return } self._queue.async(flags: DispatchWorkItemFlags.barrier) { self.dict[key] = newValue } } } }
1f194bc4d0f7481ea797c128699ab07f
24.238636
146
0.561121
false
false
false
false
binarylevel/Tinylog-iOS
refs/heads/master
Tinylog/View Controllers/Lists/TLIListsViewController.swift
mit
1
// // TLIListsViewController.swift // Tinylog // // Created by Spiros Gerokostas on 17/10/15. // Copyright © 2015 Spiros Gerokostas. All rights reserved. // import UIKit import CoreData class TLIListsViewController: TLICoreDataTableViewController, UITextFieldDelegate, TLIAddListViewControllerDelegate, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating { struct RestorationKeys { static let viewControllerTitle = "ViewControllerTitleKey" static let searchControllerIsActive = "SearchControllerIsActiveKey" static let searchBarText = "SearchBarTextKey" static let searchBarIsFirstResponder = "SearchBarIsFirstResponderKey" } // State restoration values. struct SearchControllerRestorableState { var wasActive = false var wasFirstResponder = false } var restoredState = SearchControllerRestorableState() let kEstimateRowHeight = 61 let kCellIdentifier = "CellIdentifier" var editingIndexPath:NSIndexPath? var estimatedRowHeightCache:NSMutableDictionary? var resultsTableViewController:TLIResultsTableViewController? var searchController:UISearchController? var topBarView:UIView? var didSetupContraints = false var listsFooterView:TLIListsFooterView? = { let listsFooterView = TLIListsFooterView.newAutoLayoutView() return listsFooterView }() lazy var noListsLabel:UILabel? = { let noListsLabel:UILabel = UILabel.newAutoLayoutView() noListsLabel.font = UIFont.tinylogFontOfSize(16.0) noListsLabel.textColor = UIColor.tinylogTextColor() noListsLabel.textAlignment = NSTextAlignment.Center noListsLabel.text = "Tap + icon to create a new list." return noListsLabel }() func configureFetch() { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "List") let positionDescriptor = NSSortDescriptor(key: "position", ascending: false) let titleDescriptor = NSSortDescriptor(key: "title", ascending: true) fetchRequest.sortDescriptors = [positionDescriptor, titleDescriptor] fetchRequest.predicate = NSPredicate(format: "archivedAt = nil") self.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: cdc.context!, sectionNameKeyPath: nil, cacheName: nil) self.frc?.delegate = self do { try self.frc?.performFetch() } catch let error as NSError { fatalError(error.localizedDescription) } } override func viewDidLoad() { super.viewDidLoad() configureFetch() self.title = "My Lists" self.view.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0) self.tableView?.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0) self.tableView?.backgroundView = UIView() self.tableView?.backgroundView?.backgroundColor = UIColor.clearColor() self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.None self.tableView?.registerClass(TLIListTableViewCell.self, forCellReuseIdentifier: kCellIdentifier) self.tableView?.rowHeight = UITableViewAutomaticDimension self.tableView?.estimatedRowHeight = 61 self.tableView?.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height - 50.0) resultsTableViewController = TLIResultsTableViewController() resultsTableViewController?.tableView?.delegate = self searchController = UISearchController(searchResultsController: resultsTableViewController) searchController?.searchResultsUpdater = self searchController?.searchBar.sizeToFit() searchController?.searchBar.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0) searchController?.searchBar.searchBarStyle = UISearchBarStyle.Minimal searchController?.searchBar.setSearchFieldBackgroundImage(UIImage(named: "search-bar-bg-gray"), forState: UIControlState.Normal) searchController?.searchBar.tintColor = UIColor.tinylogMainColor() let searchField:UITextField = searchController?.searchBar.valueForKey("searchField") as! UITextField searchField.textColor = UIColor.tinylogTextColor() self.tableView?.tableHeaderView = searchController?.searchBar searchController?.delegate = self searchController?.dimsBackgroundDuringPresentation = false searchController?.searchBar.delegate = self let settingsImage:UIImage = UIImage(named: "740-gear-toolbar")! let settingsButton:UIButton = UIButton(type: UIButtonType.Custom) settingsButton.frame = CGRectMake(0, 0, 22, 22); settingsButton.setBackgroundImage(settingsImage, forState: UIControlState.Normal) settingsButton.setBackgroundImage(settingsImage, forState: UIControlState.Highlighted) settingsButton.addTarget(self, action: #selector(TLIListsViewController.displaySettings(_:)), forControlEvents: UIControlEvents.TouchDown) let settingsBarButtonItem:UIBarButtonItem = UIBarButtonItem(customView: settingsButton) self.navigationItem.hidesBackButton = true self.navigationItem.leftBarButtonItem = settingsBarButtonItem listsFooterView?.addListButton?.addTarget(self, action: #selector(TLIListsViewController.addNewList(_:)), forControlEvents: UIControlEvents.TouchDown) listsFooterView?.archiveButton?.addTarget(self, action: #selector(TLIListsViewController.displayArchive(_:)), forControlEvents: UIControlEvents.TouchDown) setEditing(false, animated: false) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIListsViewController.syncActivityDidEndNotification(_:)), name: IDMSyncActivityDidEndNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIListsViewController.syncActivityDidBeginNotification(_:)), name: IDMSyncActivityDidBeginNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIListsViewController.updateFonts), name: TLINotifications.kTLIFontDidChangeNotification as String, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIListsViewController.appBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TLIListsViewController.onChangeSize(_:)), name: UIContentSizeCategoryDidChangeNotification, object: nil) definesPresentationContext = true } override func loadView() { super.loadView() view.addSubview(noListsLabel!) view.addSubview(listsFooterView!) view.setNeedsUpdateConstraints() } func deleteMentionWithName(name:String) { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Mention") let nameDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.predicate = NSPredicate(format: "name = %@", name) fetchRequest.sortDescriptors = [nameDescriptor] fetchRequest.fetchLimit = 1 fetchRequest.fetchBatchSize = 20 do { let mentions:NSArray = try cdc.context!.executeFetchRequest(fetchRequest) let mention:TLIMention = mentions.lastObject as! TLIMention cdc.context?.deleteObject(mention) cdc.backgroundSaveContext() } catch let error as NSError { fatalError(error.localizedDescription) } } func viewAllMentions() { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Mention") let displayLongTextDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [displayLongTextDescriptor] fetchRequest.fetchBatchSize = 20 do { let mentions:NSArray = try cdc.context!.executeFetchRequest(fetchRequest) for item in mentions { let mention:TLIMention = item as! TLIMention print("mention.name \(mention.name)") } } catch let error as NSError { fatalError(error.localizedDescription) } } func deleteTagWithName(name:String) { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Tag") let nameDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.predicate = NSPredicate(format: "name = %@", name) fetchRequest.sortDescriptors = [nameDescriptor] fetchRequest.fetchLimit = 1 fetchRequest.fetchBatchSize = 20 do { let tags:NSArray = try cdc.context!.executeFetchRequest(fetchRequest) let tag:TLITag = tags.lastObject as! TLITag cdc.context?.deleteObject(tag) cdc.backgroundSaveContext() } catch let error as NSError { fatalError(error.localizedDescription) } } func viewAllTags() { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Tag") let displayLongTextDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [displayLongTextDescriptor] fetchRequest.fetchBatchSize = 20 do { let tags:NSArray = try cdc.context!.executeFetchRequest(fetchRequest) for item in tags { let tag:TLITag = item as! TLITag print("tag.name \(tag.name)") } } catch let error as NSError { fatalError(error.localizedDescription) } } func onChangeSize(notification:NSNotification) { self.tableView?.reloadData() } func checkForLists() { let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "List") let positionDescriptor = NSSortDescriptor(key: "position", ascending: false) let titleDescriptor = NSSortDescriptor(key: "title", ascending: true) fetchRequest.sortDescriptors = [positionDescriptor, titleDescriptor] fetchRequest.predicate = NSPredicate(format: "archivedAt = nil") do { let results = try cdc.context?.executeFetchRequest(fetchRequest) if results?.count == 0 { self.noListsLabel?.hidden = false } else { self.noListsLabel?.hidden = true } } catch let error as NSError { fatalError(error.localizedDescription) } } override func updateViewConstraints() { if !didSetupContraints { noListsLabel?.autoCenterInSuperview() listsFooterView?.autoMatchDimension(.Width, toDimension: .Width, ofView: self.view) listsFooterView?.autoSetDimension(.Height, toSize: 51.0) listsFooterView?.autoPinEdgeToSuperviewEdge(.Left) listsFooterView?.autoPinEdgeToSuperviewEdge(.Bottom) didSetupContraints = true } super.updateViewConstraints() } func appBecomeActive() { startSync() } func startSync() { let syncManager:TLISyncManager = TLISyncManager.sharedSyncManager() if syncManager.canSynchronize() { syncManager.synchronizeWithCompletion { (error) -> Void in } } } func updateFonts() { self.tableView?.reloadData() } func syncActivityDidEndNotification(notification:NSNotification) { if TLISyncManager.sharedSyncManager().canSynchronize() { UIApplication.sharedApplication().networkActivityIndicatorVisible = false let dateFormatter = NSDateFormatter() dateFormatter.formatterBehavior = NSDateFormatterBehavior.Behavior10_4 dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle //check for connectivity if TLIAppDelegate.sharedAppDelegate().networkMode == "notReachable" { listsFooterView?.updateInfoLabel("Offline") } else { listsFooterView?.updateInfoLabel(NSString(format: "Last Updated %@", dateFormatter.stringForObjectValue(NSDate())!) as String) } checkForLists() } } func syncActivityDidBeginNotification(notification:NSNotification) { if TLISyncManager.sharedSyncManager().canSynchronize() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true if TLIAppDelegate.sharedAppDelegate().networkMode == "notReachable" { listsFooterView?.updateInfoLabel("Offline") } else { listsFooterView?.updateInfoLabel("Syncing...") } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) // Code here will execute before the rotation begins. // Equivalent to placing it in the deprecated method -[willRotateToInterfaceOrientation:duration:] coordinator.animateAlongsideTransition({ (context) -> Void in // Place code here to perform animations during the rotation. // You can pass nil for this closure if not necessary. }, completion: { (context) -> Void in self.tableView?.reloadData() self.view.setNeedsUpdateConstraints() }) } func addNewList(sender:UIButton?) { let addListViewController:TLIAddListViewController = TLIAddListViewController() addListViewController.delegate = self addListViewController.mode = "create" let navigationController:UINavigationController = UINavigationController(rootViewController: addListViewController); navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet self.navigationController?.presentViewController(navigationController, animated: true, completion: nil) TLIAnalyticsTracker.trackMixpanelEvent("Add New List", properties: nil) } // MARK: Display Setup func displaySetup() { let setupViewController:TLISetupViewController = TLISetupViewController() let navigationController:UINavigationController = UINavigationController(rootViewController: setupViewController); navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet; self.navigationController?.presentViewController(navigationController, animated: true, completion: nil) TLIAnalyticsTracker.trackMixpanelEvent("Setup", properties: nil) } func displayArchive(button:TLIArchiveButton) { let settingsViewController:TLIArchiveViewController = TLIArchiveViewController() let navigationController:UINavigationController = UINavigationController(rootViewController: settingsViewController); navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet; self.navigationController?.presentViewController(navigationController, animated: true, completion: nil) TLIAnalyticsTracker.trackMixpanelEvent("Display Archive", properties: nil) } // MARK: Display Settings func displaySettings(sender: UIButton) { let settingsViewController:TLISettingsTableViewController = TLISettingsTableViewController() let navigationController:UINavigationController = UINavigationController(rootViewController: settingsViewController); navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet; self.navigationController?.presentViewController(navigationController, animated: true, completion: nil) TLIAnalyticsTracker.trackMixpanelEvent("Display Settings", properties: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Restore the searchController's active state. if restoredState.wasActive { searchController!.active = restoredState.wasActive restoredState.wasActive = false if restoredState.wasFirstResponder { searchController!.searchBar.becomeFirstResponder() restoredState.wasFirstResponder = false } } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) setEditing(false, animated: false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) checkForLists() let userDefaults = NSUserDefaults.standardUserDefaults() let displaySetupScreen:NSString = userDefaults.objectForKey("kSetupScreen") as! NSString if displaySetupScreen == "on" { $.delay(0.1, closure: { () -> () in self.displaySetup() }) } else if displaySetupScreen == "off" { startSync() } if tableView!.indexPathForSelectedRow != nil { tableView?.deselectRowAtIndexPath(tableView!.indexPathForSelectedRow!, animated: animated) } initEstimatedRowHeightCacheIfNeeded() } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if editing { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLIListsViewController.toggleEditMode(_:))) } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TLIListsViewController.toggleEditMode(_:))) } } func toggleEditMode(sender:UIBarButtonItem) { setEditing(!editing, animated: true) } // MARK: UITableViewDataSource func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let editRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Edit", handler:{action, indexpath in let list:TLIList = self.frc?.objectAtIndexPath(indexpath) as! TLIList let addListViewController:TLIAddListViewController = TLIAddListViewController() addListViewController.delegate = self addListViewController.list = list addListViewController.mode = "edit" let navigationController:UINavigationController = UINavigationController(rootViewController: addListViewController); navigationController.modalPresentationStyle = UIModalPresentationStyle.FormSheet self.navigationController?.presentViewController(navigationController, animated: true, completion: nil) }); editRowAction.backgroundColor = UIColor(red: 229.0 / 255.0, green: 230.0 / 255.0, blue: 232.0 / 255.0, alpha: 1.0) let archiveRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Archive", handler:{action, indexpath in let list:TLIList = self.frc?.objectAtIndexPath(indexpath) as! TLIList let cdc:TLICDController = TLICDController.sharedInstance //First we must delete local notification let app:UIApplication = UIApplication.sharedApplication() let notifications:NSArray = app.scheduledLocalNotifications! for task in list.tasks! { let tmpTask:TLITask = task as! TLITask if let _ = tmpTask.notification { for notification in notifications { let temp:UILocalNotification = notification as! UILocalNotification if let userInfo:NSDictionary = temp.userInfo { let uniqueIdentifier: String? = userInfo.valueForKey("uniqueIdentifier") as? String if uniqueIdentifier == tmpTask.notification!.uniqueIdentifier { let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Notification") let positionDescriptor = NSSortDescriptor(key: "uniqueIdentifier", ascending: false) fetchRequest.sortDescriptors = [positionDescriptor] fetchRequest.predicate = NSPredicate(format: "uniqueIdentifier = %@", uniqueIdentifier!) fetchRequest.fetchLimit = 1 do { let results:NSArray = try cdc.context!.executeFetchRequest(fetchRequest) let notification:TLINotification = results.lastObject as! TLINotification cdc.context?.deleteObject(notification) app.cancelLocalNotification(temp) } catch let error as NSError { fatalError(error.localizedDescription) } } } } } } list.archivedAt = NSDate() cdc.backgroundSaveContext() self.checkForLists() }); archiveRowAction.backgroundColor = UIColor.tinylogMainColor() return [archiveRowAction, editRowAction]; } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func listAtIndexPath(indexPath:NSIndexPath)->TLIList? { let list = self.frc?.objectAtIndexPath(indexPath) as! TLIList! return list } func updateList(list:TLIList, sourceIndexPath:NSIndexPath, destinationIndexPath:NSIndexPath) { var fetchedLists:[AnyObject] = self.frc?.fetchedObjects as [AnyObject]! //println(fetchedLists) fetchedLists = fetchedLists.filter() { $0 as! TLIList != list } //println(fetchedLists) let index = destinationIndexPath.row fetchedLists.insert(list, atIndex: index) var i:NSInteger = fetchedLists.count for (_, list) in fetchedLists.enumerate() { let t = list as! TLIList t.position = NSNumber(integer: i--) } } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if sourceIndexPath.row == destinationIndexPath.row { return; } //Disable fetched results controller self.ignoreNextUpdates = true let list = self.listAtIndexPath(sourceIndexPath)! updateList(list, sourceIndexPath: sourceIndexPath, destinationIndexPath: destinationIndexPath) let cdc:TLICDController = TLICDController.sharedInstance cdc.backgroundSaveContext() } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return floor(getEstimatedCellHeightFromCache(indexPath, defaultHeight: 61)!) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as! TLIListTableViewCell self.configureCell(cell, atIndexPath: indexPath) let success = isEstimatedRowHeightInCache(indexPath) if (success != nil) { let cellSize:CGSize = cell.systemLayoutSizeFittingSize(CGSizeMake(self.view.frame.size.width, 0), withHorizontalFittingPriority: 1000, verticalFittingPriority: 61) putEstimatedCellHeightToCache(indexPath, height: cellSize.height) } return cell } override func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let list:TLIList = self.frc?.objectAtIndexPath(indexPath) as! TLIList let listTableViewCell:TLIListTableViewCell = cell as! TLIListTableViewCell listTableViewCell.currentList = list } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var list:TLIList if tableView == self.tableView { list = self.frc?.objectAtIndexPath(indexPath) as! TLIList } else { list = resultsTableViewController?.frc?.objectAtIndexPath(indexPath) as! TLIList } let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) if IS_IPAD { TLISplitViewController.sharedSplitViewController().listViewController?.managedObject = list TLISplitViewController.sharedSplitViewController().listViewController?.title = list.title } else { let tasksViewController:TLITasksViewController = TLITasksViewController() tasksViewController.list = list self.navigationController?.pushViewController(tasksViewController, animated: true) } } func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String! { return "Delete" } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle != UITableViewCellEditingStyle.Delete { return } let list:TLIList = self.frc?.objectAtIndexPath(indexPath) as! TLIList let cdc:TLICDController = TLICDController.sharedInstance cdc.context!.deleteObject(list) cdc.backgroundSaveContext() } func performBackgroundUpdates(completionHandler: ((UIBackgroundFetchResult) -> Void)!) { completionHandler(UIBackgroundFetchResult.NewData) } func onClose(addListViewController:TLIAddListViewController, list:TLIList) { let indexPath = self.frc?.indexPathForObject(list) self.tableView?.selectRowAtIndexPath(indexPath!, animated: true, scrollPosition: UITableViewScrollPosition.None) let IS_IPAD = (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) if IS_IPAD { TLISplitViewController.sharedSplitViewController().listViewController?.managedObject = list } else { let tasksViewController:TLITasksViewController = TLITasksViewController() tasksViewController.list = list tasksViewController.focusTextField = true self.navigationController?.pushViewController(tasksViewController, animated: true) } checkForLists() } func putEstimatedCellHeightToCache(indexPath:NSIndexPath, height:CGFloat) { initEstimatedRowHeightCacheIfNeeded() estimatedRowHeightCache?.setValue(height, forKey: NSString(format: "%ld", indexPath.row) as String) } func initEstimatedRowHeightCacheIfNeeded() { if estimatedRowHeightCache == nil { estimatedRowHeightCache = NSMutableDictionary() } } func getEstimatedCellHeightFromCache(indexPath:NSIndexPath, defaultHeight:CGFloat)->CGFloat? { initEstimatedRowHeightCacheIfNeeded() let height:CGFloat? = estimatedRowHeightCache!.valueForKey(NSString(format: "%ld", indexPath.row) as String) as? CGFloat if( height != nil) { return floor(height!) } return defaultHeight } func isEstimatedRowHeightInCache(indexPath:NSIndexPath)->Bool? { let value = getEstimatedCellHeightFromCache(indexPath, defaultHeight: 0) if value > 0 { return true } return false } // MARK: UISearchBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() resultsTableViewController?.frc?.delegate = nil resultsTableViewController?.frc = nil } // MARK: UISearchControllerDelegate func presentSearchController(searchController: UISearchController) {} func willPresentSearchController(searchController: UISearchController) { topBarView = UIView(frame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 20.0)) topBarView?.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0) TLIAppDelegate.sharedAppDelegate().window?.rootViewController?.view.addSubview(topBarView!) } func didPresentSearchController(searchController: UISearchController) {} func willDismissSearchController(searchController: UISearchController) { topBarView?.removeFromSuperview() } func didDismissSearchController(searchController: UISearchController) { let resultsController = searchController.searchResultsController as! TLIResultsTableViewController resultsController.frc?.delegate = nil; resultsController.frc = nil } // MARK: UISearchResultsUpdating func updateSearchResultsForSearchController(searchController: UISearchController) { if searchController.searchBar.text!.length() > 0 { let color = findColorByName(searchController.searchBar.text!.lowercaseString) let resultsController = searchController.searchResultsController as! TLIResultsTableViewController let cdc:TLICDController = TLICDController.sharedInstance let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "List") let positionDescriptor = NSSortDescriptor(key: "position", ascending: false) let titleDescriptor = NSSortDescriptor(key: "title", ascending: true) fetchRequest.sortDescriptors = [positionDescriptor, titleDescriptor] let titlePredicate = NSPredicate(format: "title CONTAINS[cd] %@ AND archivedAt = nil", searchController.searchBar.text!.lowercaseString) let colorPredicate = NSPredicate(format: "color CONTAINS[cd] %@ AND archivedAt = nil", color) let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [titlePredicate, colorPredicate]) fetchRequest.predicate = predicate resultsController.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: cdc.context!, sectionNameKeyPath: nil, cacheName: nil) resultsController.frc?.delegate = self; do { try resultsController.frc?.performFetch() resultsController.tableView?.reloadData() resultsController.checkForResults() } catch let error as NSError { fatalError(error.localizedDescription) } } } func findColorByName(name:String)->String { switch name { case "purple": return "#6a6de2" case "blue": return "#008efe" case "red": return "#fe4565" case "orange": return "#ffa600" case "green": return "#50de72" case "yellow": return "#ffd401" default: return "" } } }
0f970224f3b152ff439ab87c99cbaefb
45.011127
200
0.665105
false
false
false
false
parkera/swift
refs/heads/master
benchmark/single-source/BufferFill.swift
apache-2.0
1
//===--- BufferFill.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 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 // //===----------------------------------------------------------------------===// import TestsUtils public let BufferFill = [ BenchmarkInfo(name: "BufferFillFromSlice", runFunction: bufferFillFromSliceExecute, tags: [.validation, .api], setUpFunction: bufferFillFromSliceSetup, tearDownFunction: bufferFillFromSliceTeardown), BenchmarkInfo(name: "RawBufferCopyBytes", runFunction: rawBufferCopyBytesExecute, tags: [.validation, .api], setUpFunction: rawBufferCopyBytesSetup, tearDownFunction: rawBufferCopyBytesTeardown), BenchmarkInfo(name: "RawBufferInitializeMemory", runFunction: rawBufferInitializeMemoryExecute, tags: [.validation, .api], setUpFunction: rawBufferInitializeMemorySetup, tearDownFunction: rawBufferInitializeMemoryTeardown), ] let c = 100_000 let a = Array(0..<c) var b: UnsafeMutableBufferPointer<Int> = .init(start: nil, count: 0) var r = Int.zero public func bufferFillFromSliceSetup() { assert(b.baseAddress == nil) b = .allocate(capacity: c) r = a.indices.randomElement()! } public func bufferFillFromSliceTeardown() { b.deallocate() b = .init(start: nil, count: 0) } @inline(never) public func bufferFillFromSliceExecute(n: Int) { // Measure performance when filling an UnsafeBuffer from a Slice // of a Collection that supports `withContiguousStorageIfAvailable` // See: https://bugs.swift.org/browse/SR-14491 for _ in 0..<n { let slice = Slice(base: a, bounds: a.indices) var (iterator, copied) = b.initialize(from: slice) blackHole(b) CheckResults(copied == a.count && iterator.next() == nil) } CheckResults(a[r] == b[r]) } var ra: [UInt8] = [] var rb = UnsafeMutableRawBufferPointer(start: nil, count: 0) public func rawBufferCopyBytesSetup() { assert(rb.baseAddress == nil) ra = a.withUnsafeBytes(Array.init) r = ra.indices.randomElement()! rb = .allocate(byteCount: ra.count, alignment: 1) } public func rawBufferCopyBytesTeardown() { rb.deallocate() rb = .init(start: nil, count: 0) ra = [] } @inline(never) public func rawBufferCopyBytesExecute(n: Int) { // Measure performance when copying bytes into an UnsafeRawBuffer // from a Collection that supports `withContiguousStorageIfAvailable` // See: https://bugs.swift.org/browse/SR-14886 for _ in 0..<n { rb.copyBytes(from: ra) blackHole(rb) } CheckResults(ra[r] == rb[r]) } public func rawBufferInitializeMemorySetup() { assert(rb.baseAddress == nil) rb = .allocate(byteCount: a.count * MemoryLayout<Int>.stride, alignment: 1) r = a.indices.randomElement()! } public func rawBufferInitializeMemoryTeardown() { rb.deallocate() rb = .init(start: nil, count: 0) } @inline(never) public func rawBufferInitializeMemoryExecute(n: Int) { // Measure performance when initializing an UnsafeRawBuffer // from a Collection that supports `withContiguousStorageIfAvailable` // See: https://bugs.swift.org/browse/SR-14982 for _ in 0..<n { var (iterator, initialized) = rb.initializeMemory(as: Int.self, from: a) blackHole(rb) CheckResults(initialized.count == a.count && iterator.next() == nil) } let offset = rb.baseAddress!.advanced(by: r*MemoryLayout<Int>.stride) let value = offset.load(as: Int.self) CheckResults(value == a[r]) }
ce8d9e706f156edb8174b97c38c7743d
30.884298
80
0.667963
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleLeftWidth.Individual.swift
apache-2.0
1
// // MiddleLeftWidth.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct MiddleLeftWidth { let middleLeft: LayoutElement.Point let width: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.MiddleLeftWidth { private func makeFrame(middleLeft: Point, width: Float, height: Float) -> Rect { let x = middleLeft.x let y = middleLeft.y - height.half let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Height extension IndividualProperty.MiddleLeftWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType { public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let middleLeft = self.middleLeft.evaluated(from: parameters) let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0)) let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width)) return self.makeFrame(middleLeft: middleLeft, width: width, height: height) } }
eb426468ee65d2be61769c1c9b88bd33
22.211538
116
0.72908
false
false
false
false
urbanthings/urbanthings-sdk-apple
refs/heads/master
UrbanThingsAPI/Internal/UrbanThingsAPI.swift
apache-2.0
1
// // UrbanThingsAPI.swift // UrbanThingsAPI // // Created by Mark Woollard on 26/04/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation extension NSLocale { static var httpAcceptLanguage: String { return preferredLanguages.prefix(5).enumerated().map { "\($0.1);q=\(1.0-Double($0.0)*0.1)" }.joined(separator: ", ") } } extension URLSessionTask : UrbanThingsAPIRequest { } extension Service { var baseURLString: String { return "\(endpoint)/\(version)" } } extension UrbanThingsAPI { func toHttpResponse(response: URLResponse?) throws -> HTTPURLResponse { guard let httpResponse = response as? HTTPURLResponse else { throw UTAPIError(unexpected: "Expected HTTPURLResponse, got \(String(describing: response))", file: #file, function: #function, line: #line) } return httpResponse } func validateHTTPStatus(response: HTTPURLResponse, data: Data?) throws { guard response.statusCode < 300 else { var message: String? = "Unknown server error" if response.hasJSONBody && data != nil { // This is to catch the non-standard JSON based error that API currently reports at times. If this is // not present message is default localised message for error code do { let json = try JSONSerialization.jsonObject(with: data!, options: []) message = (json as? [String:AnyObject])?["message"] as? String } catch { } } throw UTAPIError.HTTPStatusError(code: response.statusCode, message: message) } } func validateData(response: HTTPURLResponse, data: Data?) throws { guard response.hasJSONBody else { throw UTAPIError(unexpected: "Content-Type not application/json", file: #file, function: #function, line: #line) } guard let _ = data else { throw UTAPIError(unexpected: "No data in response", file: #file, function: #function, line: #line) } } func parseData<T>(parser:(_ json: Any?, _ logger: Logger) throws -> T, data: Data) throws -> T { #if DEBUG if let utf8 = String(data: data, encoding: String.Encoding.utf8) { logger.log(level: .debug, utf8) print("\(utf8)") } #endif let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] var v2or3: Any? = json?["data"] if v2or3 == nil { v2or3 = json } return try parser(v2or3, logger) } func handleResponse<T>(parser:@escaping (_ json: Any?, _ logger: Logger) throws -> T, result:@escaping (_ data: T?, _ error: Error?) -> Void) -> (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void { func taskCompletionHandler(data: Data?, response: URLResponse?, error: Error?) { guard error == nil else { result(nil, error) return } do { let httpResponse = try self.toHttpResponse(response: response) logger.log(level: .debug, "\(httpResponse)") try self.validateHTTPStatus(response: httpResponse, data: data) try self.validateData(response: httpResponse, data: data) result(try self.parseData(parser: parser, data: data!) as T, nil) } catch { self.logger.log(level: .error, "\(error)") result(nil, error as Error) } } return taskCompletionHandler } func buildURL<R: Request>(request: R) -> String { let parameters = request.queryParameters.description let separator = parameters.characters.count > 0 ? "&" : "?" return "\(self.service.baseURLString)/\(request.endpoint)\(request.queryParameters.description)\(separator)apikey=\(self.service.key)" } }
da1c64e1e389a51595b3e79274f6a7e0
36.906542
152
0.582594
false
false
false
false
P0ed/FireTek
refs/heads/master
Source/SpaceEngine/Components/HPComponent.swift
mit
1
struct HPComponent { let maxHP: Int let armor: Int var currentHP: Float var structure: Array<UInt8> init(maxHP: Int, armor: Int = 0) { self.maxHP = maxHP self.armor = armor currentHP = Float(maxHP) structure = Array(repeating: .max, count: 40) } } extension HPComponent { subscript(x: Int, y: Int) -> UInt8 { get { return structure[HPComponent.convert(x: x, y: y)] } set { structure[HPComponent.convert(x: x, y: y)] = newValue } } static func convert(x: Int, y: Int) -> Int { switch y { case 0...1: return x + y * 7 case 2...4: switch x { case 0...1, 5...6: let yOffset = x > 1 ? 1 : 0 let offset = (y - 2 + yOffset) * 3 return x + y * 7 - offset default: fatalError("Invalid x: \(x) y: \(y)") } case 5...6: return x + y * 7 - 9 default: fatalError("Invalid x: \(x) y: \(y)") } } static func convert(i: Int) -> (x: Int, y: Int) { let offset = ((i > 15) ? 3 : 0) + ((i > 19) ? 3 : 0) + ((i > 23) ? 3 : 0) let i = i + offset return (i % 7, i / 7) } }
57b9f8d1f5267f5548047b01063a351e
19.45098
75
0.544583
false
false
false
false
Oyvindkg/swiftydb
refs/heads/master
Pod/Classes/SwiftyDB+Asynchronous.swift
mit
1
// // SwiftyDB+Asynchronous.swift // SwiftyDB // // Created by Øyvind Grimnes on 13/01/16. // import TinySQLite /** Support asynchronous queries */ extension SwiftyDB { /** A global, concurrent queue with default priority */ private var queue: dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) } // MARK: - Asynchronous database operations /** Asynchronously add object to the database - parameter object: object to be added to the database - parameter update: indicates whether the record should be updated if already present */ public func asyncAddObject <S: Storable> (object: S, update: Bool = true, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { asyncAddObjects([object], update: update, withCompletionHandler: completionHandler) } /** Asynchronously add objects to the database - parameter objects: objects to be added to the database - parameter update: indicates whether the record should be updated if already present */ public func asyncAddObjects <S: Storable> (objects: [S], update: Bool = true, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler?(self!.addObjects(objects)) } } /** Asynchronous retrieval of data for a specified type, matching a filter, from the database - parameter filters: dictionary containing the filters identifying objects to be retrieved - parameter type: type of the objects to be retrieved */ public func asyncDataForType <S: Storable> (type: S.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<[[String: Value?]]>)->Void)) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler(self!.dataForType(type, matchingFilter: filter)) } } /** Asynchronously remove objects of a specified type, matching a filter, from the database - parameter filters: dictionary containing the filters identifying objects to be deleted - parameter type: type of the objects to be deleted */ public func asyncDeleteObjectsForType (type: Storable.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<Bool>)->Void)? = nil) { dispatch_async(queue) { [weak self] () -> Void in guard self != nil else { return } completionHandler?(self!.deleteObjectsForType(type, matchingFilter: filter)) } } } extension SwiftyDB { // MARK: - Asynchronous dynamic initialization /** Asynchronous retrieval of objects of a specified type, matching a set of filters, from the database - parameter filters: dictionary containing the filters identifying objects to be retrieved - parameter type: type of the objects to be retrieved */ public func asyncObjectsForType <D where D: Storable, D: NSObject> (type: D.Type, matchingFilter filter: Filter? = nil, withCompletionHandler completionHandler: ((Result<[D]>)->Void)) { dispatch_async(queue) { [unowned self] () -> Void in completionHandler(self.objectsForType(type, matchingFilter: filter)) } } }
c7cca606d77ac56435e27d050058c870
35.188119
189
0.63711
false
false
false
false
YesVideo/swix
refs/heads/master
swix/swix/swix/matrix/m-simple-math.swift
mit
1
// // twoD-math.swift // swix // // Created by Scott Sievert on 7/10/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func apply_function(function: ndarray->ndarray, x: matrix)->matrix{ let y = function(x.flat) var z = zeros_like(x) z.flat = y return z } // TRIG public func sin(x: matrix) -> matrix{ return apply_function(sin, x: x) } public func cos(x: matrix) -> matrix{ return apply_function(cos, x: x) } public func tan(x: matrix) -> matrix{ return apply_function(tan, x: x) } public func tanh(x: matrix) -> matrix { return apply_function(tanh, x: x) } // BASIC INFO public func abs(x: matrix) -> matrix{ return apply_function(abs, x: x) } public func sign(x: matrix) -> matrix{ return apply_function(sign, x: x) } // POWER FUNCTION public func pow(x: matrix, power: Double) -> matrix{ let y = pow(x.flat, power: power) var z = zeros_like(x) z.flat = y return z } public func sqrt(x: matrix) -> matrix{ return apply_function(sqrt, x: x) } // ROUND public func floor(x: matrix) -> matrix{ return apply_function(floor, x: x) } public func ceil(x: matrix) -> matrix{ return apply_function(ceil, x: x) } public func round(x: matrix) -> matrix{ return apply_function(round, x: x) } // LOG public func log(x: matrix) -> matrix{ return apply_function(log, x: x) } // BASIC STATS public func min(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = min(x.flat, y: y.flat) return z } public func max(x:matrix, y:matrix)->matrix{ var z = zeros_like(x) z.flat = max(x.flat, y: y.flat) return z } // AXIS public func sum(x: matrix, axis:Int = -1) -> ndarray{ // arg dim: indicating what dimension you want to sum over. For example, if dim==0, then it'll sum over dimension 0 -- it will add all the numbers in the 0th dimension, x[0..<x.shape.0, i] assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") if axis==1{ let n = x.shape.1 let m = ones((n,1)) return (x.dot(m)).flat } else if axis==0 { let n = x.shape.0 let m = ones((1,n)) return (m.dot(x)).flat } // the program will never get below this line assert(false) return zeros(1) } public func prod(x: matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "if you want to sum over the entire matrix, call `sum(x.flat)`.") let y = log(x) let z = sum(y, axis:axis) return exp(z) } public func mean(x:matrix, axis:Int = -1) -> ndarray{ assert(axis==0 || axis==1, "If you want to find the average of the whole matrix call `mean(x.flat)`") let div = axis==0 ? x.shape.0 : x.shape.1 return sum(x, axis:axis) / div.double }
cb9a8a34636375fbb880063c1b525446
24.427273
192
0.61709
false
false
false
false
KaiCode2/swift-corelibs-foundation
refs/heads/master
Foundation/NSOrderedSet.swift
apache-2.0
3
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /**************** Immutable Ordered Set ****************/ public class NSOrderedSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, ArrayLiteralConvertible { internal var _storage: Set<NSObject> internal var _orderedStorage: [NSObject] public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } public override func mutableCopy() -> AnyObject { return mutableCopyWithZone(nil) } public func mutableCopyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } public override func isEqual(_ object: AnyObject?) -> Bool { if let orderedSet = object as? NSOrderedSet { return isEqualToOrderedSet(orderedSet) } else { return false } } public func encodeWithCoder(_ aCoder: NSCoder) { if aCoder.allowsKeyedCoding { for idx in 0..<self.count { aCoder.encodeObject(self.objectAtIndex(idx), forKey:"NS.object.\(idx)") } } else { NSUnimplemented() } } public required convenience init?(coder aDecoder: NSCoder) { if aDecoder.allowsKeyedCoding { var idx = 0 var objects : [AnyObject] = [] while aDecoder.containsValueForKey(("NS.object.\(idx)")) { guard let object = aDecoder.decodeObjectForKey("NS.object.\(idx)") else { return nil } objects.append(object) idx += 1 } self.init(array: objects) } else { NSUnimplemented() } } public var count: Int { return _storage.count } public func objectAtIndex(_ idx: Int) -> AnyObject { return _orderedStorage[idx] } public func indexOfObject(_ object: AnyObject) -> Int { guard let object = object as? NSObject else { return NSNotFound } return _orderedStorage.index(of: object) ?? NSNotFound } public convenience override init() { self.init(objects: [], count: 0) } public init(objects: UnsafePointer<AnyObject?>, count cnt: Int) { _storage = Set<NSObject>() _orderedStorage = [NSObject]() super.init() _insertObjects(objects, count: cnt) } required public convenience init(arrayLiteral elements: AnyObject...) { self.init(array: elements) } public convenience init(objects elements: AnyObject...) { self.init(array: elements) } public subscript (idx: Int) -> AnyObject { return objectAtIndex(idx) } private func _insertObject(_ object: AnyObject) { guard !containsObject(object), let object = object as? NSObject else { return } _storage.insert(object) _orderedStorage.append(object) } private func _insertObjects(_ objects: UnsafePointer<AnyObject?>, count cnt: Int) { let buffer = UnsafeBufferPointer(start: objects, count: cnt) for obj in buffer { _insertObject(obj!) } } } extension NSOrderedSet : Sequence { /// Return a *generator* over the elements of this *sequence*. /// /// - Complexity: O(1). public typealias Iterator = NSEnumerator.Iterator public func makeIterator() -> Iterator { return self.objectEnumerator().makeIterator() } } extension NSOrderedSet { public func getObjects(_ objects: inout [AnyObject], range: NSRange) { for idx in range.location..<(range.location + range.length) { objects.append(_orderedStorage[idx]) } } public func objectsAtIndexes(_ indexes: NSIndexSet) -> [AnyObject] { var entries = [AnyObject]() for idx in indexes { if idx >= count && idx < 0 { fatalError("\(self): Index out of bounds") } entries.append(objectAtIndex(idx)) } return entries } public var firstObject: AnyObject? { return _orderedStorage.first } public var lastObject: AnyObject? { return _orderedStorage.last } public func isEqualToOrderedSet(_ otherOrderedSet: NSOrderedSet) -> Bool { if count != otherOrderedSet.count { return false } for idx in 0..<count { let obj1 = objectAtIndex(idx) as! NSObject let obj2 = otherOrderedSet.objectAtIndex(idx) as! NSObject if obj1 === obj2 { continue } if !obj1.isEqual(obj2) { return false } } return true } public func containsObject(_ object: AnyObject) -> Bool { if let object = object as? NSObject { return _storage.contains(object) } return false } public func intersectsOrderedSet(_ other: NSOrderedSet) -> Bool { if count < other.count { return contains { obj in other.containsObject(obj as! NSObject) } } else { return other.contains { obj in containsObject(obj) } } } public func intersectsSet(_ set: Set<NSObject>) -> Bool { if count < set.count { return contains { obj in set.contains(obj as! NSObject) } } else { return set.contains { obj in containsObject(obj) } } } public func isSubsetOfOrderedSet(_ other: NSOrderedSet) -> Bool { return !self.contains { obj in !other.containsObject(obj as! NSObject) } } public func isSubsetOfSet(_ set: Set<NSObject>) -> Bool { return !self.contains { obj in !set.contains(obj as! NSObject) } } public func objectEnumerator() -> NSEnumerator { if self.dynamicType === NSOrderedSet.self || self.dynamicType === NSMutableOrderedSet.self { return NSGeneratorEnumerator(_orderedStorage.makeIterator()) } else { NSRequiresConcreteImplementation() } } public func reverseObjectEnumerator() -> NSEnumerator { if self.dynamicType === NSOrderedSet.self || self.dynamicType === NSMutableOrderedSet.self { return NSGeneratorEnumerator(_orderedStorage.reversed().makeIterator()) } else { NSRequiresConcreteImplementation() } } /*@NSCopying*/ public var reversedOrderedSet: NSOrderedSet { return NSOrderedSet(array: _orderedStorage.reversed().bridge().bridge()) } // These two methods return a facade object for the receiving ordered set, // which acts like an immutable array or set (respectively). Note that // while you cannot mutate the ordered set through these facades, mutations // to the original ordered set will "show through" the facade and it will // appear to change spontaneously, since a copy of the ordered set is not // being made. public var array: [AnyObject] { NSUnimplemented() } public var set: Set<NSObject> { NSUnimplemented() } public func enumerateObjectsUsingBlock(_ block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateObjectsWithOptions(_ opts: NSEnumerationOptions, usingBlock block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateObjectsAtIndexes(_ s: NSIndexSet, options opts: NSEnumerationOptions, usingBlock block: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func indexOfObjectPassingTest(_ predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } public func indexOfObjectWithOptions(_ opts: NSEnumerationOptions, passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } public func indexOfObjectAtIndexes(_ s: NSIndexSet, options opts: NSEnumerationOptions, passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int { NSUnimplemented() } public func indexesOfObjectsPassingTest(_ predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { NSUnimplemented() } public func indexesOfObjectsWithOptions(_ opts: NSEnumerationOptions, passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { NSUnimplemented() } public func indexesOfObjectsAtIndexes(_ s: NSIndexSet, options opts: NSEnumerationOptions, passingTest predicate: (AnyObject, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet { NSUnimplemented() } public func indexOfObject(_ object: AnyObject, inSortedRange range: NSRange, options opts: NSBinarySearchingOptions, usingComparator cmp: NSComparator) -> Int { NSUnimplemented() } // binary search public func sortedArrayUsingComparator(_ cmptr: NSComparator) -> [AnyObject] { NSUnimplemented() } public func sortedArrayWithOptions(_ opts: NSSortOptions, usingComparator cmptr: NSComparator) -> [AnyObject] { NSUnimplemented() } public func descriptionWithLocale(_ locale: AnyObject?) -> String { NSUnimplemented() } public func descriptionWithLocale(_ locale: AnyObject?, indent level: Int) -> String { NSUnimplemented() } } extension NSOrderedSet { public convenience init(object: AnyObject) { self.init(array: [object]) } public convenience init(orderedSet set: NSOrderedSet) { self.init(orderedSet: set, copyItems: false) } public convenience init(orderedSet set: NSOrderedSet, copyItems flag: Bool) { self.init(orderedSet: set, range: NSMakeRange(0, set.count), copyItems: flag) } public convenience init(orderedSet set: NSOrderedSet, range: NSRange, copyItems flag: Bool) { // TODO: Use the array method here when available. self.init(array: set.map { $0 }, range: range, copyItems: flag) } public convenience init(array: [AnyObject]) { let buffer = UnsafeMutablePointer<AnyObject?>(allocatingCapacity: array.count) for (idx, element) in array.enumerated() { buffer.advanced(by: idx).initialize(with: element) } self.init(objects: buffer, count: array.count) buffer.deinitialize(count: array.count) buffer.deallocateCapacity(array.count) } public convenience init(array set: [AnyObject], copyItems flag: Bool) { self.init(array: set, range: NSMakeRange(0, set.count), copyItems: flag) } public convenience init(array set: [AnyObject], range: NSRange, copyItems flag: Bool) { var objects = set if let range = range.toRange() where range.count != set.count || flag { objects = [AnyObject]() for index in range.indices { let object = set[index] as! NSObject objects.append(flag ? object.copy() : object) } } self.init(array: objects) } public convenience init(set: Set<NSObject>) { self.init(set: set, copyItems: false) } public convenience init(set: Set<NSObject>, copyItems flag: Bool) { self.init(array: set.map { $0 as AnyObject }, copyItems: flag) } } /**************** Mutable Ordered Set ****************/ public class NSMutableOrderedSet : NSOrderedSet { public func insertObject(_ object: AnyObject, atIndex idx: Int) { guard idx < count && idx >= 0 else { fatalError("\(self): Index out of bounds") } if containsObject(object) { return } if let object = object as? NSObject { _storage.insert(object) _orderedStorage.insert(object, at: idx) } } public func removeObjectAtIndex(_ idx: Int) { _storage.remove(_orderedStorage[idx]) _orderedStorage.remove(at: idx) } public func replaceObjectAtIndex(_ idx: Int, withObject object: AnyObject) { guard idx < count && idx >= 0 else { fatalError("\(self): Index out of bounds") } if let objectToReplace = objectAtIndex(idx) as? NSObject, object = object as? NSObject { _orderedStorage[idx] = object _storage.remove(objectToReplace) _storage.insert(object) } } public init(capacity numItems: Int) { super.init(objects: [], count: 0) } required public convenience init(arrayLiteral elements: AnyObject...) { self.init(capacity: 0) addObjectsFromArray(elements) } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } private func _removeObject(_ object: AnyObject) { guard containsObject(object), let object = object as? NSObject else { return } _storage.remove(object) _orderedStorage.remove(at: indexOfObject(object)) } } extension NSMutableOrderedSet { public func addObject(_ object: AnyObject) { _insertObject(object) } public func addObjects(_ objects: UnsafePointer<AnyObject?>, count: Int) { _insertObjects(objects, count: count) } public func addObjectsFromArray(_ array: [AnyObject]) { for object in array { _insertObject(object) } } public func exchangeObjectAtIndex(_ idx1: Int, withObjectAtIndex idx2: Int) { guard idx1 < count && idx1 >= 0 && idx2 < count && idx2 >= 0 else { fatalError("\(self): Index out of bounds") } if let object1 = objectAtIndex(idx1) as? NSObject, object2 = objectAtIndex(idx2) as? NSObject { _orderedStorage[idx1] = object2 _orderedStorage[idx2] = object1 } } public func moveObjectsAtIndexes(_ indexes: NSIndexSet, toIndex idx: Int) { var removedObjects = [NSObject]() for index in indexes.lazy.reversed() { if let object = objectAtIndex(index) as? NSObject { removedObjects.append(object) removeObjectAtIndex(index) } } for removedObject in removedObjects { insertObject(removedObject, atIndex: idx) } } public func insertObjects(_ objects: [AnyObject], atIndexes indexes: NSIndexSet) { for (indexLocation, index) in indexes.enumerated() { if let object = objects[indexLocation] as? NSObject { insertObject(object, atIndex: index) } } } public func setObject(_ obj: AnyObject, atIndex idx: Int) { if let object = obj as? NSObject { _storage.insert(object) if idx == _orderedStorage.count { _orderedStorage.append(object) } else { _orderedStorage[idx] = object } } } public func replaceObjectsInRange(_ range: NSRange, withObjects objects: UnsafePointer<AnyObject?>, count: Int) { if let range = range.toRange() { let buffer = UnsafeBufferPointer(start: objects, count: count) for (indexLocation, index) in range.indices.lazy.reversed().enumerated() { if let object = buffer[indexLocation] as? NSObject { replaceObjectAtIndex(index, withObject: object) } } } } public func replaceObjectsAtIndexes(_ indexes: NSIndexSet, withObjects objects: [AnyObject]) { for (indexLocation, index) in indexes.enumerated() { if let object = objects[indexLocation] as? NSObject { replaceObjectAtIndex(index, withObject: object) } } } public func removeObjectsInRange(_ range: NSRange) { if let range = range.toRange() { for index in range.indices.lazy.reversed() { removeObjectAtIndex(index) } } } public func removeObjectsAtIndexes(_ indexes: NSIndexSet) { for index in indexes.lazy.reversed() { removeObjectAtIndex(index) } } public func removeAllObjects() { _storage.removeAll() _orderedStorage.removeAll() } public func removeObject(_ object: AnyObject) { if let object = object as? NSObject { _storage.remove(object) _orderedStorage.remove(at: indexOfObject(object)) } } public func removeObjectsInArray(_ array: [AnyObject]) { array.forEach(removeObject) } public func intersectOrderedSet(_ other: NSOrderedSet) { for case let item as NSObject in self where !other.containsObject(item) { removeObject(item) } } public func minusOrderedSet(_ other: NSOrderedSet) { for item in other where containsObject(item) { removeObject(item) } } public func unionOrderedSet(_ other: NSOrderedSet) { other.forEach(addObject) } public func intersectSet(_ other: Set<NSObject>) { for case let item as NSObject in self where !other.contains(item) { removeObject(item) } } public func minusSet(_ other: Set<NSObject>) { for item in other where containsObject(item) { removeObject(item) } } public func unionSet(_ other: Set<NSObject>) { other.forEach(addObject) } public func sortUsingComparator(_ cmptr: NSComparator) { sortRange(NSMakeRange(0, count), options: [], usingComparator: cmptr) } public func sortWithOptions(_ opts: NSSortOptions, usingComparator cmptr: NSComparator) { sortRange(NSMakeRange(0, count), options: opts, usingComparator: cmptr) } public func sortRange(_ range: NSRange, options opts: NSSortOptions, usingComparator cmptr: NSComparator) { // The sort options are not available. We use the Array's sorting algorithm. It is not stable neither concurrent. guard opts.isEmpty else { NSUnimplemented() } let swiftRange = range.toRange()! _orderedStorage[swiftRange].sort { lhs, rhs in return cmptr(lhs, rhs) == .orderedAscending } } }
5f0254b8f4cf70ded9ab075ae78d578b
33.579044
211
0.61581
false
false
false
false
ribl/FBAnnotationClusteringSwift
refs/heads/master
Pod/Classes/FBBoundingBox+MapKit.swift
mit
1
// // FBBoundingBox+MapKit.swift // Pods // // Created by Antoine Lamy on 23/9/2016. // // import Foundation import MapKit extension FBBoundingBox { init(mapRect: MKMapRect) { let topLeft = mapRect.origin.coordinate let bottomRight = MKMapPoint(x: mapRect.maxX, y: mapRect.maxY).coordinate let minLat = bottomRight.latitude let maxLat = topLeft.latitude let minLon = topLeft.longitude let maxLon = bottomRight.longitude self.init(x0: CGFloat(minLat), y0: CGFloat(minLon), xf: CGFloat(maxLat), yf: CGFloat(maxLon)) } func contains(coordinate: CLLocationCoordinate2D) -> Bool { let containsX = (x0 <= CGFloat(coordinate.latitude)) && (CGFloat(coordinate.latitude) <= xf) let containsY = (y0 <= CGFloat(coordinate.longitude)) && (CGFloat(coordinate.longitude) <= yf) return (containsX && containsY) } func mapRect() -> MKMapRect { let topLeft = MKMapPoint(CLLocationCoordinate2DMake(CLLocationDegrees(x0), CLLocationDegrees(y0))) let botRight = MKMapPoint(CLLocationCoordinate2DMake(CLLocationDegrees(xf), CLLocationDegrees(yf))) return MKMapRect(x: topLeft.x, y: botRight.y, width: fabs(botRight.x - topLeft.x), height: fabs(botRight.y - topLeft.y)) } }
d8b054d43d961ad676e04c9cd8db8d84
31.131579
128
0.715807
false
false
false
false
nikrad/ios
refs/heads/master
FiveCalls/FiveCalls/MultipleSelectionSegmentedControl.swift
mit
2
// // MultipleSelectionSegmentedControl.swift // FiveCalls // // Created by Christopher Brandow on 2/7/17. // Copyright © 2017 5calls. All rights reserved. // import Foundation class MultipleSelectionControl: UIControl { @IBInspectable var selectedColor: UIColor = .lightGray @IBInspectable var deSelectedColor: UIColor = .white @IBInspectable var titlesString = "" private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.alignment = .fill stackView.spacing = 0.5 return stackView }() private var titles: [String]? var buttons: [UIButton]? var selectedIndices: [Int] { get { var indices = [Int]() for index in (buttons?.indices)! { if (buttons?[index].isSelected)! { indices.append(index) } } return indices } } func setSelectedButtons(at indices: [Int]) { for index in indices { buttons?[index].isSelected = true let titleColor = (buttons?[index].isSelected)! ? deSelectedColor : selectedColor buttons?[index].setTitleColor(titleColor, for: .normal) buttons?[index].backgroundColor = (buttons?[index].isSelected)! ? selectedColor : deSelectedColor } } private func addButtons(to stackView: UIStackView) { let titles = titlesString.components(separatedBy: ",") buttons = titles.flatMap({ title in guard !title.isEmpty else { return nil } let button = UIButton() button.isSelected = false button.setTitle(title, for: .normal) button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside) stackView.addArrangedSubview(button) setColor(button: button) return button }) } override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 4 layer.masksToBounds = true addSubview(stackView) addButtons(to: stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.leftAnchor.constraint(equalTo: leftAnchor), stackView.rightAnchor.constraint(equalTo: rightAnchor), stackView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } @objc func buttonAction(_ sender: UIButton) { sender.isSelected = !sender.isSelected setColor(button: sender) sendActions(for: .valueChanged) } func setColor(button: UIButton) { let titleColor = button.isSelected ? deSelectedColor : selectedColor button.setTitleColor(titleColor, for: .normal) button.backgroundColor = button.isSelected ? selectedColor : deSelectedColor } }
a61acc469c098782dcf29621aeafa4e9
31.902174
109
0.625041
false
false
false
false
henryhsin/vapor_helloPersistance
refs/heads/master
Sources/App/Controllers/BasicControllers.swift
mit
1
// // BasicControllers.swift // helloPersistance // // Created by 辛忠翰 on 2017/4/10. // // import Foundation import Vapor import HTTP import VaporPostgreSQL final class BasicControllers{ func addRoutes(drop: Droplet){ let basic = drop.grouped("basic") let data = drop.grouped("data") basic.get("version", handler: version) data.get("model", handler: model) data.get("addFUM", handler: addFUM) data.get("allRows", handler: allRows) data.get("firstRow", handler: firstRow) data.get("filterASAP", handler: filterASAP) data.get("nonASAP", handler: nonASAP) data.get("deleteASAP", handler: deleteASAP) data.post("addNew", handler: addNew) data.get("update",handler: update) } func version(request: Request) throws -> ResponseRepresentable { if let db = drop.database?.driver as? PostgreSQLDriver{ let version = try db.raw("SELECT version()") return try JSON(node: version) }else{ return "No db connection." } } func model(request: Request) throws -> ResponseRepresentable { let acronym = Acronym(short: "AFK", long: "Away From Keyboard~~") return try acronym.makeJSON() } func addFUM(request: Request) throws -> ResponseRepresentable { var acronym = Acronym(short: "FUM", long: "Fuck Your Mother!!") try acronym.save() return try JSON(node: Acronym.all().makeNode()) } func allRows(request: Request) throws -> ResponseRepresentable { return try JSON(node: Acronym.all().makeNode()) } func firstRow(request: Request) throws -> ResponseRepresentable { return try JSON(node: Acronym.query().first()?.makeNode()) } func filterASAP(request: Request) throws -> ResponseRepresentable { return try JSON(node: Acronym.query().filter("short", "ASAP").all().makeNode()) } func nonASAP(request: Request) throws -> ResponseRepresentable { return try JSON(node: Acronym.query().filter("short", .notEquals , "ASAP") .all().makeNode()) } func deleteASAP(request: Request) throws -> ResponseRepresentable { let query = try Acronym.query().filter("short", "ASAP") try query.delete() return try JSON(node: Acronym.all().makeNode()) } func addNew(request: Request) throws -> ResponseRepresentable { var acronym = try Acronym(node: request.json) print(request) try acronym.save() return acronym } func update(request: Request) throws -> ResponseRepresentable { guard var phrase = try Acronym.query().first(), let long = request.data["long"]?.string else { throw Abort.badRequest } phrase.long = long try phrase.save() return phrase } }
62757d0e85076cc1f11a48b3b04d6e3e
30.376344
102
0.61172
false
false
false
false
talentsparkio/CloudNote
refs/heads/master
CloudNote/NoteCell.swift
bsd-3-clause
1
// // NoteCell.swift // CloudNote // // Created by Nick Chen on 8/8/15. // Copyright © 2015 TalentSpark. All rights reserved. // import UIKit class NoteCell: UITableViewCell { @IBOutlet weak var notePhoto: UIImageView! @IBOutlet weak var noteTitle: UILabel! @IBOutlet weak var noteBody: UILabel! var note: PFObject? { didSet { if let setNote = note { noteTitle.text = setNote["Title"] as? String noteBody.text = setNote["Body"] as? String let image = setNote["Photo"] as? PFFile image?.getDataInBackgroundWithBlock {(imageData, error) -> Void in if error == nil { if let imageData = imageData { self.notePhoto.image = UIImage(data:imageData) } } } } } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
5272b972a4649479fb9ad4e8f20db221
26.119048
82
0.528534
false
false
false
false
JPIOS/JDanTang
refs/heads/master
JDanTang/JDanTang/Class/MainClass/Home/Home/Model/Target.swift
apache-2.0
1
// // Target.swift // // Create by 朋 家 on 9/7/2017 // Copyright © 2017. All rights reserved. // 模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class Target : NSObject { var bannerImageUrl : String! var coverImageUrl : String! var createdAt : Int! var id : Int! var postsCount : Int! var status : Int! var subtitle : String! var title : String! var updatedAt : Int! /** * 用字典来初始化一个实例并设置各个属性值 */ init(fromDictionary dictionary: NSDictionary){ bannerImageUrl = dictionary["banner_image_url"] as? String coverImageUrl = dictionary["cover_image_url"] as? String createdAt = dictionary["created_at"] as? Int id = dictionary["id"] as? Int postsCount = dictionary["posts_count"] as? Int status = dictionary["status"] as? Int subtitle = dictionary["subtitle"] as? String title = dictionary["title"] as? String updatedAt = dictionary["updated_at"] as? Int } }
96e7fc01e1568f0cb75adfdd36c679b5
22.175
65
0.695793
false
false
false
false
karwa/swift
refs/heads/master
test/Parse/type_expr.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -swift-version 4 // not ready: dont_run: %target-typecheck-verify-swift -enable-astscope-lookup -swift-version 4 // Types in expression contexts must be followed by a member access or // constructor call. struct Foo { struct Bar { init() {} static var prop: Int = 0 static func meth() {} func instMeth() {} } init() {} static var prop: Int = 0 static func meth() {} func instMeth() {} } protocol Zim { associatedtype Zang init() // TODO class var prop: Int { get } static func meth() {} // expected-error{{protocol methods must not have bodies}} func instMeth() {} // expected-error{{protocol methods must not have bodies}} } protocol Bad { init() {} // expected-error{{protocol initializers must not have bodies}} } struct Gen<T> { struct Bar { init() {} static var prop: Int { return 0 } static func meth() {} func instMeth() {} } init() {} static var prop: Int { return 0 } static func meth() {} func instMeth() {} } func unqualifiedType() { _ = Foo.self _ = Foo.self _ = Foo() _ = Foo.prop _ = Foo.meth let _ : () = Foo.meth() _ = Foo.instMeth _ = Foo // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{10-10=()}} expected-note{{use '.self'}} {{10-10=.self}} _ = Foo.dynamicType // expected-error {{type 'Foo' has no member 'dynamicType'}} // expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{10-22=)}} _ = Bad // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}}{{10-10=.self}} } func qualifiedType() { _ = Foo.Bar.self let _ : Foo.Bar.Type = Foo.Bar.self let _ : Foo.Protocol = Foo.self // expected-error{{cannot use 'Protocol' with non-protocol type 'Foo'}} _ = Foo.Bar() _ = Foo.Bar.prop _ = Foo.Bar.meth let _ : () = Foo.Bar.meth() _ = Foo.Bar.instMeth _ = Foo.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{14-14=()}} expected-note{{use '.self'}} {{14-14=.self}} _ = Foo.Bar.dynamicType // expected-error {{type 'Foo.Bar' has no member 'dynamicType'}} // expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{14-26=)}} } // We allow '.Type' in expr context func metaType() { let _ = Foo.Type.self let _ = Foo.Type.self let _ = Foo.Type // expected-error{{expected member name or constructor call after type name}} // expected-note@-1 {{use '.self' to reference the type object}} let _ = type(of: Foo.Type) // expected-error{{expected member name or constructor call after type name}} // expected-note@-1 {{use '.self' to reference the type object}} } func genType() { _ = Gen<Foo>.self _ = Gen<Foo>() _ = Gen<Foo>.prop _ = Gen<Foo>.meth let _ : () = Gen<Foo>.meth() _ = Gen<Foo>.instMeth _ = Gen<Foo> // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{use '.self' to reference the type object}} // expected-note@-2{{add arguments after the type to construct a value of the type}} } func genQualifiedType() { _ = Gen<Foo>.Bar.self _ = Gen<Foo>.Bar() _ = Gen<Foo>.Bar.prop _ = Gen<Foo>.Bar.meth let _ : () = Gen<Foo>.Bar.meth() _ = Gen<Foo>.Bar.instMeth _ = Gen<Foo>.Bar // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{add arguments after the type to construct a value of the type}} // expected-note@-2{{use '.self' to reference the type object}} _ = Gen<Foo>.Bar.dynamicType // expected-error {{type 'Gen<Foo>.Bar' has no member 'dynamicType'}} // expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{19-31=)}} } func typeOfShadowing() { // Try to shadow type(of:) func type<T>(of t: T.Type, flag: Bool) -> T.Type { // expected-note {{'type(of:flag:)' declared here}} return t } func type<T, U>(of t: T.Type, _ : U) -> T.Type { return t } func type<T>(_ t: T.Type) -> T.Type { return t } func type<T>(fo t: T.Type) -> T.Type { return t } _ = type(of: Gen<Foo>.Bar) // expected-error{{missing argument for parameter 'flag' in call}} {{28-28=, flag: <#Bool#>}} _ = type(Gen<Foo>.Bar) // expected-error{{expected member name or constructor call after type name}} // expected-note@-1{{add arguments after the type to construct a value of the type}} // expected-note@-2{{use '.self' to reference the type object}} _ = type(of: Gen<Foo>.Bar.self, flag: false) // No error here. _ = type(fo: Foo.Bar.self) // No error here. _ = type(of: Foo.Bar.self, [1, 2, 3]) // No error here. } func archetype<T: Zim>(_: T) { _ = T.self _ = T() // TODO let prop = T.prop _ = T.meth let _ : () = T.meth() _ = T // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{8-8=()}} expected-note{{use '.self'}} {{8-8=.self}} } func assocType<T: Zim>(_: T) where T.Zang: Zim { _ = T.Zang.self _ = T.Zang() // TODO _ = T.Zang.prop _ = T.Zang.meth let _ : () = T.Zang.meth() _ = T.Zang // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{13-13=()}} expected-note{{use '.self'}} {{13-13=.self}} } class B { class func baseMethod() {} } class D: B { class func derivedMethod() {} } func derivedType() { let _: B.Type = D.self _ = D.baseMethod let _ : () = D.baseMethod() let _: D.Type = D.self _ = D.derivedMethod let _ : () = D.derivedMethod() let _: B.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}} let _: D.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}} } // Referencing a nonexistent member or constructor should not trigger errors // about the type expression. func nonexistentMember() { let cons = Foo("this constructor does not exist") // expected-error{{argument passed to call that takes no arguments}} let prop = Foo.nonexistent // expected-error{{type 'Foo' has no member 'nonexistent'}} let meth = Foo.nonexistent() // expected-error{{type 'Foo' has no member 'nonexistent'}} } protocol P {} func meta_metatypes() { let _: P.Protocol = P.self _ = P.Type.self _ = P.Protocol.self _ = P.Protocol.Protocol.self // expected-error{{cannot use 'Protocol' with non-protocol type 'P.Protocol'}} _ = P.Protocol.Type.self _ = B.Type.self } class E { private init() {} } func inAccessibleInit() { _ = E // expected-error {{expected member name or constructor call after type name}} expected-note {{use '.self'}} {{8-8=.self}} } enum F: Int { case A, B } struct G { var x: Int } func implicitInit() { _ = F // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}} _ = G // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}} } // https://bugs.swift.org/browse/SR-502 func testFunctionCollectionTypes() { _ = [(Int) -> Int]() _ = [(Int, Int) -> Int]() _ = [(x: Int, y: Int) -> Int]() // Make sure associativity is correct let a = [(Int) -> (Int) -> Int]() let b: Int = a[0](5)(4) _ = [String: (Int) -> Int]() _ = [String: (Int, Int) -> Int]() _ = [1 -> Int]() // expected-error {{expected type before '->'}} _ = [Int -> 1]() // expected-error {{expected type after '->'}} // expected-error@-1 {{single argument function types require parentheses}} // Should parse () as void type when before or after arrow _ = [() -> Int]() _ = [(Int) -> ()]() _ = 2 + () -> Int // expected-error {{expected type before '->'}} _ = () -> (Int, Int).2 // expected-error {{expected type after '->'}} _ = (Int) -> Int // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}} _ = @convention(c) () -> Int // expected-error{{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}} _ = 1 + (@convention(c) () -> Int).self // expected-error{{cannot convert value of type '(@convention(c) () -> Int).Type' to expected argument type 'Int'}} _ = (@autoclosure () -> Int) -> (Int, Int).2 // expected-error {{expected type after '->'}} _ = ((@autoclosure () -> Int) -> (Int, Int)).1 // expected-error {{type '(@autoclosure () -> Int) -> (Int, Int)' has no member '1'}} _ = ((inout Int) -> Void).self _ = [(Int) throws -> Int]() _ = [@convention(swift) (Int) throws -> Int]().count _ = [(inout Int) throws -> (inout () -> Void) -> Void]().count _ = [String: (@autoclosure (Int) -> Int32) -> Void]().keys // expected-error {{argument type of @autoclosure parameter must be '()'}} let _ = [(Int) -> throws Int]() // expected-error{{'throws' may only occur before '->'}} let _ = [Int throws Int](); // expected-error{{'throws' may only occur before '->'}} expected-error {{consecutive statements on a line must be separated by ';'}} } protocol P1 {} protocol P2 {} protocol P3 {} func compositionType() { _ = P1 & P2 // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self'}} {{7-7=(}} {{14-14=).self}} _ = P1 & P2.self // expected-error {{binary operator '&' cannot be applied to operands of type 'P1.Protocol' and 'P2.Protocol'}} expected-note {{overloads}} _ = (P1 & P2).self // Ok. _ = (P1 & (P2)).self // FIXME: OK? while `typealias P = P1 & (P2)` is rejected. _ = (P1 & (P2, P3)).self // expected-error {{non-protocol, non-class type '(P2, P3)' cannot be used within a protocol-constrained type}} _ = (P1 & Int).self // expected-error {{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}} _ = (P1? & P2).self // expected-error {{non-protocol, non-class type 'P1?' cannot be used within a protocol-constrained type}} _ = (P1 & P2.Type).self // expected-error {{non-protocol, non-class type 'P2.Type' cannot be used within a protocol-constrained type}} _ = P1 & P2 -> P3 // expected-error @-1 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}} // expected-error @-2 {{expected member name or constructor call after type name}} // expected-note @-3 {{use '.self'}} {{7-7=(}} {{20-20=).self}} _ = P1 & P2 -> P3 & P1 -> Int // expected-error @-1 {{single argument function types require parentheses}} {{18-18=(}} {{25-25=)}} // expected-error @-2 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}} // expected-error @-3 {{expected member name or constructor call after type name}} // expected-note @-4 {{use '.self'}} {{7-7=(}} {{32-32=).self}} _ = (() -> P1 & P2).self // Ok _ = (P1 & P2 -> P3 & P2).self // expected-error {{single argument function types require parentheses}} {{8-8=(}} {{15-15=)}} _ = ((P1 & P2) -> (P3 & P2) -> P1 & Any).self // Ok } func complexSequence() { // (assign_expr // (discard_assignment_expr) // (try_expr // (type_expr typerepr='P1 & P2 throws -> P3 & P1'))) _ = try P1 & P2 throws -> P3 & P1 // expected-warning @-1 {{no calls to throwing functions occur within 'try' expression}} // expected-error @-2 {{single argument function types require parentheses}} {{none}} {{11-11=(}} {{18-18=)}} // expected-error @-3 {{expected member name or constructor call after type name}} // expected-note @-4 {{use '.self' to reference the type object}} {{11-11=(}} {{36-36=).self}} } func takesVoid(f: Void -> ()) {} // expected-error {{single argument function types require parentheses}} {{19-23=()}} func takesOneArg<T>(_: T.Type) {} func takesTwoArgs<T>(_: T.Type, _: Int) {} func testMissingSelf() { // None of these were not caught in Swift 3. // See test/Compatibility/type_expr.swift. takesOneArg(Int) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesOneArg(Swift.Int) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesTwoArgs(Int, 0) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} takesTwoArgs(Swift.Int, 0) // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} Swift.Int // expected-warning {{expression of type 'Int.Type' is unused}} // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} _ = Swift.Int // expected-error@-1 {{expected member name or constructor call after type name}} // expected-note@-2 {{add arguments after the type to construct a value of the type}} // expected-note@-3 {{use '.self' to reference the type object}} }
a6d43e9e38f0c568dadc5023f906bef5
39.994169
186
0.623498
false
false
false
false
woodcockjosh/FastContact
refs/heads/master
Core/FastContactListManager.swift
mit
1
// // FastContactDelegate.swift // FastContact // // Created by Josh Woodcock on 8/22/15. // Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved. // import UIKit public class FastContactListManager { private var _onBuildListFilterBlocks: Array<()->Void> = Array(); private var _updateBlock: ()->Void; private var _onBuildListGroupingBlocks: Array<()->Void> = Array(); private var _lists: Array<Array<Array<IListItem>>> = Array<Array<Array<IListItem>>>(); private var _itemsBeforeEmptyListMax: Int; public init(listCount: Int, itemsBeforeEmptyListMax: Int, updateBlock: ()->Void) { self._updateBlock = updateBlock; self._itemsBeforeEmptyListMax = itemsBeforeEmptyListMax; self._lists = self._getDefaultLists(listCount); } public func setItemsInListForState(listIndex: Int, list: Array<Array<IListItem>>, state: FastContactViewState) { var listToSet = list; // Add a fillter empty cell if(state == .ManyWithAccessAndFiller || state == .ManyNoAccess || state == .ManyBlockedAccess){ if(listToSet.count == 0){ listToSet.append(Array<IListItem>()); } if(list[0].count <= _itemsBeforeEmptyListMax) { listToSet[0].append(EmptyListItem()); }else{ listToSet[0].insert(EmptyListItem(), atIndex: 0); } } _lists[listIndex] = listToSet; self.updateListsForState(state); } public func updateListsForState(state: FastContactViewState) { self._updateBlock(); } public func getLists() -> Array<Array<Array<IListItem>>> { return _lists; } private func _getDefaultLists(listCount: Int)->Array<Array<Array<IListItem>>> { var lists = Array<Array<Array<IListItem>>>(); for (var i = 0; i < listCount; i++) { var list = Array<Array<IListItem>>(); var oneEmptyListSection = Array<IListItem>(); var oneEmptyListItem = EmptyListItem(); oneEmptyListSection.append(oneEmptyListItem); list.append(oneEmptyListSection); lists.append(list); } return lists; } private func _listIsEmpty(list: Array<Array<IListItem>>)->Bool{ if((list.count == 0 && list[0].count == 0 && list[0][0] is EmptyListItem) || list.count == 0) { return true; }else{ return false; } } }
359cf08445145e63160dd58407865382
33.013333
116
0.59098
false
false
false
false
salemoh/GoldenQuraniOS
refs/heads/master
GoldenQuranSwift/GoldenQuranSwift/AppDelegate.swift
mit
1
// // AppDelegate.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 2/12/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import UIKit import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. IQKeyboardManager.sharedManager().enable = true UINavigationBar.appearance().barTintColor = UIColor(patternImage:UIImage(named:"textureHeader")!) UINavigationBar.appearance().tintColor = UIColor.orange UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.orange , NSFontAttributeName:FontManager.fontWithSize(size: 17.0 , isBold: true)] UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: FontManager.fontWithSize(size: 15.0)], for: .normal) LocationManager.shared.startLocationUpdating() if Mus7afManager.shared.hasMushaf { UIApplication.shared.windows[0].rootViewController = Constants.storyboard.mushaf.instantiateInitialViewController() } NotificationsManager().fridayNotification() let currentRecititation = RecitationManager.getRecitationWithId(id: Mus7afManager.shared.currentMus7af.recitationId!) RecitationDownloadManager.downloadRecitation(recitation: currentRecititation, soraNo: 2, verseNo: 3) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
21a368359d38f23db6f2f01a43b0a405
49.666667
285
0.745514
false
false
false
false
Kawoou/FlexibleImage
refs/heads/master
Sources/Filter/ColorBurnFilter.swift
mit
1
// // ColorBurnFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(OSX) import UIKit #else import AppKit #endif #if !os(watchOS) import Metal #endif internal class ColorBurnFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "ColorBurnFilter" } } internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0) // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { let factors: [Float] = [color.r, color.g, color.b, color.a] for i in 0..<factors.count { var factor = factors[i] let size = max(MemoryLayout<Float>.size, 16) let options: MTLResourceOptions if #available(iOS 9.0, *) { options = [.storageModeShared] } else { options = [.cpuCacheModeWriteCombined] } let buffer = device.device.makeBuffer( bytes: &factor, length: size, options: options ) #if swift(>=4.0) commandEncoder.setBuffer(buffer, offset: 0, index: i) #else commandEncoder.setBuffer(buffer, offset: 0, at: i) #endif } return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { guard let context = device.context else { return false } let color = FIColor( red: CGFloat(self.color.r), green: CGFloat(self.color.g), blue: CGFloat(self.color.b), alpha: CGFloat(self.color.a) ) context.saveGState() context.setBlendMode(.colorBurn) context.setFillColor(color.cgColor) context.fill(device.drawRect!) context.restoreGState() return super.processNone(device) } }
e7fa10e53efcec5050a170586108d6eb
26.931034
160
0.515638
false
false
false
false
nodes-vapor/ironman
refs/heads/master
App/Models/Races/Race.swift
mit
1
import Vapor import Fluent final class Race: Model { var id: Node? var name: String var btnImagePath: String var startAt: String var liveDataProvider: String var liveDataEventId: String var liveStreamUrl: String var youtubeChannel: String var isLiveStreamEnabled: Bool var isLiveStreamActive: Bool var isGeoTrackingEnabled: Bool var sponsorImagePath: String var eventInfoImagePath: String var eventText: String var touriestAppLinkIos: String var touriestAppLinkAndroid: String var fbPage: String var hashtag: String var isActive: Bool var createdAt: String var updatedAt: String init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") isActive = try node.extract("is_active") btnImagePath = try node.extract("btn_image_path") startAt = try node.extract("start_at") liveDataProvider = try node.extract("live_data_provider") liveDataEventId = try node.extract("live_data_event_id") liveStreamUrl = try node.extract("live_stream_url") youtubeChannel = try node.extract("youtube_channel") isLiveStreamEnabled = try node.extract("is_live_stream_enabled") isLiveStreamActive = try node.extract("is_live_stream_active") isGeoTrackingEnabled = try node.extract("is_geo_tracking_enabled") sponsorImagePath = try node.extract("sponsor_image_path") eventInfoImagePath = try node.extract("event_info_image_path") eventText = try node.extract("event_text") touriestAppLinkIos = try node.extract("tourist_app_link_ios") touriestAppLinkAndroid = try node.extract("tourist_app_link_android") fbPage = try node.extract("fb_page") hashtag = try node.extract("hashtag") createdAt = try node.extract("created_at") updatedAt = try node.extract("updated_at") } public func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": Node(name), "btn_image_path": Node(btnImagePath), "sponsor_image_path": sponsorImagePath, "event_info_image_path" : Node(eventInfoImagePath), "event_text": Node(eventText), "start_at": Node(startAt), "live_data_provider": Node(liveDataProvider), "live_data_event_id": Node(liveDataEventId), "is_geo_tracking_enabled": Node(isGeoTrackingEnabled), "is_live_stream_enabled": Node(isLiveStreamEnabled), "is_live_stream_active": Node(isLiveStreamActive), "hashtag": Node(hashtag), "live_stream_url": Node(liveStreamUrl), "youtube_channel": Node(youtubeChannel), "tourist_app_link_ios": Node(touriestAppLinkIos), "tourist_app_link_android": Node(touriestAppLinkAndroid), "is_active": Node(isActive), "created_at": Node(createdAt), "updated_at": Node(updatedAt) ]) } func makeJSON() throws -> JSON { return try JSON(node: [ "id": id, "name": Node(name), "btnImageUrl": Node(btnImagePath), "sponsorImageUrl": Node(sponsorImagePath), "eventInfoImageUrl" : Node(eventInfoImagePath), "eventText": Node(eventText), "startDatetime": Node(startAt), "liveDataProvider": Node(liveDataProvider), "liveDataProviderEventId": Node(liveDataEventId), "isGeoTrackingEnabled": Node(isGeoTrackingEnabled), "isLiveStreamEnabled": Node(isLiveStreamEnabled), "isLiveStreamActive": Node(isLiveStreamActive), "hashTag": Node(hashtag), "liveStreamUrl": Node(liveStreamUrl), "youtubeChannel": Node(youtubeChannel), "touristAppLinkIos": Node(touriestAppLinkIos), "touristAppLinkAndroid": Node(touriestAppLinkAndroid) ]) } static func prepare(_ database: Database) throws { try database.create("races") { races in races.id() races.string("name") races.string("btn_image_path", optional: true) races.string("start_at", optional: true) races.string("live_data_provider", optional: true) races.string("live_data_event_id", optional: true) races.string("live_stream_url", optional: true) races.string("youtube_channel", optional: true) races.bool("is_live_stream_enabled", optional: true) races.bool("is_live_stream_active", optional: true) races.bool("is_geo_tracking_enabled", optional: true) races.string("sponsor_image_path", optional: true) races.string("event_info_image_path", optional: true) races.data("event_text", optional: true) races.string("tourist_app_link_ios", optional: true) races.string("tourist_app_link_android", optional: true) races.string("fb_page", optional: true) races.string("hashtag", optional: true) races.bool("is_active", optional: true) races.string("created_at", optional: true) races.string("updated_at", optional: true) } } static func revert(_ database: Database) throws { try database.delete("races") } } extension Race { func rss() throws -> Children<Rss> { return children() } }
9cf0771f2a0327242213f17acaf23c82
34.347826
77
0.602355
false
false
false
false
dche/FlatColor
refs/heads/master
Sources/Theory.swift
mit
1
// // FlatColor - Theory.swift // // Copyright (c) 2016 The FlatColor authors. // Licensed under MIT License. import GLMath public extension Hsb { /// The complementary color of a HSB color. public var complement: Hsb { var c = self c.hue = mod(self.hue + Float.π, Float.tau) return c } /// Returns a pair of colors that are splited from the complementary color /// of a HSB color, /// /// These 2 colors have same distances to the complementary color on the /// color wheel. In our implementation, this distance is fixed to `30` /// degrees. public var splitComplement: (Hsb, Hsb) { let pi2 = Float.tau var c1 = self var c2 = self c1.hue = mod(self.hue + radians(150), pi2); c2.hue = mod(self.hue + radians(210), pi2); return (c1, c2) } /// Returns 2 pairs of complementary colors. The first colors of both pairs /// are the result of a HSB color's `split_complement`. public var doubleComplement: ((Hsb, Hsb), (Hsb, Hsb)) { let (c1, c2) = self.splitComplement return ((c1, c1.complement), (c2, c2.complement)) } /// Returns other 2 colors of triad colors that includes the receiver. public var triad: (Hsb, Hsb) { let a120: Float = radians(120) var c1 = self var c2 = self c1.hue = mod(self.hue + a120, Float.tau); c2.hue = mod(self.hue + a120 + a120, Float.tau); return (c1, c2) } /// Returns `n` colors that are analogous to the receiver. /// /// - note: /// * `[]` is returned if `n` is `0` or negative, /// * `span` can be larger than `2π`, /// * `span` can be negative. public func analog(by n: Int, span: Float) -> [Hsb] { guard n > 0 else { return [] } guard !span.isZero else { return [Hsb](repeating: self, count: n) } let d = span / Float(n) let h = self.hue var cs = [self] for i in 1 ..< n { var clr = self clr.hue = h + d * Float(i) cs.append(clr) } return cs } /// Returns `n` colors distributed on the color wheel evenly. /// /// The returned colors have same saturation and brightness as `self`. /// `self` is the first color in the array. /// /// If `n` is `0`, an empty array is returned. public func colorWheel(_ n: Int) -> [Hsb] { return self.analog(by: n, span: Float.tau) } /// Produces a color by adding white to the receiver. /// /// For `Hsb` color model, adding white means increasing the lightness. /// /// Parameter `amt` specifies absolute lightness to be added. public func tinted(_ amount: Float) -> Hsb { var c = self c.brightness = self.brightness + amount return c } /// Produces a list of `n` colors whose brightness increase monotonically /// and evenly. /// /// If `n` is `0`, returns an empty array. Other wise, the receiver is /// the first element of the vector and a color with full brightness is /// the last. public func tinted(by n: Int) -> [Hsb] { switch n { case _ where n < 1: return [] case 1: return [self] default: let b = self.brightness let d = (1 - b) / Float(n) var c = self var cs = [c] for i in 1 ..< n - 1 { c = self c.brightness = b + d * Float(i) cs.append(c) } c = self c.brightness = 1 cs.append(c) return cs } } /// Produces a color by adding black to the receiver. public func shaded(_ amount: Float) -> Hsb { var c = self c.brightness = self.brightness - amount return c } /// Produces`n` colors whose brightness decrease monotonically and evenly. public func shaded(by n: Int) -> [Hsb] { switch n { case _ where n < 1: return [] case 1: return [self] default: let b = self.brightness let d = b / Float(n) var c = self var cs = [c] for i in 1 ..< n - 1 { c = self c.brightness = b - d * Float(i) cs.append(c) } c = self c.brightness = 0 cs.append(c) return cs } } /// Produces a color by adding gray to the receiver, i.e., decreases its /// saturation. public func tone(_ amount: Float) -> Hsb { var c = self c.saturation = self.saturation - amount return c } /// Produces `n` colors whose saturation decrease monotonically and /// evenly. public func tone(by n: Int) -> [Hsb] { switch n { case _ where n < 1: return [] case 1: return [self] default: let s = self.saturation let d = s / Float(n) var c = self var cs = [c] for i in 1 ..< n - 1 { c = self c.saturation = s - d * Float(i) cs.append(c) } c = self c.saturation = 0 cs.append(c) return cs } } }
18569740e167f4d3d9b9c4297d6c87b5
28.353261
79
0.507128
false
false
false
false
yellowei/HWPicker
refs/heads/master
HWPhotoPicker-Swift/Category/String+Extention.swift
mit
1
// // String+Extention.swift // HWPicker // // Created by yellowei on 2017/5/26. // Copyright © 2017年 yellowei. All rights reserved. // import UIKit extension String { static func commonSize(with text: String?, fontNum: CGFloat, size: CGSize) -> (CGSize) { guard let text = text as NSString? else { return CGSize.zero } let font = UIFont.systemFont(ofSize: fontNum) let attributes = [NSFontAttributeName: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil) return rect.size; } static func commonSizeAutoWidth(with text: String?, fontNum: CGFloat, textHeigth: CGFloat) -> (CGSize) { guard let text = text as NSString? else { return CGSize.zero } let size = CGSize(width: CGFloat(MAXFLOAT), height: textHeigth) let font = UIFont.systemFont(ofSize: fontNum) let attributes = [NSFontAttributeName: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil) return rect.size; } static func commonSizeAutoHeight(with text: String?, fontNum: CGFloat, textWidth: CGFloat) -> (CGSize) { guard let text = text as NSString? else { return CGSize.zero } let size = CGSize(width: textWidth, height: CGFloat(MAXFLOAT)) let font = UIFont.systemFont(ofSize: fontNum) let attributes = [NSFontAttributeName: font] let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil) return rect.size; } }
e2543b2c4c16752cddf8b5e1af94bb73
34.555556
110
0.643229
false
false
false
false
psitaraman/Utilities
refs/heads/master
CommonUtilities/CommonUtilities/UIView+Utilities.swift
mit
1
/* MIT License Copyright (c) 2017 Praveen Sitaraman 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. */ // // UIView+Utilities.swift // CommonUtilities // // Created by Praveen Sitaraman on 6/5/17. // Copyright © 2017 Praveen Sitaraman. All rights reserved. // import UIKit extension UIView { func fillWithView(_ subView: UIView, topPadding: CGFloat = 0.0, bottomPadding: CGFloat = 0.0, leadingPadding: CGFloat = 0.0, trailingPadding: CGFloat = 0.0) { // exit out if re-adding subview to superview guard !self.subviews.contains(subView) else { return } subView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(subView) let topConstraint = NSLayoutConstraint(item: subView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0 + topPadding) let bottomConstraint = NSLayoutConstraint(item: subView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0 + bottomPadding) let leadingConstraint = NSLayoutConstraint(item: subView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0 + leadingPadding) let trailingConstraint = NSLayoutConstraint(item: subView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0 + trailingPadding) self.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint]) } }
5fbfb983fa1ec3e3610c7dd8f68d71b8
48.615385
193
0.737209
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
ResearchKit/ResearchKitDemo/ResearchKitDemo/ConsentDocument.swift
mit
3
// // ConsentDocument.swift // ResearchKitDemo // // Created by Domenico on 18/06/15. // Copyright (c) 2015 Domenico. All rights reserved. // import ResearchKit public var ConsentDocument: ORKConsentDocument{ let consentDocument = ORKConsentDocument() consentDocument.title = "Example title" // Sections let consentSectionTypes: [ORKConsentSectionType] = [ .Overview, .DataGathering, .Privacy, .DataUse, .TimeCommitment, .StudySurvey, .StudyTasks, .Withdrawing ] var consentSections: [ORKConsentSection] = consentSectionTypes.map{ consentSectionType in let consentSection = ORKConsentSection(type: consentSectionType) consentSection.summary = "If you wish to complete this study..." consentSection.content = "In this study you will be asked five (wait, no, three!) questions.You will also have your voice recorded for ten seconds." return consentSection } consentDocument.sections = consentSections // Signature consentDocument.addSignature(ORKConsentSignature(forPersonWithTitle: nil, dateFormatString: nil, identifier: "ConsentDocumentParticipantSignature")) return consentDocument }
c45cf30f443dad7e28ffe4bd78addd21
29.512195
156
0.698641
false
false
false
false
lennet/proNotes
refs/heads/master
app/proNotes/Model/DocumentLayer/ImageLayer.swift
mit
1
// // ImageLayer.swift // proNotes // // Created by Leo Thomas on 20/02/16. // Copyright © 2016 leonardthomas. All rights reserved. // import UIKit class ImageLayer: MovableLayer { var image: UIImage? { get { return ImageCache.sharedInstance[imageKey] } set { ImageCache.sharedInstance[imageKey] = newValue } } let imageKey = UUID().uuidString init(index: Int, docPage: DocumentPage, origin: CGPoint, size: CGSize?, image: UIImage) { super.init(index: index, type: .image, docPage: docPage, origin: origin, size: size ?? image.size) self.image = image } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder, type: .image) type = .image if let imageData = aDecoder.decodeObject(forKey: imageDataKey) as? Data { image = UIImage(data: imageData)! } else { image = UIImage() } } required init(coder aDecoder: NSCoder, type: DocumentLayerType) { fatalError("init(coder:type:) has not been implemented") } private final let imageDataKey = "imageData" override func encode(with aCoder: NSCoder) { guard let image = image else { return } if let imageData = UIImageJPEGRepresentation(image, 1.0) { aCoder.encode(imageData, forKey: imageDataKey) } else { print("Could not save drawing Image") } super.encode(with: aCoder) } override func undoAction(_ oldObject: Any?) { if let image = oldObject as? UIImage { self.image = image } else { super.undoAction(oldObject) } } override func isEqual(_ object: Any?) -> Bool { guard object is ImageLayer else { return false } if !super.isEqual(object) { return false } return true } }
c67227b22bc778977492d759741e95a7
24.179487
106
0.57332
false
false
false
false
gustavoavena/MOPT
refs/heads/master
MOPT/Comment.swift
mit
1
// // Comment.swift // MOPT // // Created by Gustavo Avena on 204//17. // Copyright © 2017 Gustavo Avena. All rights reserved. // import UIKit class Comment: NSObject, MoptObject { let ID: ObjectID let createdAt: Date = Date() let creatorID: ObjectID let topicID: ObjectID var text: String var topic: Topic { get { return Cache.get(objectType: .topic, objectWithID: topicID) as! Topic // FIXME: make sure this is never nil! } } var creator: User { get { return Cache.get(objectType: .user, objectWithID: creatorID) as! User // FIXME: make sure this is never nil! } } init(ID: String, creatorID: ObjectID, text: String, topicID: ObjectID) { self.ID = ID self.creatorID = creatorID self.text = text self.topicID = topicID } }
9cac255a60aaaad15842166f630b0c4e
18
111
0.67009
false
false
false
false
xebia-france/XebiaSkiExtension
refs/heads/master
XebiaSkiFramework/Models/SkiResort.swift
apache-2.0
1
// // SkiResort.swift // XebiaSki // // Created by JC on 30/11/14. // Copyright (c) 2014 Xebia IT Architechts. All rights reserved. // public class SkiResort: NSObject, NSCoding { public var name: String public var photoURL: NSURL public var temperature: Int public init(name: String, photoURL: NSURL, temperature: Int) { self.name = name self.photoURL = photoURL self.temperature = temperature } public required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as String self.photoURL = NSURL(string: aDecoder.decodeObjectForKey("photoURL") as String)! self.temperature = aDecoder.decodeObjectForKey("temperature") as Int } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.photoURL.absoluteString, forKey: "photoURL") aCoder.encodeObject(self.temperature, forKey: "temperature") } }
1667eab2277eebfa83557337439479b6
31.677419
89
0.674235
false
false
false
false
iamtomcat/color
refs/heads/master
Color/HSV.swift
mit
1
// // HSV.swift // ColorSpace // // Created by Tom Clark on 2016-03-07. // Copyright © 2016 FluidDynamics. All rights reserved. // import Foundation public struct HSV { public let h: CGFloat public let s: CGFloat public let v: CGFloat public let a: CGFloat } extension HSV: ColorData { var toHSV: HSV { return self } var toRGB: RGB { var r = CGFloat(0.0), g = CGFloat(0.0), b = CGFloat(0.0) let i = floor(h * 6) let f = h * 6 - i; let p = v * (1 - s); let q = v * (1 - f * s); let t = v * (1 - (1 - f) * s); switch(i % 6){ case 0: r = v; g = t; b = p case 1: r = q; g = v; b = p case 2: r = p; g = v; b = t case 3: r = p; g = q; b = v case 4: r = t; g = p; b = v case 5: r = v; g = p; b = q default: return RGB(r: 1.0, g: 1.0, b: 1.0, a: 1.0) } return RGB(r: r, g: g, b: b, a: a) } var toHSL: HSL { return self.toRGB.toHSL } }
91592022fbb35d56957c7bf096e1feac
18.893617
60
0.497326
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKit/model/TKSegment+StationaryType.swift
apache-2.0
1
// // TKSegment+StationaryType.swift // TripKit // // Created by Adrian Schönig on 19.03.20. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // import Foundation extension TKSegment { /// Stationary segment type /// /// For details see [TripGo API F.A.Q.](https://developer.tripgo.com/faq/) public enum StationaryType: String { case parkingOnStreet = "stationary_parking-onstreet" case parkingOffStreet = "stationary_parking-offstreet" case wait = "stationary_wait" case transfer = "stationary_transfer" case vehicleCollect = "stationary_vehicle-collect" case vehicleReturn = "stationary_vehicle-return" case airportCheckIn = "stationary_airport-checkin" case airportCheckOut = "stationary_airport-checkout" case airportTransfer = "stationary_airport-transfer" } /// Type for a stationary segment;,`nil` for non-stationary segments public var stationaryType: StationaryType? { StationaryType(rawValue: modeInfo?.identifier ?? "") } }
60c6614c3c90b9d48dec070224c0c522
30.59375
76
0.718101
false
false
false
false
felimuno/FMProgressBarView
refs/heads/master
FMProgressBarViewDemo/ViewController.swift
mit
1
// // ViewController.swift // FMProgressBarViewDemo // // Created by felipe munoz on 7/8/15. // Copyright (c) 2015 felipe munoz. All rights reserved. // import UIKit import FMProgressBarView class ViewController: UIViewController { @IBOutlet weak var mySlider: UISlider! @IBOutlet weak var pbar: FMProgressBarView! @IBOutlet weak var pbar2: FMProgressBarView! override func viewDidLoad() { super.viewDidLoad() //you can set the parameters on Interface Builder or programmatically /* self.pbar.title = "Custom Text.." self.pbar.titleFont = UIFont(name:"Helvetica", size: 27.0)! self.pbar.titleCompletedColor = UIColor.blackColor() self.pbar.titleLoadingColor = UIColor.whiteColor() self.pbar.backgroundCompletedColor = UIColor.greenColor() self.pbar.backgroundLoadingColor = UIColor.redColor() self.pbar.borderWidth = 1.0 self.pbar.borderColor = UIColor.blueColor() self.pbar2.useImages = true */ self.pbar.titleFont = UIFont(name:"Helvetica", size: 27.0)! self.pbar2.titleFont = UIFont(name:"Helvetica", size: 27.0)! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func valueChanged(sender: UISlider) { var currentValue = sender.value/sender.maximumValue pbar.progressPercent = CGFloat(currentValue) pbar2.progressPercent = CGFloat(currentValue) } }
ade635643f0850a95e87711e116d118d
29.557692
77
0.660793
false
false
false
false
OSzhou/MyTestDemo
refs/heads/master
17_SwiftTestCode/TestCode/CustomCamera/WBVideoPreview.swift
apache-2.0
1
// // WBVideoPreview.swift // TestCode // // Created by Zhouheng on 2020/6/29. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit import AVFoundation class WBVideoPreview: UIView { var captureSessionsion: AVCaptureSession? { set { let layer = self.layer as? AVCaptureVideoPreviewLayer layer?.session = newValue } get { let layer = self.layer as? AVCaptureVideoPreviewLayer return layer?.session } } override init(frame: CGRect) { super.init(frame: frame) let layer = self.layer as? AVCaptureVideoPreviewLayer layer?.videoGravity = .resizeAspectFill } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// open interface func captureDevicePointForPoint(_ point: CGPoint) -> CGPoint { let layer = self.layer as? AVCaptureVideoPreviewLayer return layer?.captureDevicePointConverted(fromLayerPoint: point) ?? .zero } static override var layerClass: AnyClass { return AVCaptureVideoPreviewLayer.self } }
ad2feea95531928822794479def5db11
23.469388
81
0.615513
false
false
false
false
GRSource/YZPopOverView
refs/heads/master
YZPopOverView/YZPopOverView.swift
mit
1
// // YZPopOverView.swift // BatourTool // // Created by iOS_Dev5 on 2017/2/15. // Copyright © 2017年 GRSource. All rights reserved. // import UIKit class YZPopOverView: NSObject { static let sharedInstance = YZPopOverView() private static var gTintColor: UIColor? private static var gTitleFont: UIFont? private var observing = false private var menuView: YZPopOverMenuView? class func showMenuInView(_ view: UIView, fromRect rect: CGRect, menuItems: [YZPopOverItem]) { self.sharedInstance.showMenuInView(view, fromRect: rect, menuItems: menuItems) } func showMenuInView(_ view: UIView, fromRect rect: CGRect, menuItems: [YZPopOverItem]) { if menuView != nil { menuView?.dismissMenu(false) menuView = nil } if !observing { observing = true NotificationCenter.default.addObserver(self, selector: #selector(orientationWillChange(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: nil) } menuView = YZPopOverMenuView() menuView?.showMenuInView(view, rect: rect, menuItems: menuItems) } func orientationWillChange(_ sender: Notification) { self.dismissMenu() } func dismissMenu() { if menuView != nil { menuView!.dismissMenu(false) menuView = nil } if observing { observing = false NotificationCenter.default.removeObserver(self) } } class func dismissMenu() { self.sharedInstance.dismissMenu() } class func tintColor() -> UIColor? { return gTintColor } class func setTintColor(_ tintColor: UIColor) { gTintColor = tintColor } class func titleFont() -> UIFont? { return gTitleFont } class func setTitleFont(_ titleFont: UIFont) { gTitleFont = titleFont } }
becd43372833783cda13190b830a3f09
25.76
188
0.610862
false
false
false
false
victorchee/Live
refs/heads/master
Live/RTMP/RTMPMessage.swift
mit
1
// // RTMPMessage.swift // RTMP // // Created by VictorChee on 2016/12/21. // Copyright © 2016年 VictorChee. All rights reserved. // import Foundation enum MessageType: UInt8 { case SetChunkSize = 0x01 case Abort = 0x02 case Acknowledgement = 0x03 case UserControl = 0x04 case WindowAckSize = 0x05 case SetPeerBandwidth = 0x06 case Audio = 0x08 case Video = 0x09 case AMF3Data = 0x0f case AMF3SharedObject = 0x10 case AMF3Command = 0x11 case AMF0Data = 0x12 case AMF0SharedObject = 0x13 case AMF0Command = 0x14 case Aggregate = 0x16 case Unknown = 0xff } class RTMPMessage { /** +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | Message Type | Payload length | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | Timestamp | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | Stream ID | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Message Header */ /// 1B message type var messageType: MessageType! /// 3B message payload length var payloadLength: Int { get { return payload.count } set { } } /// RTMP的时间戳在发送音视频之前都为零,开始发送音视频消息的时候只要保证时间戳是单增的基本就可以正常播放音视频 /// 4B timestamp var timestamp: UInt32 = 0 // 毫秒 /// 4B stream id var messageStreamID: UInt32 = 0 /// Message payload var payload = [UInt8]() // Empty initialize for subclass to override init() {} init(messageType: MessageType) { self.messageType = messageType } class func create(messageType: MessageType) -> RTMPMessage? { switch messageType { case .SetChunkSize: return RTMPSetChunkSizeMessage() case .Abort: return RTMPAbortMessage() case .UserControl: return nil case .WindowAckSize: return RTMPWindowAckSizeMessage() case .SetPeerBandwidth: return RTMPSetPeerBandwidthMessage() case .Audio: return RTMPAudioMessage() case .Video: return RTMPVideoMessage() case .AMF0Command: return RTMPCommandMessage() case .AMF0Data: return RTMPDataMessage() case .Acknowledgement: return RTMPAcknowledgementMessage() default: return nil } } } /// 设置块的大小,通知对端用使用新的块大小,共4B final class RTMPSetChunkSizeMessage: RTMPMessage { /* 默认为128B,客户端或服务端可以修改此值,并用该消息通知另一端,不能小于1B,通常不小于128B。每个方向的大小是独立的。 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ |0| chunk size | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ var chunkSize = 0 override init() { super.init(messageType: .SetChunkSize) } init(chunkSize: Int) { super.init(messageType: .SetChunkSize) self.chunkSize = chunkSize } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += Int32(chunkSize).bigEndian.bytes return super.payload } set { chunkSize = Int(Int32(bytes: newValue).bigEndian) } } } /// 当消息包分成多个chunk,已经发送若干包,若不再发送,就是Abort Message,通知接收端终止接收消息,并且丢弃已经接收的Chunk,共4B final class RTMPAbortMessage: RTMPMessage { /* 应用可能在关闭的时候发送该消息,用来表明后面的消息没有必要继续处理了 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | chunk stream id | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ private var chunkStreamID: Int32! override init() { super.init(messageType: .Abort) } init(chunkStreamID: Int32) { super.init(messageType: .Abort) self.chunkStreamID = chunkStreamID } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += chunkStreamID.bigEndian.bytes return super.payload } set { chunkStreamID = Int32(bytes: newValue).bigEndian } } } /// 确认消息,客户端或服务端在接收到数量与Window size相等的字节后发送确认消息到对方。Window size是在没有接收到接收者发送的确认消息之前发送的字节数的最大值。服务端在建立连接之后发送窗口大小。共4B final class RTMPAcknowledgementMessage: RTMPMessage { /** 到当前时间位置收到的总字节数 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | sequence number | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ var sequenceNumber: Int32! override init() { super.init(messageType: .Acknowledgement) } init(sequenceNumber: Int32) { super.init(messageType: .Acknowledgement) self.sequenceNumber = sequenceNumber } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += sequenceNumber.bigEndian.bytes return super.payload } set { sequenceNumber = Int32(bytes: newValue).bigEndian } } } /// 客户端或服务端发送该消息来通知对端发送确认消息所使用的Window Size,并等待接受端发送Acknowledgement消息,接受端在接受到Window Size字节数据后需要发送Acknowledgement消息确认 final class RTMPWindowAckSizeMessage: RTMPMessage { /** Window size就是一次发送数据,接收方可不作应答的最大长度 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | acknowledgement window size | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ var windowAckSize: UInt32! override init() { super.init(messageType: .WindowAckSize) } init(windowAckSize: UInt32) { super.init(messageType: .WindowAckSize) self.windowAckSize = windowAckSize self.timestamp = 0 } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += windowAckSize.bigEndian.bytes return super.payload } set { windowAckSize = UInt32(bytes: newValue).bigEndian } } } /// 客户端或服务端发送该消息来限制对端的输出带宽。接收端收到消息后,通过将已发送但未被确认的数据总数限制为该消息指定的Widnow Size,来实现限制输出带宽的目的。如果Window Size与上一个不同,则该消息的接收端应该向消息的发送端发送Window Size确认消息。 final class RTMPSetPeerBandwidthMessage: RTMPMessage { /** +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | acknowledgement window size | limit type | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ enum LimitType: UInt8 { /// 消息接收端应该将输出带宽限制为指定Window Size大小 case Hard = 0x00 /// 消息接收端应该将输出带宽限制为指定Window Size和当前的较小的值 case Soft = 0x01 /// 如果上一个消息的限制类型为Hard,则该消息同样为Hard,否则抛弃该消息 case Dynamic = 0x02 case Unknown = 0xFF } var ackWindowSize: UInt32 = 0 var limit = LimitType.Hard override init() { super.init(messageType: .SetPeerBandwidth) } init(ackWindowSize: UInt32, limitType: LimitType, messageStreamID: UInt32) { super.init(messageType: .SetPeerBandwidth) self.ackWindowSize = ackWindowSize self.messageStreamID = messageStreamID } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += ackWindowSize.bigEndian.bytes super.payload += [limit.rawValue] return super.payload } set { if super.payload == newValue { return } self.ackWindowSize = UInt32(bytes: Array(newValue[0...3])).bigEndian self.limit = LimitType(rawValue: newValue[4])! } } } /// Command Message(命令消息,Message Type ID=17或20):表示在客户端盒服务器间传递的在对端执行某些操作的命令消息,如connect表示连接对端,对端如果同意连接的话会记录发送端信息并返回连接成功消息,publish表示开始向对方推流,接受端接到命令后准备好接受对端发送的流信息,后面会对比较常见的Command Message具体介绍。当信息使用AMF0编码时,Message Type ID=20,AMF3编码时Message Type ID=17. final class RTMPCommandMessage: RTMPMessage { var commandName = "" /// 用来标识command类型的消息的,服务器返回的_result消息可以通过这个来区分是对哪个命令的回应 var transactionID = 0 var commandObjects = [Amf0Data]() override init() { super.init(messageType: .AMF0Command) } init(commandName: String, transactionID: Int, messageStreamID: UInt32) { super.init(messageType: .AMF0Command) self.commandName = commandName self.transactionID = transactionID self.messageStreamID = messageStreamID } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += Amf0String(value: commandName).dataInBytes super.payload += Amf0Number(value: transactionID).dataInBytes for object in commandObjects { super.payload += object.dataInBytes } return super.payload } set { let inputStream = ByteArrayInputStream(byteArray: newValue) guard let commandName = Amf0String.decode(inputStream, isAmfObjectKey: false) else { return } self.commandName = commandName self.transactionID = Int(Amf0Number.decode(inputStream)) while inputStream.remainLength > 0 { guard let object = Amf0Data.create(inputStream) else { return } commandObjects.append(object) } } } } /// Data Message(数据消息,Message Type ID=15或18):传递一些元数据(MetaData,比如视频名,分辨率等等)或者用户自定义的一些消息。当信息使用AMF0编码时,Message Type ID=18,AMF3编码时Message Type ID=15. final class RTMPDataMessage: RTMPMessage { private var type: String! var objects = [Amf0Data]() override init() { super.init(messageType: .AMF0Data) } init(type: String, messageStreamID: UInt32) { super.init(messageType: .AMF0Data) self.type = type self.messageStreamID = messageStreamID } override var payload: [UInt8] { get { guard super.payload.isEmpty else { return super.payload } super.payload += Amf0String(value: type).dataInBytes for object in objects { super.payload += object.dataInBytes } return super.payload } set { let inputStream = ByteArrayInputStream(byteArray: newValue) guard let type = Amf0String.decode(inputStream, isAmfObjectKey: false) else { return } self.type = type while inputStream.remainLength > 0 { guard let object = Amf0Data.create(inputStream) else { return } objects.append(object) } } } } /// Audio Message(音频信息,Message Type ID=8):音频数据。 final class RTMPAudioMessage: RTMPMessage { override init() { super.init(messageType: .Audio) } init(audioBuffer: [UInt8], messageStreamID: UInt32) { super.init(messageType: .Audio) self.messageStreamID = messageStreamID self.payload = audioBuffer } override var payload: [UInt8] { get { return super.payload } set { guard super.payload != newValue else { return } super.payload = newValue } } } /// Video Message(视频信息,Message Type ID=9):视频数据。 final class RTMPVideoMessage: RTMPMessage { override init() { super.init(messageType: .Video) } init(videoBuffer: [UInt8], messageStreamID: UInt32) { super.init(messageType: .Video) self.messageStreamID = messageStreamID self.payload = videoBuffer } override var payload: [UInt8] { get { return super.payload } set { guard super.payload != newValue else { return } super.payload = newValue } } }
38daebf2ac7c6acb9c4877a2180ed321
30.765903
246
0.537568
false
false
false
false
babyboy18/swift_code
refs/heads/master
Swifter/SwifterUsers.swift
mit
1
// // SwifterUsers.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /* GET account/settings Returns settings (including current trend, geo and sleep time information) for the authenticating user. */ public func getAccountSettingsWithSuccess(success: ((settings: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "account/settings.json" self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(settings: json.object) return }, failure: failure) } /* GET account/verify_credentials Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid. */ public func getAccountVerifyCredentials(includeEntities: Bool?, skipStatus: Bool?, success: ((myInfo: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "account/verify_credentials.json" var parameters = Dictionary<String, AnyObject>() if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(myInfo: json.object) return }, failure: failure) } /* POST account/settings Updates the authenticating user's settings. */ public func postAccountSettings(trendLocationWOEID: Int?, sleepTimeEnabled: Bool?, startSleepTime: Int?, endSleepTime: Int?, timeZone: String?, lang: String?, success: ((settings: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { assert(trendLocationWOEID != nil || sleepTimeEnabled != nil || startSleepTime != nil || endSleepTime != nil || timeZone != nil || lang != nil, "At least one or more should be provided when executing this request") let path = "account/settings.json" var parameters = Dictionary<String, AnyObject>() if trendLocationWOEID != nil { parameters["trend_location_woeid"] = trendLocationWOEID! } if sleepTimeEnabled != nil { parameters["sleep_time_enabled"] = sleepTimeEnabled! } if startSleepTime != nil { parameters["start_sleep_time"] = startSleepTime! } if endSleepTime != nil { parameters["end_sleep_time"] = endSleepTime! } if timeZone != nil { parameters["time_zone"] = timeZone! } if lang != nil { parameters["lang"] = lang! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(settings: json.object) return }, failure: failure) } /* POST account/update_delivery_device Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable SMS updates. */ public func postAccountUpdateDeliveryDeviceSMS(device: Bool, includeEntities: Bool?, success: ((deliveryDeviceSettings: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "account/update_delivery_device.json" var parameters = Dictionary<String, AnyObject>() if device { parameters["device"] = "sms" } else { parameters["device"] = "none" } if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(deliveryDeviceSettings: json.object) return }, failure: failure) } /* POST account/update_profile Sets values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated. */ public func postAccountUpdateProfileWithName(name: String?, url: String?, location: String?, description: String?, includeEntities: Bool?, skipStatus: Bool?, success: ((profile: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { assert(name != nil || url != nil || location != nil || description != nil || includeEntities != nil || skipStatus != nil) let path = "account/update_profile.json" var parameters = Dictionary<String, AnyObject>() if name != nil { parameters["name"] = name! } if url != nil { parameters["url"] = url! } if location != nil { parameters["location"] = location! } if description != nil { parameters["description"] = description! } if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(profile: json.object) return }, failure: failure) } /* POST account/update_profile_background_image Updates the authenticating user's profile background image. This method can also be used to enable or disable the profile background image. Although each parameter is marked as optional, at least one of image, tile or use must be provided when making this request. */ public func postAccountUpdateProfileBackgroundImage(imageData: NSData?, title: String?, includeEntities: Bool?, use: Bool?, success: ((profile: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { assert(imageData != nil || title != nil || use != nil, "At least one of image, tile or use must be provided when making this request") let path = "account/update_profile_background_image.json" var parameters = Dictionary<String, AnyObject>() if imageData != nil { parameters["image"] = imageData!.base64EncodedStringWithOptions(nil) } if title != nil { parameters["title"] = title! } if includeEntities != nil { parameters["include_entities"] = includeEntities! } if use != nil { parameters["use"] = use! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(profile: json.object) return }, failure: failure) } /* POST account/update_profile_colors Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. Each parameter's value must be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff). */ public func postUpdateAccountProfileColors(profileBackgroundColor: String?, profileLinkColor: String?, profileSidebarBorderColor: String?, profileSidebarFillColor: String?, profileTextColor: String?, includeEntities: Bool?, skipStatus: Bool?, success: ((profile: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "account/update_profile_colors.json" var parameters = Dictionary<String, AnyObject>() if profileBackgroundColor != nil { parameters["profile_background_color"] = profileBackgroundColor! } if profileLinkColor != nil { parameters["profile_link_color"] = profileLinkColor! } if profileSidebarBorderColor != nil { parameters["profile_sidebar_link_color"] = profileSidebarBorderColor! } if profileSidebarFillColor != nil { parameters["profile_sidebar_fill_color"] = profileSidebarFillColor! } if profileTextColor != nil { parameters["profile_text_color"] = profileTextColor! } if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(profile: json.object) return }, failure: failure) } /* POST account/update_profile_image Updates the authenticating user's profile image. Note that this method expects raw multipart data, not a URL to an image. This method asynchronously processes the uploaded file before updating the user's profile image URL. You can either update your local cache the next time you request the user's information, or, at least 5 seconds after uploading the image, ask for the updated URL using GET users/show. */ public func postAccountUpdateProfileImage(imageData: NSData?, includeEntities: Bool?, skipStatus: Bool?, success: ((profile: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "account/update_profile_image.json" var parameters = Dictionary<String, AnyObject>() if imageData != nil { parameters["image"] = imageData!.base64EncodedStringWithOptions(nil) } if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(profile: json.object) return }, failure: failure) } /* GET blocks/list Returns a collection of user objects that the authenticating user is blocking. */ public func getBlockListWithIncludeEntities(includeEntities: Bool?, skipStatus: Bool?, cursor: Int?, success: ((users: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)?, failure: FailureHandler?) { let path = "blocks/list.json" var parameters = Dictionary<String, AnyObject>() if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } if cursor != nil { parameters["cursor"] = cursor! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in switch (json["users"].array, json["previous_cursor"].integer, json["next_cursor"].integer) { case (let users, let previousCursor, let nextCursor): success?(users: users, previousCursor: previousCursor, nextCursor: nextCursor) default: success?(users: nil, previousCursor: nil, nextCursor: nil) } }, failure: failure) } /* GET blocks/ids Returns an array of numeric user ids the authenticating user is blocking. */ public func getBlockIDsWithStingifyIDs(stringifyIDs: String?, cursor: Int?, success: ((ids: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)?, failure: FailureHandler) { let path = "blocks/ids.json" var parameters = Dictionary<String, AnyObject>() if stringifyIDs != nil { parameters["stringify_ids"] = stringifyIDs! } if cursor != nil { parameters["cursor"] = cursor! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in switch (json["ids"].array, json["previous_cursor"].integer, json["next_cursor"].integer) { case (let ids, let previousCursor, let nextCursor): success?(ids: ids, previousCursor: previousCursor, nextCursor: nextCursor) default: success?(ids: nil, previousCursor: nil, nextCursor: nil) } }, failure: failure) } /* POST blocks/create Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed. */ public func postBlocksCreateWithScreenName(screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "blocks/create.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func postBlocksCreateWithUserID(userID: String, includeEntities: Bool?, skipStatus: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "blocks/create.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } /* POST blocks/destroy Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored. */ public func postDestroyBlocksWithUserID(userID: String, includeEntities: Bool?, skipStatus: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "blocks/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func postDestroyBlocksWithScreenName(screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "blocks/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } /* GET users/lookup Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters. This method is especially useful when used in conjunction with collections of user IDs returned from GET friends/ids and GET followers/ids. GET users/show is used to retrieve a single user object. There are a few things to note when using this method. - You must be following a protected user to be able to see their most recent status update. If you don't follow a protected user their status will be removed. - The order of user IDs or screen names may not match the order of users in the returned array. - If a requested user is unknown, suspended, or deleted, then that user will not be returned in the results list. - If none of your lookup criteria can be satisfied by returning a user object, a HTTP 404 will be thrown. - You are strongly encouraged to use a POST for larger requests. */ public func getUsersLookupWithScreenNames(screenNames: [String], includeEntities: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler) { let path = "users/lookup.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = join(",", screenNames) if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } public func getUsersLookupWithUserIDs(userIDs: [String], includeEntities: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler) { let path = "users/lookup.json" var parameters = Dictionary<String, AnyObject>() let userIDStrings = userIDs.map { String($0) } parameters["user_id"] = join(",", userIDStrings) if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } /* GET users/show Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible. GET users/lookup is used to retrieve a bulk collection of user objects. You must be following a protected user to be able to see their most recent Tweet. If you don't follow a protected user, the users Tweet will be removed. A Tweet will not always be returned in the current_status field. */ public func getUsersShowWithScreenName(screenName: String, includeEntities: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "users/show.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func getUsersShowWithUserID(userID: String, includeEntities: Bool?, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler) { let path = "users/show.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } /* GET users/search Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported. Only the first 1,000 matching results are available. */ public func getUsersSearchWithQuery(q: String, page: Int?, count: Int?, includeEntities: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler) { let path = "users/search/json" var parameters = Dictionary<String, AnyObject>() parameters["q"] = q if page != nil { parameters["page"] = page! } if count != nil { parameters["count"] = count! } if includeEntities != nil { parameters["include_entities"] = includeEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } /* GET users/contributees Returns a collection of users that the specified user can "contribute" to. */ public func getUsersContributeesWithUserID(id: String, includeEntities: Bool?, skipStatus: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "users/contributees.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } public func getUsersContributeesWithScreenName(screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "users/contributees.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } /* GET users/contributors Returns a collection of users who can contribute to the specified account. */ public func getUsersContributorsWithUserID(id: String, includeEntities: Bool?, skipStatus: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "users/contributors.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } public func getUsersContributorsWithScreenName(screenName: String, includeEntities: Bool?, skipStatus: Bool?, success: ((users: [JSONValue]?) -> Void)?, failure: FailureHandler?) { let path = "users/contributors.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(users: json.array) return }, failure: failure) } /* POST account/remove_profile_banner Removes the uploaded profile banner for the authenticating user. Returns HTTP 200 upon success. */ public func postAccountRemoveProfileBannerWithSuccess(success: ((response: JSON) -> Void)?, failure: FailureHandler?) { let path = "account/remove_profile_banner.json" self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(response: json) return }, failure: failure) } /* POST account/update_profile_banner Uploads a profile banner on behalf of the authenticating user. For best results, upload an <5MB image that is exactly 1252px by 626px. Images will be resized for a number of display options. Users with an uploaded profile banner will have a profile_banner_url node in their Users objects. More information about sizing variations can be found in User Profile Images and Banners and GET users/profile_banner. Profile banner images are processed asynchronously. The profile_banner_url and its variant sizes will not necessary be available directly after upload. If providing any one of the height, width, offset_left, or offset_top parameters, you must provide all of the sizing parameters. HTTP Response Codes 200, 201, 202 Profile banner image succesfully uploaded 400 Either an image was not provided or the image data could not be processed 422 The image could not be resized or is too large. */ public func postAccountUpdateProfileBannerWithImageData(imageData: NSData?, width: Int?, height: Int?, offsetLeft: Int?, offsetTop: Int?, success: ((response: JSON) -> Void)?, failure: FailureHandler?) { let path = "account/update_profile_banner.json" var parameters = Dictionary<String, AnyObject>() if imageData != nil { parameters["banner"] = imageData!.base64EncodedStringWithOptions(nil) } if width != nil { parameters["width"] = width! } if height != nil { parameters["height"] = height! } if offsetLeft != nil { parameters["offset_left"] = offsetLeft! } if offsetTop != nil { parameters["offset_top"] = offsetTop! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(response: json) return }, failure: failure) } /* GET users/profile_banner Returns a map of the available size variations of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in User Profile Images and Banners. */ public func getUsersProfileBannerWithUserID(userID: String, success: ((response: JSON) -> Void)?, failure: FailureHandler?) { let path = "users/profile_banner.json" self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(response: json) return }, failure: failure) } /* POST mutes/users/create Mutes the user specified in the ID parameter for the authenticating user. Returns the muted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func postMutesUsersCreateForScreenName(screenName: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/create.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func postMutesUsersCreateForUserID(userID: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/create.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } /* POST mutes/users/destroy Un-mutes the user specified in the ID parameter for the authenticating user. Returns the unmuted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ public func postMutesUsersDestroyForScreenName(screenName: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func postMutesUsersDestroyForUserID(userID: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["user_id"] = userID self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } /* GET mutes/users/ids Returns an array of numeric user ids the authenticating user has muted. */ public func getMutesUsersIDsWithCursor(cursor: Int?, success: ((ids: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/ids.json" var parameters = Dictionary<String, AnyObject>() if cursor != nil { parameters["cursor"] = cursor! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in switch (json["ids"].array, json["previous_cursor"].integer, json["next_cursor"].integer) { case (let ids, let previousCursor, let nextCursor): success?(ids: ids, previousCursor: previousCursor, nextCursor: nextCursor) default: success?(ids: nil, previousCursor: nil, nextCursor: nil) } }, failure: failure) } /* GET mutes/users/list Returns an array of user objects the authenticating user has muted. */ public func getMutesUsersListWithCursor(cursor: Int?, includeEntities: Bool?, skipStatus: Bool?, success: ((users: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)?, failure: FailureHandler?) { let path = "mutes/users/list.json" var parameters = Dictionary<String, AnyObject>() if includeEntities != nil { parameters["include_entities"] = includeEntities! } if skipStatus != nil { parameters["skip_status"] = skipStatus! } if cursor != nil { parameters["cursor"] = cursor! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in switch (json["users"].array, json["previous_cursor"].integer, json["next_cursor"].integer) { case (let users, let previousCursor, let nextCursor): success?(users: users, previousCursor: previousCursor, nextCursor: nextCursor) default: success?(users: nil, previousCursor: nil, nextCursor: nil) } }, failure: failure) } }
2fa1f42fb7e0355dc9fda7f9a469de43
39.093679
411
0.64195
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/Subscriptions.swift
apache-2.0
1
// // Subscriptions.swift // Slide for Reddit // // Created by Carlos Crane on 1/6/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import AudioToolbox import Foundation import reddift class Subscriptions { private static var defaultSubs = ["frontpage", "slide_ios", "all", "announcements", "Art", "AskReddit", "askscience", "aww", "blog", "books", "creepy", "dataisbeautiful", "DIY", "Documentaries", "EarthPorn", "explainlikeimfive", "Fitness", "food", "funny", "Futurology", "gadgets", "gaming", "GetMotivated", "gifs", "history", "IAmA", "InternetIsBeautiful", "Jokes", "LifeProTips", "listentothis", "mildlyinteresting", "movies", "Music", "news", "nosleep", "nottheonion", "OldSchoolCool", "personalfinance", "philosophy", "photoshopbattles", "pics", "science", "Showerthoughts", "space", "sports", "television", "tifu", "todayilearned", "TwoXChromosomes", "UpliftingNews", "videos", "worldnews", "WritingPrompts", ] public static var subreddits: [String] { if accountSubs.isEmpty { return defaultSubs } return accountSubs } public static var subIcons: NSMutableDictionary = NSMutableDictionary() public static func icon(for sub: String) -> String? { if let icon = subIcons.object(forKey: sub.lowercased()) as? String, icon != "" { return icon } return nil } public static var subColors: NSMutableDictionary = NSMutableDictionary() public static func color(for sub: String) -> UIColor? { if let color = subColors.object(forKey: sub.lowercased()) as? String, color != "" { return UIColor(hex: color) } return nil } public static var pinned: [String] { if let accounts = UserDefaults.standard.array(forKey: "subsP" + AccountController.currentName) { return accounts as! [String] } UserDefaults.standard.set(["frontpage", "all", "popular"], forKey: "subsP" + AccountController.currentName) UserDefaults.standard.synchronize() return ["frontpage", "all", "popular"] } public static var offline: [String] { if let accounts = UserDefaults.standard.array(forKey: "subsO") { return accounts as! [String] } return [] } public static func isSubscriber(_ sub: String) -> Bool { for s in subreddits { if s.lowercased() == sub.lowercased() { return true } } return false } public static var historySubs: [String] = [] private static var accountSubs: [String] = [] public static func sync(name: String, completion: (() -> Void)?) { print("Getting \(name)'s subs") if let accounts = UserDefaults.standard.array(forKey: "subs" + name) { print("Count is \(accounts.count)") accountSubs = accounts as! [String] } else { accountSubs = defaultSubs } if let accounts = UserDefaults.standard.array(forKey: "historysubs" + name) { print("Count is \(accounts.count)") historySubs = accounts as! [String] } else { historySubs = [] } if (completion) != nil { completion!() } } public static func addHistorySub(name: String, sub: String) { for string in historySubs { if string.lowercased() == sub.lowercased() { return } } historySubs.append(sub) UserDefaults.standard.set(historySubs, forKey: "historysubs" + name) UserDefaults.standard.synchronize() } public static func clearSubHistory() { historySubs.removeAll() UserDefaults.standard.set(historySubs, forKey: "historysubs" + AccountController.currentName) UserDefaults.standard.synchronize() } public static func set(name: String, subs: [String], completion: @escaping () -> Void) { print("Setting subs") UserDefaults.standard.set(subs, forKey: "subs" + name) UserDefaults.standard.synchronize() Subscriptions.sync(name: name, completion: completion) } public static func setPinned(name: String, subs: [String], completion: @escaping () -> Void) { print("Setting pinned subs") UserDefaults.standard.set(subs, forKey: "subsP" + name) UserDefaults.standard.synchronize() Subscriptions.sync(name: name, completion: completion) } public static func setOffline( subs: [String], completion: @escaping () -> Void) { UserDefaults.standard.set(subs, forKey: "subsO") UserDefaults.standard.synchronize() } public static func subscribe(_ name: String, _ subscribe: Bool, session: Session?) { var sub = Subscriptions.subreddits SubredditReorderViewController.changed = true sub.append(name) set(name: AccountController.currentName, subs: sub) { () in } if #available(iOS 10.0, *) { HapticUtility.hapticActionStrong() } else if SettingValues.hapticFeedback { AudioServicesPlaySystemSound(1519) } if subscribe && AccountController.isLoggedIn && session != nil { do { try session!.setSubscribeSubreddit(Subreddit.init(subreddit: name), subscribe: true, completion: { (_) in }) } catch { } } } public static func unsubscribe(_ name: String, session: Session) { var subs = Subscriptions.subreddits subs = subs.filter { $0 != name } setPinned(name: AccountController.currentName, subs: pinned.filter { $0 != name }, completion: {}) SubredditReorderViewController.changed = true set(name: AccountController.currentName, subs: subs) { () in } if #available(iOS 10.0, *) { HapticUtility.hapticActionStrong() } else if SettingValues.hapticFeedback { AudioServicesPlaySystemSound(1519) } if AccountController.isLoggedIn { do { try session.setSubscribeSubreddit(Subreddit.init(subreddit: name), subscribe: false, completion: { (result) in switch result { case .failure: print(result.error!) default: break } }) } catch { } } } public static func getSubscriptionsUntilCompletion(session: Session, p: Paginator, tR: [Subreddit], mR: [Multireddit], multis: Bool, completion: @escaping (_ result: [Subreddit], _ multis: [Multireddit]) -> Void) { var toReturn = tR var toReturnMultis = mR var paginator = p do { if !multis { try session.getUserRelatedSubreddit(.subscriber, paginator: paginator, completion: { (result) -> Void in switch result { case .failure: print(result.error!) completion(toReturn, toReturnMultis) case .success(let listing): toReturn += listing.children.compactMap({ $0 as? Subreddit }) paginator = listing.paginator print("Size is \(toReturn.count) and hasmore is \(paginator.hasMore())") if paginator.hasMore() { getSubscriptionsUntilCompletion(session: session, p: paginator, tR: toReturn, mR: toReturnMultis, multis: false, completion: completion) } else { getSubscriptionsUntilCompletion(session: session, p: paginator, tR: toReturn, mR: toReturnMultis, multis: true, completion: completion) } } }) } else { try session.getMineMultireddit({ (result) in switch result { case .failure: print(result.error!) for sub in toReturn { subIcons[sub.displayName.lowercased()] = sub.iconImg == "" ? sub.communityIcon : sub.iconImg subColors[sub.displayName.lowercased()] = sub.keyColor } completion(toReturn, toReturnMultis) case .success(let multireddits): toReturnMultis.append(contentsOf: multireddits) for sub in toReturn { subIcons[sub.displayName.lowercased()] = sub.iconImg == "" ? sub.communityIcon : sub.iconImg subColors[sub.displayName.lowercased()] = sub.keyColor } completion(toReturn, toReturnMultis) } }) } } catch { completion(toReturn, toReturnMultis) } } public static func getSubscriptionsFully(session: Session, completion: @escaping (_ result: [Subreddit], _ multis: [Multireddit]) -> Void) { let toReturn: [Subreddit] = [] let toReturnMultis: [Multireddit] = [] let paginator = Paginator() getSubscriptionsUntilCompletion(session: session, p: paginator, tR: toReturn, mR: toReturnMultis, multis: false, completion: completion) } public static func isCollection(_ baseSub: String) -> Bool { return baseSub == "all" || baseSub == "frontpage" || baseSub.contains("/m/") || baseSub.contains("+") || baseSub == "popular" || baseSub == "random" || baseSub == "myrandom" || baseSub == "randnsfw" } }
fa899cceb314024a678d9630dd10cab8
41.253112
218
0.548463
false
false
false
false
volendavidov/NagBar
refs/heads/master
NagBar/StatusItemView.swift
apache-2.0
1
// // StatusItemView.swift // NagBar // // Created by Volen Davidov on 05.03.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation import Cocoa class StatusItemView: NSStatusBarButton { let StatusItemViewPaddingWidth = CGFloat(6) let StatusItemViewPaddingHeight = CGFloat(3) // var title: String? var statusItem: NSStatusItem? override func draw(_ dirtyRect: NSRect) { let origin = NSMakePoint(StatusItemViewPaddingWidth, StatusItemViewPaddingHeight); title.draw(at: origin, withAttributes: titleAttributes()) } private func titleAttributes() -> Dictionary<NSAttributedString.Key, AnyObject> { let font = NSFont.menuBarFont(ofSize: 0) var color = NSColor.black // check if dark mode is enabled let dict = Foundation.UserDefaults.standard.persistentDomain(forName: Foundation.UserDefaults.globalDomain) let style = dict!["AppleInterfaceStyle"] if let style = style as? String { if ComparisonResult.orderedSame == style.caseInsensitiveCompare("dark") { color = NSColor.white } } // fix for Big Sur if self.statusItem?.button?.effectiveAppearance.name.rawValue == "NSAppearanceNameVibrantDark" { color = NSColor.white } return [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: color] } override func rightMouseDown(with theEvent: NSEvent) { let menu = NSMenu(title: "") menu.addItem(withTitle: "Refresh", action: #selector(StatusItemView.refresh), keyEquivalent: "") menu.addItem(NSMenuItem.separator()) if !Settings().boolForKey("showDockIcon") as Bool { menu.addItem(withTitle: "Preferences", action: #selector(AppDelegate.openPreferences(_:)), keyEquivalent: "") } menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "") NSMenu.popUpContextMenu(menu, with: theEvent, for: self) } override func mouseDown(with theEvent: NSEvent) { // show the panel StatusBar.get().onClick() } @objc func refresh() { LoadMonitoringData().refreshStatusData() } func setStatusItemTitle(_ newTitle: String) { if self.title == newTitle { return } self.title = newTitle let titleBounds = self.titleBoundingRect() let newWidth = titleBounds.size.width + (2 * StatusItemViewPaddingWidth) self.statusItem?.length = newWidth self.needsDisplay = true } func titleBoundingRect() -> NSRect { return title.boundingRect(with: NSMakeSize(0, 0), options: .usesFontLeading, attributes: self.titleAttributes()) } }
ab69a1a3f6edd14fe3b972d648956e58
31.955056
121
0.627003
false
false
false
false
tompiking/shop_ke
refs/heads/master
shop_ke/ProductViewController.swift
apache-2.0
1
// // ProductViewController.swift // shop_ke // // Created by mac on 16/2/29. // Copyright © 2016年 peraytech. All rights reserved. // import UIKit class ProductViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate { @IBOutlet weak var goodsScrollView: UIScrollView! @IBOutlet weak var goodsCollectionView: UICollectionView! var goods = [Goods]() //商品数据 var refreshControl = UIRefreshControl() //下拉刷新 var arr = [] //标签数据 // let arr = Tag.getTags() var detail = Detail() //商品详情数据 var activityIndicatorView = UIActivityIndicatorView() //活动指示器 override func viewDidLoad() { super.viewDidLoad() //活动指示器 activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) activityIndicatorView.frame = CGRectMake(self.view.frame.size.width/2-50, self.view.frame.size.height/2-50, 100, 100) activityIndicatorView.hidden = false activityIndicatorView.hidesWhenStopped = true activityIndicatorView.color = UIColor.blackColor() self.view.addSubview(activityIndicatorView) arr = NSUserDefaults.standardUserDefaults().objectForKey("saveTag") as! NSArray loadTags() loadTagView() loadProduct(6) //创建一个cell放入内存以便重用 goodsCollectionView.registerNib(UINib(nibName: "LogMenuCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") //下拉刷新 refreshControl.addTarget(self, action: #selector(ProductViewController.refreshData), forControlEvents: UIControlEvents.ValueChanged) refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新数据") refreshControl.tintColor = UIColor.redColor() goodsCollectionView.addSubview(refreshControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:获取标签 func loadTags(){ //从接口获取标签保存至本地 let params = [String : AnyObject]() HttpManager.httpGetRequest(.GET, api_url: API_URL+"/tag_list", params: params, onSuccess: { (successData) -> Void in // Tag.saveTags(successData as! NSArray) NSUserDefaults.standardUserDefaults().setObject(successData, forKey: "saveTag") }) { (failData) -> Void in print("保存标签失败") } } //MARK:加载标签 func loadTagView() { goodsScrollView.contentSize = CGSizeMake(CGFloat(arr.count)*65, 30) for index in 0..<arr.count { let btn = UIButton(type: .System) btn.frame = CGRectMake(CGFloat(Float(index)) * 65, 0, 65, 30) btn.setTitle((arr[index]["name"]) as? String, forState: UIControlState.Normal) // btn.setTitleColor(UIColor.redColor(),forState: .Highlighted) btn.tintColor = UIColor.blackColor() btn.tag = index btn.addTarget(self, action: #selector(ProductViewController.tagClick(_:)), forControlEvents: .TouchUpInside) //使第一个颜色变红 if index == 0 { btn.tintColor = UIColor.redColor() } goodsScrollView.addSubview(btn) } } //MARK:点击标签 func tagClick(btn : UIButton) { print(btn.tag) //点击标签 根据标签id加载商品 loadProduct(((arr[btn.tag]["id"]) as? Int)!) print(((arr[btn.tag]["id"]) as? Int)!) //点击标签变色 for (index,subviews) in goodsScrollView.subviews.enumerate() { if index == btn.tag { subviews.tintColor = UIColor.redColor() }else { subviews.tintColor = UIColor.blackColor() } } } //MARK:加载商品 func loadProduct(tagid : Int) { activityIndicatorView.startAnimating() var pramas = [String : AnyObject]() pramas["sort_type"] = "created_at-desc" pramas["tag_id"] = tagid pramas["page"] = 1 HttpManager.httpGetRequest(.GET, api_url: API_URL+"/product_list", params: pramas, onSuccess: { (successData) -> Void in print("=======\(successData)") self.goods = Goods.initWithGoods(successData) self.goodsCollectionView.reloadData() self.activityIndicatorView.stopAnimating() }) { (failData) -> Void in print("***********") } } //MARK:上拉刷新 // func onPullToFresh(){ // // } //MARK:下拉刷新 func refreshData() { self.goodsCollectionView.reloadData() self.refreshControl.endRefreshing() } //MARK: 设置cell的数量 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return goods.count; } //MARK:设置cell的内容 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! LogMenuCollectionViewCell // let image = UIImage(named: "zpzk") cell.goodsPicture.setWebImage(goods[indexPath.row].image!, placeHolder: UIImage(named: "zpzk")) cell.goodsDescribe.text = goods[indexPath.row].content cell.goodsPrice.text = "¥" + String(goods[indexPath.row].price!) cell.goodsDiscount.text = String(goods[indexPath.row].discount!)+"折" return cell } //MARK:点击cell后显示内容 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { //根据商品id显示商品详情 var params = [String: AnyObject]() params["id"] = goods[indexPath.row].id HttpManager.httpGetRequest(.GET, api_url: API_URL+"/product_detail", params: params, onSuccess: { (successData) -> Void in //获取点击的商品的数据 self.detail = Detail.setDetail(successData) print(successData) let selectDetail = ProductDetailViewController() NSBundle.mainBundle().loadNibNamed("ProductDetailViewController", owner: selectDetail, options: nil) // let image = UIImage(named: "zpzk") selectDetail.detailImage.setWebImage(self.detail.detailImage!, placeHolder: UIImage(named: "zpzk")) selectDetail.detailIntroduction.text = self.detail.detailIntroduction! selectDetail.discountPrice.text = "¥"+String(self.detail.discountPrice!) selectDetail.originalPrice.text = "原价:"+String(self.detail.originalPrice!) selectDetail.discount.text = self.detail.discount!+"折" selectDetail.detailUrl = self.detail.detailUrl! self.presentViewController(selectDetail, animated: true, completion: nil) }) { (failData) -> Void in print("获取失败!") } } //MARK: 跳转到分类 @IBAction func logMenu(sender: UIButton) { let nib = LogMenuViewController() self.presentViewController(nib, animated: true, completion: nil) } }
e43ef31c4a9bce6bc698ed570965f166
37.817204
140
0.623546
false
false
false
false
Laptopmini/SwiftyArtik
refs/heads/master
Source/MessagesAPI.swift
mit
1
// // MessagesAPI.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 6/12/17. // Copyright © 2017 Paul-Valentin Mini. All rights reserved. // import Foundation import PromiseKit import Alamofire open class MessagesAPI { public enum MessageType: String { case message = "message" case action = "action" } public enum MessageStatisticsInterval: String { case minute = "minute" case hour = "hour" case day = "day" case month = "month" case year = "year" } // MARK: - Messages /// Send a Message to ARTIK Cloud. /// /// - Parameters: /// - data: The message payload. /// - did: The Device's id, used as the sender. /// - timestamp: (Optional) Message timestamp. Must be a valid time: past time, present or future up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>`, returning the resulting message's id. open class func sendMessage(data: [String:Any], fromDid did: String, timestamp: Int64? = nil) -> Promise<String> { let parameters: [String:Any] = [ "data": data, "type": MessageType.message.rawValue, "sdid": did ] return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the messages sent by a Device using pagination. /// /// - Parameters: /// - did: The Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getMessages(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var presenceValue: String? if let fieldPresence = fieldPresence { presenceValue = "(" + fieldPresence.map { return "+_exists_:\($0)" }.joined(separator: " ") + ")" } let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "filter": presenceValue ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.fieldPresence = fieldPresence promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a specific Message /// /// - Parameters: /// - mid: The Message's id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getMessage(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the presence of Messages for a given time period. /// /// - Parameters: /// - sdid: The source Device's id. /// - fieldPresence: (Optional) Return only messages which contain the provided field name /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: The grouping interval /// - Returns: A `Promise<MessagesPresence>` open class func getPresence(sdid: String?, fieldPresence: String? = nil, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval) -> Promise<MessagesPresence> { let promise = Promise<MessagesPresence>.pending() let path = SwiftyArtikSettings.basePath + "/messages/presence" let parameters = APIHelpers.removeNilParameters([ "sdid": sdid, "fieldPresence": fieldPresence, "interval": interval.rawValue, "startDate": startDate, "endDate": endDate ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let presence = MessagesPresence(JSON: response) { promise.fulfill(presence) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest messages sent by a Device. /// /// - Parameters: /// - did: The Device's id /// - count: The count of results, max 100 /// - fieldPresence: (Optional) Return only messages which contain the provided field names /// - Returns: A `Promise<MessagePage>` open class func getLastMessages(did: String, count: Int = 100, fieldPresence: [String]? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getMessages(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, fieldPresence: fieldPresence).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the lastest message sent by a Device. /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message>` open class func getLastMessage(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastMessages(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Actions /// Send an Action to a Device through ARTIK Cloud. /// /// - Parameters: /// - named: The name of the action /// - parameters: (Optional) The parameters of the action. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendAction(named: String, parameters: [String:Any]? = nil, toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": [ [ "name": named, "parameters": parameters ?? [:] ] ] ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Send multiple Actions to a Device through ARTIK Cloud. /// /// - Parameters: /// - actions: A dict where the `key` is the name of the action and the `value` is its parameters. /// - target: The Device's id receiving the action. /// - sender: (Optional) The id of the Device sending the action. /// - timestamp: (Optional) Action timestamp, a past/present/future time up to the current server timestamp grace period. Current time if omitted. /// - Returns: A `Promise<String>` returning the resulting action's id. open class func sendActions(_ actions: [String:[String:Any]?], toDid target: String, fromDid sender: String? = nil, timestamp: Int64? = nil) -> Promise<String> { var data = [[String:Any]]() for (name, parameters) in actions { data.append([ "name": name, "parameters": parameters ?? [:] ]) } var parameters: [String:Any] = [ "ddid": target, "type": MessageType.action.rawValue, "data": [ "actions": data ] ] if let sender = sender { parameters["sdid"] = sender } return postMessage(baseParameters: parameters, timestamp: timestamp) } /// Get the actions sent to a Device. /// /// - Parameters: /// - did: The Device's id /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - count: The count of results, max `100` (default). /// - offset: (Optional) The offset cursor for pagination. /// - order: (Optional) The order of the results, `.ascending` if ommited. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getActions(did: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, count: Int = 100, offset: String? = nil, order: PaginationOrder? = nil, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() let path = SwiftyArtikSettings.basePath + "/actions" let parameters = APIHelpers.removeNilParameters([ "sdid": did, "startDate": startDate, "endDate": endDate, "count": count, "offset": offset, "order": order?.rawValue, "name": name ]) APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let page = MessagePage(JSON: response) { page.count = count page.name = name promise.fulfill(page) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get a particular action sent to a Device. /// /// - Parameters: /// - mid: The Action's (message) id. /// - uid: (Optional) The owner's user ID, required when using an `ApplicationToken`. /// - Returns: A `Promise<Message>` open class func getAction(mid: String, uid: String? = nil) -> Promise<Message> { let promise = Promise<Message>.pending() let path = SwiftyArtikSettings.basePath + "/actions" var parameters = [ "mid": mid ] if let uid = uid { parameters["uid"] = uid } APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let data = (response["data"] as? [[String:Any]])?.first, let message = Message(JSON: data) { promise.fulfill(message) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest actions sent to a Device. /// /// - Parameters: /// - did: The Device's id. /// - count: The count of results, max 100. /// - name: (Optional) Return only actions with the provided name. /// - Returns: A `Promise<MessagePage>` open class func getLastActions(did: String, count: Int = 100, name: String? = nil) -> Promise<MessagePage> { let promise = Promise<MessagePage>.pending() getActions(did: did, startDate: 1, endDate: currentArtikEpochtime(), count: count, order: .descending, name: name).then { page -> Void in promise.fulfill(page) }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Get the latest action sent to a Device /// /// - Parameter did: The Device's id. /// - Returns: A `Promise<Message?>` open class func getLastAction(did: String) -> Promise<Message?> { let promise = Promise<Message?>.pending() getLastActions(did: did, count: 1).then { page -> Void in if let message = page.data.first { promise.fulfill(message) } else { promise.fulfill(nil) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Analytics /// Get the sum, minimum, maximum, mean and count of message fields that are numerical. Values for `startDate` and `endDate` are rounded to start of minute, and the date range between `startDate` and `endDate` is restricted to 31 days max. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - field: Message field being queried for analytics. /// - Returns: A `Promise<MessageAggregates>` open class func getAggregates(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, field: String) -> Promise<MessageAggregates> { let promise = Promise<MessageAggregates>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/aggregates" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let aggregate = MessageAggregates(JSON: response) { promise.fulfill(aggregate) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } /// Returns message aggregates over equal intervals, which can be used to draw a histogram. /// /// - Parameters: /// - sdid: The source Device's id. /// - startDate: Time of the earliest possible item, in milliseconds since epoch. /// - endDate: Time of the latest possible item, in milliseconds since epoch. /// - interval: Interval on histogram X-axis. /// - field: Message field being queried for histogram aggregation (histogram Y-axis). /// - Returns: A `Promise<MessageHistogram>` open class func getHistogram(sdid: String, startDate: ArtikTimestamp, endDate: ArtikTimestamp, interval: MessageStatisticsInterval, field: String) -> Promise<MessageHistogram> { let promise = Promise<MessageHistogram>.pending() let path = SwiftyArtikSettings.basePath + "/messages/analytics/histogram" let parameters: [String:Any] = [ "sdid": sdid, "startDate": startDate, "endDate": endDate, "interval": interval.rawValue, "field": field ] APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in if let histogram = MessageHistogram(JSON: response) { promise.fulfill(histogram) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Snapshots /// Get the last received value for all Manifest fields (aka device "state") of devices. /// /// - Parameters: /// - dids: An array containing the Devices' ids. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:[String:Any]]>` where the `key` is the Device id and the `value` is its snapshot. open class func getSnapshots(dids: [String], includeTimestamp: Bool? = nil) -> Promise<[String:[String:Any]]> { let promise = Promise<[String:[String:Any]]>.pending() let path = SwiftyArtikSettings.basePath + "/messages/snapshots" if dids.count > 0 { var didsString = "" for did in dids { didsString += "\(did)," } APIHelpers.makeRequest(url: path, method: .get, parameters: ["sdids": didsString], encoding: URLEncoding.queryString).then { response -> Void in if let data = response["data"] as? [[String:Any]] { var result = [String:[String:Any]]() for item in data { if let sdid = item["sdid"] as? String, let data = item["data"] as? [String:Any] { result[sdid] = data } else { promise.reject(ArtikError.json(reason: .invalidItem)) return } } promise.fulfill(result) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } } else { promise.fulfill([:]) } return promise.promise } /// Get the last received value for all Manifest fields (aka device "state") of a device. /// /// - Parameters: /// - did: The Device's id. /// - includeTimestamp: (Optional) Include the timestamp of the last modification for each field. /// - Returns: A `Promise<[String:Any]>` returning the snapshot open class func getSnapshot(did: String, includeTimestamp: Bool? = nil) -> Promise<[String:Any]> { let promise = Promise<[String:Any]>.pending() getSnapshots(dids: [did], includeTimestamp: includeTimestamp).then { result -> Void in if let snapshot = result[did] { promise.fulfill(snapshot) } else { promise.fulfill([:]) } }.catch { error -> Void in promise.reject(error) } return promise.promise } // MARK: - Private Methods fileprivate class func currentArtikEpochtime() -> Int64 { return Int64(Date().timeIntervalSince1970 * 1000.0) } fileprivate class func postMessage(baseParameters: [String:Any], timestamp: Int64?) -> Promise<String> { let promise = Promise<String>.pending() let path = SwiftyArtikSettings.basePath + "/messages" var parameters = baseParameters if let timestamp = timestamp { parameters["ts"] = timestamp } APIHelpers.makeRequest(url: path, method: .post, parameters: parameters, encoding: JSONEncoding.default).then { response -> Void in if let mid = (response["data"] as? [String:Any])?["mid"] as? String { promise.fulfill(mid) } else { promise.reject(ArtikError.json(reason: .unexpectedFormat)) } }.catch { error -> Void in promise.reject(error) } return promise.promise } }
bcdfc854e45d88d0f796cd8ac61ae163
41.442
243
0.578154
false
false
false
false
Tsiems/mobile-sensing-apps
refs/heads/master
06-Daily/code/Daily/IBAnimatable/DropDownAnimator.swift
gpl-3.0
5
// // Created by Tom Baranes on 13/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class DropDownAnimator: NSObject, AnimatedPresenting { // MARK: - AnimatedPresenting public var transitionDuration: Duration = defaultTransitionDuration fileprivate var completion: AnimatableCompletion? // MARK: - Life cycle public init(transitionDuration: Duration) { self.transitionDuration = transitionDuration super.init() } } // MARK: - Animator extension DropDownAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (fromView, toView, tempContainerView) = retrieveViews(transitionContext: transitionContext) let isPresenting = self.isPresenting(transitionContext: transitionContext) guard let containerView = tempContainerView, let animatingView = isPresenting ? toView : fromView else { transitionContext.completeTransition(true) return } if isPresenting { containerView.addSubview(animatingView) } animateDropDown(animatingView: animatingView, isPresenting: isPresenting) { if !isPresenting { fromView?.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Animation private extension DropDownAnimator { func animateDropDown(animatingView: UIView, isPresenting: Bool, completion: @escaping AnimatableCompletion) { if isPresenting { animatePresengingDropDown(animatingView: animatingView, completion: completion) } else { animateDismissingDropDown(animatingView: animatingView, completion: completion) } } func animatePresengingDropDown(animatingView: UIView, completion: @escaping AnimatableCompletion) { let y = animatingView.center.y let animation = CAKeyframeAnimation(keyPath: "position.y") animation.values = [y - UIScreen.main.bounds.height, y + 20, y - 10, y] animation.keyTimes = [0, 0.5, 0.75, 1] animation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] animation.duration = transitionDuration animation.delegate = self self.completion = completion animatingView.layer.add(animation, forKey: "dropdown") } func animateDismissingDropDown(animatingView: UIView, completion: @escaping AnimatableCompletion) { var point = animatingView.center let angle = CGFloat(arc4random_uniform(100)) - 50 point.y += UIScreen.main.bounds.height UIView.animate(withDuration: transitionDuration, animations: { animatingView.center = point animatingView.transform = CGAffineTransform(rotationAngle: angle / 100) }, completion: { _ in completion() }) } } // MARK: - CAAnimationDelegate extension DropDownAnimator: CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let completion = completion { completion() self.completion = nil } } }
5d006d6fb17074e0fb28191231113fc5
33.040404
211
0.751929
false
false
false
false
BennyKJohnson/OpenCloudKit
refs/heads/master
Sources/CKFetchRecordsOperation.swift
mit
1
// // CKFetchRecordsOperation.swift // OpenCloudKit // // Created by Benjamin Johnson on 7/07/2016. // // import Foundation public class CKFetchRecordsOperation: CKDatabaseOperation { var isFetchCurrentUserOperation = false var recordErrors: [String: Any] = [:] // todo use this for partial errors var shouldFetchAssetContent: Bool = false var recordIDsToRecords: [CKRecordID: CKRecord] = [:] /* Called repeatedly during transfer. */ public var perRecordProgressBlock: ((CKRecordID, Double) -> Void)? /* Called on success or failure for each record. */ public var perRecordCompletionBlock: ((CKRecord?, CKRecordID?, Error?) -> Void)? /* This block is called when the operation completes. The [NSOperation completionBlock] will also be called if both are set. If the error is CKErrorPartialFailure, the error's userInfo dictionary contains a dictionary of recordIDs to errors keyed off of CKPartialErrorsByItemIDKey. */ public var fetchRecordsCompletionBlock: (([CKRecordID : CKRecord]?, Error?) -> Void)? public class func fetchCurrentUserRecord() -> Self { let operation = self.init() operation.isFetchCurrentUserOperation = true return operation } public override required init() { super.init() } public var recordIDs: [CKRecordID]? public var desiredKeys: [String]? public convenience init(recordIDs: [CKRecordID]) { self.init() self.recordIDs = recordIDs } override func finishOnCallbackQueue(error: Error?) { if(error == nil){ // todo build partial error using recordErrors } self.fetchRecordsCompletionBlock?(self.recordIDsToRecords, error) super.finishOnCallbackQueue(error: error) } func completed(record: CKRecord?, recordID: CKRecordID?, error: Error?){ callbackQueue.async { self.perRecordCompletionBlock?(record, recordID, error) } } func progressed(recordID: CKRecordID, progress: Double){ callbackQueue.async { self.perRecordProgressBlock?(recordID, progress) } } override func performCKOperation() { // Generate the CKOperation Web Service URL let url = "\(operationURL)/records/\(CKRecordOperation.lookup)" var request: [String: Any] = [:] let lookupRecords = recordIDs?.map { (recordID) -> [String: Any] in return ["recordName": recordID.recordName.bridge()] } request["records"] = lookupRecords?.bridge() urlSessionTask = CKWebRequest(container: operationContainer).request(withURL: url, parameters: request) { [weak self] (dictionary, error) in guard let strongSelf = self, !strongSelf.isCancelled else { return } defer { strongSelf.finish(error: error) } guard let dictionary = dictionary, let recordsDictionary = dictionary["records"] as? [[String: Any]], error == nil else { return } // Process Records // Parse JSON into CKRecords for (index,recordDictionary) in recordsDictionary.enumerated() { // Call Progress Block, this is hacky support and not the callbacks intented purpose let progress = Double(index + 1) / Double((strongSelf.recordIDs!.count)) let recordID = strongSelf.recordIDs![index] strongSelf.progressed(recordID: recordID, progress: progress) if let record = CKRecord(recordDictionary: recordDictionary) { strongSelf.recordIDsToRecords[record.recordID] = record // Call per record callback, not to be confused with finished strongSelf.completed(record: record, recordID: record.recordID, error: nil) } else { // Create Error let error = NSError(domain: CKErrorDomain, code: CKErrorCode.PartialFailure.rawValue, userInfo: [NSLocalizedDescriptionKey: "Failed to parse record from server".bridge()]) // Call per record callback, not to be confused with finished strongSelf.completed(record: nil, recordID: nil, error: error) // todo add to recordErrors array } } } } }
4e1e14324eb42f795134699e21393917
34.182482
191
0.578008
false
false
false
false
austinzheng/swift
refs/heads/master
test/SILGen/convenience_init_peer_delegation.swift
apache-2.0
2
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class X { init() { } // Convenience inits must dynamically dispatch designated inits... // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC // CHECK: class_method {{%.*}}, #X.init!allocator.1 convenience init(convenience: ()) { self.init() } // ...but can statically invoke peer convenience inits // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC // CHECK: function_ref @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC convenience init(doubleConvenience: ()) { self.init(convenience: ()) } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC required init(required: ()) { } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC required convenience init(requiredConvenience: ()) { self.init(required: ()) } // Convenience inits must dynamically dispatch required peer convenience inits // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC // CHECK: class_method {{%.*}}, #X.init!allocator.1 required convenience init(requiredDoubleConvenience: ()) { self.init(requiredDoubleConvenience: ()) } } class Y: X { // This is really a designated initializer. Ensure that we don't try to // treat it as an override of the base class convenience initializer (and // override a nonexistent vtable entry) just because it has the same name. init(convenience: ()) { super.init() } // Conversely, a designated init *can* be overridden as a convenience // initializer. override convenience init() { self.init(convenience: ()) } required init(required: ()) { super.init() } required init(requiredConvenience: ()) { super.init() } required init(requiredDoubleConvenience: ()) { super.init() } } // CHECK-LABEL: sil hidden [ossa] @$s32convenience_init_peer_delegation11invocations2xtyAA1XCm_tF func invocations(xt: X.Type) { // CHECK: function_ref @$s32convenience_init_peer_delegation1XCACycfC _ = X() // CHECK: function_ref @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC _ = X(convenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC _ = X(doubleConvenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC _ = X(required: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC _ = X(requiredConvenience: ()) // CHECK: function_ref @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC _ = X(requiredDoubleConvenience: ()) // CHECK: class_method {{%.*}}, #X.init!allocator.1 _ = xt.init(required: ()) // CHECK: class_method {{%.*}}, #X.init!allocator.1 _ = xt.init(requiredConvenience: ()) // CHECK: class_method {{%.*}}, #X.init!allocator.1 _ = xt.init(requiredDoubleConvenience: ()) } // CHECK-LABEL: sil_vtable X // -- designated init() // CHECK: @$s32convenience_init_peer_delegation1XCACycfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XCACycfc // -- no unrequired convenience inits // CHECK-NOT: @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC0A0ACyt_tcfc // CHECK-NOT: @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC17doubleConvenienceACyt_tcfc // -- designated init(required:) // CHECK: @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC8requiredACyt_tcfc // -- convenience init(requiredConvenience:) // CHECK: @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC19requiredConvenienceACyt_tcfc // -- convenience init(requiredDoubleConvenience:) // CHECK: @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1XC25requiredDoubleConvenienceACyt_tcfc // CHECK-LABEL: sil_vtable Y // -- designated init() overridden by convenience init // CHECK: @$s32convenience_init_peer_delegation1YCACycfC // CHECK-NOT: @$s32convenience_init_peer_delegation1YCACycfc // -- Y.init(convenience:) is a designated init // CHECK: @$s32convenience_init_peer_delegation1YC0A0ACyt_tcfC // CHECK-NOT: @$s32convenience_init_peer_delegation1YC0A0ACyt_tcfc
db318531caf531155a8e0fc5aa110191
43.803738
112
0.708594
false
false
false
false
fabiomassimo/eidolon
refs/heads/master
Kiosk/Bid Fulfillment/RegistrationPostalZipViewController.swift
mit
1
import ReactiveCocoa import Swift_RAC_Macros public class RegistrationPostalZipViewController: UIViewController, RegistrationSubController { @IBOutlet var zipCodeTextField: TextField! @IBOutlet var confirmButton: ActionButton! let finishedSignal = RACSubject() public lazy var viewModel: GenericFormValidationViewModel = { let zipCodeIsValidSignal = self.zipCodeTextField.rac_textSignal().map(isZeroLengthString).not() return GenericFormValidationViewModel(isValidSignal: zipCodeIsValidSignal, manualInvocationSignal: self.zipCodeTextField.returnKeySignal(), finishedSubject: self.finishedSignal) }() public lazy var bidDetails: BidDetails! = { self.navigationController!.fulfillmentNav().bidDetails }() public override func viewDidLoad() { super.viewDidLoad() zipCodeTextField.text = bidDetails.newUser.zipCode RAC(bidDetails, "newUser.zipCode") <~ zipCodeTextField.rac_textSignal().takeUntil(viewWillDisappearSignal()) confirmButton.rac_command = viewModel.command zipCodeTextField.becomeFirstResponder() } public class func instantiateFromStoryboard(storyboard: UIStoryboard) -> RegistrationPostalZipViewController { return storyboard.viewControllerWithID(.RegisterPostalorZip) as! RegistrationPostalZipViewController } }
05595f5df75b9a293cac7926864662e0
45.068966
185
0.776946
false
false
false
false
4np/UitzendingGemist
refs/heads/master
NPOKit/NPOKit/NPOManager+Token.swift
apache-2.0
1
// // NPOManager+Token.swift // NPOKit // // Created by Jeroen Wesbeek on 14/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import Alamofire import CocoaLumberjack extension NPOManager { internal func getToken(withCompletion completed: @escaping (_ token: String?, _ error: NPOError?) -> Void = { token, error in }) { // use cached token? if let token = self.token, !token.hasExpired { //DDLogDebug("Use cached token: \(token), age: \(token.age)") completed(token.token, nil) return } // refresh token let url = "https://ida.omroep.nl/app.php/auth" _ = fetchModel(ofType: NPOToken.self, fromURL: url) { [weak self] token, error in //DDLogDebug("Refreshed token: \(token)") self?.token = token completed(token?.token, error) } } }
8a48e934fda52cb0ad351632028d193c
29.633333
134
0.594124
false
false
false
false
almapp/uc-access-ios
refs/heads/master
uc-access/src/services/Labmat.swift
gpl-3.0
1
// // Labmat.swift // uc-access // // Created by Patricio Lopez on 08-01-16. // Copyright © 2016 Almapp. All rights reserved. // import Foundation import Alamofire import PromiseKit public class Labmat: Service { public static let ID = "LABMAT" private static let URL = "http://www.labmat.puc.cl/index.php" private let user: String private let password: String init(user: String, password: String) { self.user = user self.password = password super.init(name: "Labmat", urls: URLs( basic: "http://www.labmat.puc.cl/", logged: "http://www.labmat.puc.cl/?app=labmat", failed: "http://www.labmat.puc.cl/" )) self.domain = "www.labmat.puc.cl" } override func login() -> Promise<[NSHTTPCookie]> { let params: [String: String] = [ "accion": "ingreso", "usuario": self.user + "@uc.cl", "clave": self.password, ] return Request.GET(self.urls.basic) .then { (response, _) -> Promise<(NSHTTPURLResponse, NSData)> in self.addCookies(response) return Request.POST(Labmat.URL, parameters: params, headers: NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies)) } .then { (_, _) -> [NSHTTPCookie] in return self.cookies } } override func validate(request: NSURLRequest) -> Bool { if let headers = request.allHTTPHeaderFields { return Service.hasCookie("LABMAT_USUARIO", header: headers) } else { return false } } }
00bbb0fc07eda651290733ef35e43aa2
28.660714
135
0.566526
false
false
false
false
cxchope/NyaaCatAPP_iOS
refs/heads/master
nyaacatapp/DMChatTVC.swift
gpl-3.0
1
// // DMChatTVC.swift // nyaacatapp // // Created by 神楽坂雅詩 on 16/2/21. // Copyright © 2016年 KagurazakaYashi. All rights reserved. // import UIKit import WebKit class DMChatTVC: UITableViewController,WKNavigationDelegate { //,UIScrollViewDelegate let 允许转义颜色代码:Bool = false //true: 将&视为颜色代码 var 实时聊天数据:[[String]]? = nil var 默认头像:UIImage = UIImage(contentsOfFile: Bundle.main.path(forResource: "seting-icon", ofType: "png")!)! var 第三方软件发送头像:UIImage = UIImage(contentsOfFile: Bundle.main.path(forResource: "t_logo", ofType: "png")!)! var 动态地图聊天头像:UIImage = UIImage(contentsOfFile: Bundle.main.path(forResource: "msg-icon", ofType: "png")!)! var 手机聊天头像:UIImage = UIImage(contentsOfFile: Bundle.main.path(forResource: "mobile-2-icon", ofType: "png")!)! var 服务器消息头像:UIImage = UIImage(contentsOfFile: Bundle.main.path(forResource: "cloud-icon", ofType: "png")!)! var 左上按钮:UIBarButtonItem? = nil var 右上按钮:UIBarButtonItem? = nil var 聊天文字输入框:UIAlertController? = nil // var 后台网页加载器:WKWebView? = nil var 正在发送的消息:String? = nil var 网络模式:网络模式选项 = 网络模式选项.提交登录请求 var 首次更新数据:Bool = true var 空白提示信息:UILabel? = nil var 已读聊天数据:Int = 0 var 上一条玩家消息内容:String = "" var 前台:Bool = false enum 网络模式选项 { case 提交登录请求 case 发送聊天消息 } override func viewWillAppear(_ animated: Bool) { 前台 = true 清除未读消息数量() } override func viewWillDisappear(_ animated: Bool) { 前台 = false } override func viewDidLoad() { super.viewDidLoad() let 背景图:UIImageView = UIImageView(frame: tableView.frame) 背景图.image = UIImage(contentsOfFile: Bundle.main.path(forResource: "bg", ofType: "jpg")!)! 背景图.contentMode = .scaleAspectFill // self.tableView.insertSubview(背景图, atIndex: 0) self.tableView.backgroundView = 背景图 self.tableView.backgroundColor = UIColor.clear self.tableView.separatorStyle = .none NotificationCenter.default.addObserver(self, selector: #selector(DMChatTVC.接收数据更新通知), name: Notification.Name("data"), object: nil) // 初始化WebView() 左上按钮 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.trash, target: self, action: #selector(DMChatTVC.左上按钮点击)) navigationItem.leftBarButtonItem = 左上按钮 右上按钮 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(DMChatTVC.右上按钮点击)) navigationItem.rightBarButtonItem = 右上按钮 左上按钮?.isEnabled = false 右上按钮?.isEnabled = false 空白提示信息 = UILabel(frame: CGRect(x: 0, y: 0-(self.navigationController?.navigationBar.frame.size.height)!, width: self.tableView.frame.size.width, height: self.tableView.frame.size.height)) 空白提示信息!.backgroundColor = UIColor.clear 空白提示信息!.textColor = UIColor.white 空白提示信息!.textAlignment = .center 空白提示信息!.text = "正在连接聊天服务器" self.view.addSubview(空白提示信息!) } func 初始化WebView() { let 浏览器设置:WKWebViewConfiguration = WKWebViewConfiguration() 浏览器设置.allowsPictureInPictureMediaPlayback = false 浏览器设置.allowsInlineMediaPlayback = false 浏览器设置.allowsAirPlayForMediaPlayback = false 浏览器设置.requiresUserActionForMediaPlayback = false 浏览器设置.suppressesIncrementalRendering = false // 浏览器设置.applicationNameForUserAgent = "Mozilla/5.0 (kagurazaka-browser)" let 浏览器偏好设置:WKPreferences = WKPreferences() 浏览器偏好设置.minimumFontSize = 40.0 浏览器偏好设置.javaScriptCanOpenWindowsAutomatically = false 浏览器偏好设置.javaScriptEnabled = false // let 用户脚本文本:String = "$('div img').remove();" // let 用户脚本:WKUserScript = WKUserScript(source: 用户脚本文本, injectionTime: .AtDocumentEnd, forMainFrameOnly: false) // 浏览器设置.userContentController.addUserScript(用户脚本) 浏览器设置.preferences = 浏览器偏好设置 浏览器设置.selectionGranularity = .dynamic // 后台网页加载器 = WKWebView(frame: CGRectMake(0, 0, 300, 300), configuration: 浏览器设置) // 后台网页加载器?.alpha = 0.5 // 后台网页加载器?.userInteractionEnabled = false // self.view.addSubview(后台网页加载器!) // 后台网页加载器!.navigationDelegate = self // 后台网页加载器!.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) // 后台网页加载器!.addObserver(self, forKeyPath: "title", options: .New, context: nil) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { 网络连接完成() } func 网络连接完成() { if (网络模式 == 网络模式选项.提交登录请求) { 网络模式 = 网络模式选项.发送聊天消息 //向服务器提交聊天消息 let 网络参数:NSString = "{\"name\":\"\",\"message\":\"§2" + 全局_手机发送消息关键字 + "§f" + 正在发送的消息! + "\"}" as NSString let 要加载的网页URL:URL = URL(string: 全局_喵窩API["消息发送接口"]!)! let 网络请求:NSMutableURLRequest = NSMutableURLRequest(url: 要加载的网页URL, cachePolicy: 全局_缓存策略, timeoutInterval: 30) let 网络参数数据:Data = 网络参数.data(using: String.Encoding.utf8.rawValue)! 网络请求.httpMethod = "POST" //§2[NyaaCatAPP] §fThis is a test message. //[urlRequest setValue: [NSString stringWithFormat:@"%@\r\n", @"http://XXXXXX HTTP/1.1"]]; //application/json , application/x-www-data-urlencoded 网络请求.setValue("application/json, text/javascript, */*; q=0.01", forHTTPHeaderField: "accept") 网络请求.setValue("gzip, deflate", forHTTPHeaderField: "accept-encoding") 网络请求.setValue("zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4", forHTTPHeaderField: "accept-language") 网络请求.setValue("\(网络参数数据.count)", forHTTPHeaderField: "content-length") 网络请求.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "content-type") 网络请求.setValue("1", forHTTPHeaderField: "dnt") 网络请求.setValue(全局_喵窩API["动态地图域名"], forHTTPHeaderField: "origin") 网络请求.setValue(全局_喵窩API["动态地图主页"], forHTTPHeaderField: "referer") 网络请求.setValue("XMLHttpRequest", forHTTPHeaderField: "x-requested-with") //网络请求.HTTPBody = 网络参数数据 // 后台网页加载器!.loadRequest(网络请求) let 上传会话 = URLSession.shared let 上传任务 = 上传会话.uploadTask(with: 网络请求 as URLRequest, from: 网络参数数据){ (data:Data?, reponse:URLResponse?, error:Error?) ->Void in if(error != nil){ self.网络连接失败(error!.localizedDescription) } else{ let 回应:String = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String if (回应 == "{\"error\":\"none\"}") { self.右上按钮?.isEnabled = true self.网络连接完成() } else { self.网络连接失败(回应) } } } 上传任务.resume() } else { 右上按钮!.isEnabled = true } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { 网络连接失败(error.localizedDescription) } func 网络连接失败(_ 错误描述:String) { NSLog("消息发送失败=%@", 错误描述) 网络模式 = 网络模式选项.提交登录请求 if (正在发送的消息 != nil) { 正在发送的消息 = 转义颜色代码(false, 内容: 正在发送的消息!) } 打开发送消息框(正在发送的消息,错误描述: 错误描述) 正在发送的消息 = nil } func 左上按钮点击() { if (全局_用户名 != nil) { NotificationCenter.default.post(name: Notification.Name(rawValue: "reloadwebview"), object: nil) } else { //正在以游客身份登录,没有参与聊天的权限 } } func 右上按钮点击() { if (全局_用户名 != nil) { 打开发送消息框(nil,错误描述: nil) } else { //正在以游客身份登录,没有参与聊天的权限 } } func 打开发送消息框(_ 重试消息:String?,错误描述:String?) { var 标题:String = "输入聊天信息" var 内容:String? = nil if (错误描述 != nil) { 内容 = "回复给 \(错误描述!): " } if (重试消息 != nil) { 标题 = "消息发送失败" 内容 = 错误描述 } 聊天文字输入框 = UIAlertController(title: 标题, message: 内容, preferredStyle: UIAlertControllerStyle.alert) let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (动作:UIAlertAction) -> Void in self.提示框处理(false) }) let okAction = UIAlertAction(title: "发送", style: UIAlertActionStyle.default, handler: { (动作:UIAlertAction) -> Void in self.提示框处理(true) }) 聊天文字输入框!.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "请在此输入要发送的内容" textField.text = 重试消息 } 聊天文字输入框!.addAction(cancelAction) 聊天文字输入框!.addAction(okAction) self.present(聊天文字输入框!, animated: true, completion: nil) } func 提示框处理(_ 确定:Bool) { if (确定 == true) { let 输入框:UITextField = 聊天文字输入框!.textFields!.first! as UITextField var 聊天文本:String? = 输入框.text if (聊天文本 != nil && 聊天文本 != "") { if (聊天文字输入框!.message != nil && 聊天文字输入框!.message != "") { 聊天文本 = 聊天文字输入框!.message! + 聊天文本! } 发送消息(聊天文本!) } } else { self.右上按钮?.isEnabled = true } 聊天文字输入框 = nil } func 转义颜色代码(_ 转义:Bool, 内容:String) -> String { if (转义 == true) { if (允许转义颜色代码) { return 内容.replacingOccurrences(of: "&", with: "§", options: NSString.CompareOptions.literal, range: nil) } } else { return 内容.replacingOccurrences(of: "§", with: "&", options: NSString.CompareOptions.literal, range: nil) } return 内容 } func 发送消息(_ 消息:String) { 右上按钮!.isEnabled = false 正在发送的消息 = 转义颜色代码(true,内容: 消息) 网络模式 = 网络模式选项.提交登录请求 let 网络参数:String = "j_username=" + 全局_用户名! + "&j_password=" + 全局_密码! let 包含参数的网址:String = 全局_喵窩API["动态地图登录接口"]! + "?" + 网络参数 let 要加载的网页URL:URL = URL(string: 包含参数的网址)! let 网络请求:NSMutableURLRequest = NSMutableURLRequest(url: 要加载的网页URL, cachePolicy: 全局_缓存策略, timeoutInterval: 10) 网络请求.httpMethod = "POST" let 上传会话 = URLSession.shared let 上传任务 = 上传会话.dataTask(with: 网络请求 as URLRequest) { (data:Data?, reponse:URLResponse?, error:Error?) in do { if(error != nil) { self.网络连接失败(error!.localizedDescription) } else { let 回应:String = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String if (回应 == "{\"result\":\"success\"}") { self.网络连接完成() } else { self.网络连接失败(回应) } } } } 上传任务.resume() } func 接收数据更新通知() { if (首次更新数据 == true) { 首次更新数据 = false 空白提示信息?.removeFromSuperview() 空白提示信息 = nil if (全局_用户名 != nil && 左上按钮?.isEnabled == false) { 左上按钮?.isEnabled = true 右上按钮?.isEnabled = true } tableView.reloadData() } if (全局_综合信息 != nil) { 实时聊天数据 = 全局_综合信息!["聊天记录"] as? [[String]] //显示消息数量 if (实时聊天数据 != nil && 实时聊天数据!.count > 0) { if (前台 == true) { 上一条玩家消息内容 = 实时聊天数据!.last![3] } else { 显示未读消息数量() } } 装入信息() } } func 清除未读消息数量() { if (全局_综合信息 != nil) { 实时聊天数据 = 全局_综合信息!["聊天记录"] as? [[String]] //显示消息数量 if (实时聊天数据 != nil && 实时聊天数据!.count > 0) { 上一条玩家消息内容 = 实时聊天数据!.last![3] } } let 当前选项卡按钮:UITabBarItem = self.tabBarController!.tabBar.items![1] 当前选项卡按钮.badgeValue = nil } func 显示未读消息数量() { let 当前选项卡按钮:UITabBarItem = self.tabBarController!.tabBar.items![1] //if (上一条玩家消息内容 == "") { // 当前选项卡按钮.badgeValue = "" // return //} let 最后一条消息:String = 实时聊天数据!.last![3] var 未读消息:Int = -1 for i:Int in 0...实时聊天数据!.count-1 { let 校对位置:Int = 实时聊天数据!.count - 1 - i let 当前消息:String = 实时聊天数据![校对位置][3] if (当前消息 == 最后一条消息) { 未读消息 = i } } NSLog("消息数据量=\(实时聊天数据!.count) , 未读消息=\(String(未读消息))") if (未读消息 == -1) { 当前选项卡按钮.badgeValue = "..." } else if (未读消息 == 0) { 当前选项卡按钮.badgeValue = nil } else if (未读消息 > 0) { 当前选项卡按钮.badgeValue = String(未读消息) } } func 装入信息() { if (实时聊天数据 != nil && (实时聊天数据?.count)! > 0) { if (tableView.contentOffset.y >= tableView.contentSize.height - tableView.frame.size.height) { tableView.reloadData() //self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true) self.tableView.scrollToRow(at: IndexPath(row: 实时聊天数据!.count-1, section: 0), at: .bottom, animated: true) } else { tableView.reloadData() } } else { tableView.reloadData() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { 全局_调整计时器延迟(10,外接电源时: 10) //列表被拖动时 } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { 全局_调整计时器延迟(3,外接电源时: 1) //列表拖动结束时 } override func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { } override func viewDidAppear(_ animated: Bool) { 全局_调整计时器延迟(3,外接电源时: 1) //进入页面时 } override func viewDidDisappear(_ animated: Bool) { 全局_调整计时器延迟(10,外接电源时: 1) //退出页面时 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (首次更新数据 == true) { return 0 } if (实时聊天数据 == nil || 实时聊天数据?.count == 0) { return 1 } return 实时聊天数据!.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: "chatcell", for: indexPath) as! DMChatTCell let row = (indexPath as NSIndexPath).row //聊天.append([玩家头像,玩家名称,类型,玩家消息]) if (实时聊天数据 == nil || 实时聊天数据?.count == 0) { cell.头像.image = 默认头像 if (全局_用户名 != nil) { cell.内容!.loadHTMLString(合并html("<span>没有数据</span>",内容文本: "暂时还没有人发送消息"), baseURL: nil) } else { cell.内容!.loadHTMLString(合并html("<span>正在以游客身份登录</span>",内容文本: "没有参与聊天的权限"), baseURL: nil) } } else { let 当前聊天:[String] = 实时聊天数据![row] //聊天.append([玩家头像,玩家名称,类型,玩家消息]) // var 头像文本路径:String = "" var 头像相对路径:String = 当前聊天[0] // if (头像相对路径 != "") { // 头像文本路径 = "https://map.nyaa.cat/tiles/faces/32x32/\(当前聊天[0])" // } else { // 头像文本路径 = 默认头像路径 // } if (头像相对路径 != "") { 头像相对路径 = "\(全局_喵窩API["32px头像接口"]!)\(当前聊天[0])" cell.头像.setImageWith(URL(string: 头像相对路径)!, placeholderImage: 默认头像) } else { //0=游戏内聊天/动态地图,1=上下线消息,2=Telegram/IRC,3=手机 if (当前聊天[1] == " Server: ") { cell.头像.image = 服务器消息头像 } else if (当前聊天[2] == "3") { cell.头像.image = 手机聊天头像 } else if (当前聊天[2] == "0") { cell.头像.image = 动态地图聊天头像 } else if (当前聊天[2] == "2") { cell.头像.image = 第三方软件发送头像 } else { cell.头像.image = 默认头像 } } cell.内容!.loadHTMLString(合并html(当前聊天[1],内容文本: 当前聊天[3]), baseURL: nil) } return cell } func 合并html(_ 名字html:String,内容文本:String) -> String { //头像URL:String, //return "<!doctype html><html><head><meta charset=\"UTF-8\"></head><body><table width=\"100%\" border=\"0\"><tbody><tr><td width=\"64\"><img src=\"\(头像URL)\" width=\"64\" height=\"64\" alt=\"\"/></td><td align=\"left\" valign=\"top\">\(名字html)<p><span style=\"color:#FF99CC\">\(内容文本)</span></td></tr></tbody></table></body></html>" return "<!doctype html><html><head><meta charset=\"UTF-8\"></head><body><font size=\"40\"><span style=\"color:#FFF;\">\(名字html)<p><span style=\"color:#FF99CC;\">\(内容文本)</span></font></body></html>" } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if (全局_用户名 != nil && 实时聊天数据 != nil && (实时聊天数据?.count)! > indexPath.row) { let 当前聊天:[String] = 实时聊天数据![indexPath.row] let 转换器:Analysis = Analysis() let 用户名单数组:[String] = 转换器.去除HTML标签(当前聊天[1], 需要合成: true) let 用户名文本:String = 用户名单数组[0] 打开发送消息框(nil,错误描述: 用户名文本) } else { //正在以游客身份登录,没有参与聊天的权限 } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
93ba470afbbf3c5d5accbf11c2124c1a
38.892495
340
0.565719
false
false
false
false
SpectralDragon/LightRoute
refs/heads/master
Sources/TransitionNodes/GenericTransitionNode.swift
mit
1
// // GenericTransitionNode.swift // LiteRoute // // Copyright © 2016-2020 Vladislav Prusakov <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// This class is main frame to transition's public class GenericTransitionNode<T> { // Main transition data. internal unowned var root: UIViewController internal var destination: UIViewController? internal var type: T.Type /// Contain moduleInput, if user wanna use custom selector internal var customModuleInput: Any? /// Wait transition post action. internal var postLinkAction: TransitionPostLinkAction? // MARK: - // MARK: Initialize /// /// Initialize transition node for current transition. /// /// - Parameters: /// - root: The root view controller. /// - destination: The view controller at which the jump occurs. /// - type: The argument which checks the specified type and controller type for compatibility, and returns this type in case of success. /// init(root: UIViewController, destination: UIViewController?, for type: T.Type) { self.root = root self.destination = destination self.type = type } /// /// This method is responsible for the delivery of the controller for the subsequent initialization, then there is a transition. /// /// - Parameter block: Initialize controller for transition and fire. /// - Throws: Throw error, if destination was nil or could not be cast to type. /// open func then(_ block: @escaping TransitionSetupBlock<T>) throws { guard let destination = self.destination else { throw LiteRouteError.viewControllerWasNil("Destination") } var moduleInput: Any? = (self.customModuleInput != nil) ? self.customModuleInput : destination.moduleInput // If first controller was UINavigationController, then try find top view controller. if destination is UINavigationController { let result = (destination as! UINavigationController).topViewController ?? destination moduleInput = (self.customModuleInput != nil) ? self.customModuleInput : result.moduleInput } var moduleOutput: Any? if moduleInput is T { moduleOutput = block(moduleInput as! T) } else if destination is T { moduleOutput = block(destination as! T) } else { throw LiteRouteError.castError(controller: .init(describing: T.self), type: "\(moduleInput as Any)") } self.destination?.moduleOutput = moduleOutput try self.perform() } /// This method makes a current transition. public func perform() throws { try self.postLinkAction?() } /// /// Methods return in clousure view controller for configure something. /// /// - Parameter block: UIViewController for configure. /// - Returns: Return current transition node. /// - Throws: Throw error, if destination was nil. /// public func apply(to block: (UIViewController) -> Void) throws -> Self { guard let destination = self.destination else { throw LiteRouteError.viewControllerWasNil("Destination") } block(destination) return self } // MARK: - // MARK: Private methods /// /// This method waits to be able to fire. /// - Parameter completion: Whait push action from `TransitionPromise` class. /// func postLinkAction( _ completion: @escaping TransitionPostLinkAction) { self.postLinkAction = completion } }
e4eb2cb2153a1fd469cb53d2ae495da4
36.457627
143
0.720136
false
false
false
false
Look-ARound/LookARound2
refs/heads/hd-callouts
lookaround2/Controllers/PlaceDetail/PlaceDetailViewController.swift
apache-2.0
3
// // PlaceDetailViewController.swift // lookaround2 // // Created by Ali Mir on 11/6/17. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit import AFNetworking import FBSDKCoreKit import FBSDKLoginKit import FBSDKShareKit import Mapbox fileprivate enum OperationType { case add case remove } internal class PlaceDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Outlets @IBOutlet private var modalView: UIView! @IBOutlet private var bookMarkButton: UIButton! @IBOutlet private var tableView: UITableView! @IBOutlet weak var addTipButton: UIButton! @IBOutlet weak var addListButton: UIButton! // MARK: - Stored Properties internal var place: Place! internal var tips = [Tip]() // MARK: - Computed Properties private var isBookMarked: Bool = false { didSet { bookMarkButton.isSelected = isBookMarked } } // MARK: - Lifecycles override func viewDidLoad() { print("load start") super.viewDidLoad() setupViews() fetchTips() print("load finish") } override func viewWillAppear(_ animated: Bool) { print("will appear") super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true fetchTips() tableView.reloadData() updateBookMarkSetup() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.isNavigationBarHidden = false } // MARK: - Setup Views private func setupViews() { modalView.layer.cornerRadius = 10 modalView.layer.masksToBounds = true addTipButton.backgroundColor = UIColor.LABrand.primary addListButton.tintColor = UIColor.LABrand.primary setupBookMarkButton() } private func setupBookMarkButton() { bookMarkButton.setImage(#imageLiteral(resourceName: "bookmark"), for: .normal) bookMarkButton.setImage(#imageLiteral(resourceName: "bookmarked"), for: .selected) bookMarkButton.tintColor = UIColor.LABrand.primary } private func updateBookMarkSetup() { DatabaseRequests.shared.fetchCurrentUserLists(success: { lists in self.bookMarkButton.isSelected = false guard let lists = lists else { return } for list in lists { if list.name == "Bookmarks" { if list.placeIDs.contains(self.place.id) { self.isBookMarked = true } } } }, failure: nil) } // MARK: - Helpers private func addTip(text: String) { Tip.CreateTip(for: place.id, text: text) { tip, error in if let tip = tip { DatabaseRequests.shared.addTip(tip: tip) self.tips.append(tip) let indexPath = IndexPath(row: self.tips.count - 1, section: 2) self.tableView.beginUpdates() self.tableView.insertRows(at: [indexPath], with: .automatic) self.tableView.endUpdates() } else { _ = SweetAlert().showAlert("Error", subTitle: error!.localizedDescription, style: .error) } } } private func fetchTips() { DatabaseRequests.shared.fetchTips(for: place.id, success: { tipsArray in if let tips = tipsArray { self.tips = tips self.tableView.reloadData() } return }, failure: { error in if let error = error { _ = SweetAlert().showAlert("Error", subTitle: error.localizedDescription, style: .error) } }) } private func updateBookmark(operation: OperationType) { switch operation { case .add: addToBookmarks() case .remove: removeFromBookmarks() } } private func addToBookmarks() { DatabaseRequests.shared.fetchCurrentUserLists(success: { lists in guard let lists = lists else { return } for list in lists { if list.name == "Bookmarks" { list.placeIDs.append(self.place.id) self.createOrUpdateList(for: list) return } } self.createOrUpdateList(for: List(name: "Bookmarks", placeID: self.place.id)) }, failure: nil) } private func removeFromBookmarks() { DatabaseRequests.shared.fetchCurrentUserLists(success: { lists in guard let lists = lists else { return } for list in lists { if list.name == "Bookmarks" { for (index, placeID) in list.placeIDs.enumerated() { if placeID == self.place.id { list.placeIDs.remove(at: index) self.createOrUpdateList(for: list) return } } } } }, failure: nil) } private func createOrUpdateList(for list: List?) { guard let list = list else { _ = SweetAlert().showAlert("Error", subTitle: "Could not save bookmark!", style: .error) return } DatabaseRequests.shared.createOrUpdateList(list: list) { error in if let error = error { _ = SweetAlert().showAlert("Error", subTitle: error.localizedDescription, style: .error) } } } // MARK: - Target/Actions @IBAction private func onBGTap(_ sender: UITapGestureRecognizer) { self.dismiss(animated: true, completion: nil) } @IBAction private func onBookmarkToggle(_ sender: Any) { isBookMarked = !isBookMarked updateBookmark(operation: isBookMarked ? .add : .remove) } @IBAction private func onAddTip(_ sender: Any) { let alertVC = UIAlertController(title: "Add a tip", message: nil, preferredStyle: .alert) alertVC.addTextField { textField in textField.placeholder = "Type your tip here" } let saveAction = UIAlertAction(title: "Save", style: .default) { _ in if let text = alertVC.textFields?[0].text { self.addTip(text: text) } } alertVC.addAction(saveAction) alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertVC, animated: true, completion: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addPlaceVC" { let addPlaceVC = segue.destination as! AddPlaceViewController addPlaceVC.place = self.place } } // MARK: - UITableView Setup func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return 1 default: return tips.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let placeImageCell = tableView.dequeueReusableCell(withIdentifier: "placeImageCell", for: indexPath) as! PlaceImageTableViewCell placeImageCell.imageURLString = place.picture return placeImageCell case 1: let placeDetailCell = tableView.dequeueReusableCell(withIdentifier: "placeDetailCell", for: indexPath) as! PlaceDetailCell placeDetailCell.initCell(with: place) return placeDetailCell default: let tipsCell = tableView.dequeueReusableCell(withIdentifier: "placeTipsCell", for: indexPath) as! PlaceTipsCell tipsCell.tip = tips[indexPath.row] return tipsCell } } }
c03e308e98bc10bc5d32be6174a7a177
31.305019
140
0.574877
false
false
false
false
almazrafi/Metatron
refs/heads/master
Sources/ID3v2/FrameStuffs/ID3v2TimeValue.swift
mit
1
// // ID3v2TimeValue.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension ID3v2TextInformation { // MARK: Instance Properties public var timeValue: TagTime { get { guard let field = self.fields.first else { return TagTime() } let characters = [Character](field.characters) guard characters.count == 4 else { return TagTime() } guard let hour = Int(String(characters.prefix(2))) else { return TagTime() } guard let minute = Int(String(characters.suffix(2))) else { return TagTime() } return TagTime(hour: hour, minute: minute) } set { if newValue.isValid && ((newValue.hour > 0) || (newValue.minute > 0)) { self.fields = [String(format: "%02d%02d", newValue.hour, newValue.minute)] } else { self.fields.removeAll() } } } }
3d725c7f1b19959204b94fa244507b4a
32.984127
84
0.640822
false
false
false
false
lexicalparadox/Chirppy
refs/heads/master
Chirppy/ReplyViewController.swift
apache-2.0
1
// // ReplyViewController.swift // Chirppy // // Created by Alexander Doan on 9/27/17. // Copyright © 2017 Alexander Doan. All rights reserved. // import UIKit import SwiftDate class ReplyViewController: UIViewController { @IBOutlet weak var retweetButton: UIImageView! @IBOutlet weak var favoriteButton: UIImageView! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var createdAtLabel: UILabel! @IBOutlet weak var homeButton: UIBarButtonItem! @IBOutlet weak var replyButton: UIBarButtonItem! @IBOutlet weak var tweetLabel: UILabel! @IBOutlet weak var textView: UITextView! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoritesCountLabel: UILabel! let retweet = UIImage(named: "retweet.png") let favorite = UIImage(named: "favorite.png") let heartEmpty = UIImage(named: "heart_empty.png") let heartFilled = UIImage(named: "heart_filled_2.png") let retweetGreen = UIImage(named: "retweet_green.png") let client = TwitterClient.sharedInstance var tweet: Tweet! override func viewDidLoad() { super.viewDidLoad() profileImageView.setImageWith(URL(string: (tweet.user?.profileImageUrl)!)!) profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true nameLabel.text = tweet.user?.name ?? "Default name" usernameLabel.text = String(format: "@%@", tweet.user?.screenName ?? "@Default screen name") tweetLabel.text = tweet.text ?? "Default tweet, because I wasn't able to find an actual tweet for this user!" let createdAtDate = tweet.createdAtDate! let formattedDate = createdAtDate.string(custom: "MM/dd/yy h:mm a") createdAtLabel.text = formattedDate // createdAtLabel.text = tweet.createdAt! retweetCountLabel.text = "\(tweet.retweetCount!)" favoritesCountLabel.text = "\(tweet.favoritesCount!)" if tweet.favorited ?? false { self.favoriteButton.image = heartFilled } else { self.favoriteButton.image = favorite } if tweet.retweeted ?? false { self.retweetButton.image = retweetGreen } else { self.retweetButton.image = retweet } // tapping reply, retweet, favorite images let retweetTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TimelineTweetCell.retweetImageTapped(tapGestureRecognizer:))) self.retweetButton.isUserInteractionEnabled = true self.retweetButton.addGestureRecognizer(retweetTapRecognizer) let favoriteTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TimelineTweetCell.favoriteImageTapped(tapGestureRecognizer:))) self.favoriteButton.isUserInteractionEnabled = true self.favoriteButton.addGestureRecognizer(favoriteTapRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func retweetImageTapped(tapGestureRecognizer: UITapGestureRecognizer) { let retweetGreen = UIImage(named: "retweet_green.png") self.retweetButton.image = retweetGreen client.postRetweet(tweetId: self.tweet.id!, success: { print("Successfully retweeted for user: \(self.tweet.user?.screenName) and tweetId: \(self.tweet.id)") }) { (error: Error) in print(error) } } func favoriteImageTapped(tapGestureRecognizer: UITapGestureRecognizer) { let heartFilled = UIImage(named: "heart_filled_2.png") self.favoriteButton.image = heartFilled var parameters = [String:String]() parameters["id"] = String(format: "%ld", tweet.id!) client.postFavorite(queryParameters: parameters, success: { print("Successfully favorited a tweet for user: \(self.tweet.user?.screenName) and tweetId: \(self.tweet.id)") }) { (error: Error) in print(error) } } @IBAction func onHomeButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func onReplyButton(_ sender: Any) { let isEmpty = self.textView.text.isEmpty if isEmpty { return } else { let count = self.textView.text.characters.count if count <= 140 { var parameters = [String:String]() let chirp = self.textView.text parameters["status"] = chirp parameters["in_reply_to_status_id"] = "\(tweet.id!)" client.postTweet(queryParameters: parameters, success: { (tweet: Tweet) in print("Successfully replied to chirp: \(self.tweet.text) for \(self.tweet.user?.screenName)") self.dismiss(animated: true, completion: nil) }, failure: { (error: Error) in print("Failed to chirp: \(error.localizedDescription)") }) } } } /* // 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. } */ }
c0a672965546098d5711ca2fb16d7858
38.408451
153
0.645818
false
false
false
false
fafhrd91/fut
refs/heads/master
Tests/FutureTests.swift
apache-2.0
1
// // FutureTests.swift // fut // // Created by Nikolay on 1/25/17. // Copyright © 2017 nkim. All rights reserved. // import XCTest @testable import fut class FutureTests: XCTestCase { func testCtor() { let fut = Future<Int>(1) switch fut.state { case .finished(let res): XCTAssertEqual(res, 1) default: XCTFail() } XCTAssertEqual(fut, fut) XCTAssertNotEqual(fut, Future<Int>(1)) XCTAssertNotEqual(fut.hashValue, Future<Int>(1).hashValue) } func testDone() { let fut = Future<Int>() XCTAssertFalse(fut.isDone()) _ = fut.cancel() XCTAssertTrue(fut.isDone()) XCTAssertTrue(Future<Int>(1).isDone()) } func testCancel() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } let cancelled = fut.cancel() XCTAssertTrue(cancelled) XCTAssertEqual(result, 0) fut.set(1) XCTAssertEqual(result, 0) XCTAssertFalse(fut.cancel()) } func testMerge() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } _ = fut.notify(.Same) { res in result += 100 } let fut2 = Future<Int>() fut2.merge(fut) fut2.set(1) fut.set(1) XCTAssertEqual(result, 101) } func testMergeSelfFinished() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } _ = fut.notify(.Same) { res in result += 100 } let fut2 = Future<Int>(1) fut2.merge(fut) XCTAssertEqual(result, 101) } func testMergeSelfCancelled() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } _ = fut.notify(.Same) { res in result += 100 } let fut2 = Future<Int>() _ = fut2.cancel() fut2.merge(fut) XCTAssertEqual(result, 100) } func testReset() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } _ = fut.notify(.Same) { res in result += 100 } fut.reset() fut.set(1) XCTAssertEqual(result, 0) } func testWait() { let fut = Future<Int>() var result = 0 _ = fut.wait(.Same) { res in result += res } fut.set(1) XCTAssertTrue(result==1) } func testWaitFinished() { var result = 0 let fut = Future<Int>() fut.set(1) // wait on finished future _ = fut.wait(.Same) { res in result += res } XCTAssertTrue(result==1) } func testWaitCancelled() { let fut = Future<Int>() let cancelled = fut.cancel() XCTAssertTrue(cancelled) var result = 0 _ = fut.wait(.Same) { res in result += res } XCTAssertEqual(result, 0) } func testWaitWithContext() { let fut = Future<Int>() var result = 0 _ = fut.wait(self, on:.Same) { ctx, res in result += res } fut.set(1) XCTAssertTrue(result==1) } func testWaitFinishedWithContext() { var result = 0 let fut = Future<Int>() fut.set(1) // wait on finished future _ = fut.wait(self, on:.Same) { ctx, res in result += res } XCTAssertTrue(result==1) } func testWaitCancelledWithContext() { let fut = Future<Int>() let cancelled = fut.cancel() XCTAssertTrue(cancelled) var result = 0 _ = fut.wait(self, on:.Same) { ctx, res in result += res } XCTAssertEqual(result, 0) } func testNotify() { let fut = Future<Int>() var result = 0 _ = fut.notify(.Same) { res in switch res { case .finished(let val): result += val default: XCTFail() } } fut.set(1) XCTAssertTrue(result==1) } func testNotifyCancel() { let fut = Future<Int>() var result = 0 _ = fut.notify(.Same) { res in switch res { case .cancelled: result = 100 default: XCTFail() } } _ = fut.cancel() XCTAssertTrue(result==100) } func testNotifyFinished() { var result = 0 let fut = Future<Int>() fut.set(1) // wait on finished future _ = fut.notify(.Same) { res in switch res { case .finished(let val): result += val default: XCTFail() } } XCTAssertTrue(result==1) } func testNotifyCancelled() { let fut = Future<Int>() let cancelled = fut.cancel() XCTAssertTrue(cancelled) var result = 0 _ = fut.notify(.Same) { res in switch res { case .cancelled: result = 100 default: XCTFail() } } XCTAssertEqual(result, 100) } func testNotifyWithContext() { let fut = Future<Int>() var result = 0 _ = fut.notify(self, on:.Same) { ctx, res in switch res { case .finished(let val): result += val default: XCTFail() } } fut.set(1) XCTAssertTrue(result==1) } func testNotifyCancelWithContext() { let fut = Future<Int>() var result = 0 _ = fut.notify(self, on:.Same) { ctx, res in switch res { case .cancelled: result = 100 default: XCTFail() } } _ = fut.cancel() XCTAssertTrue(result==100) } func testNotifyFinishedWithContext() { var result = 0 let fut = Future<Int>() fut.set(1) // wait on finished future _ = fut.notify(self, on:.Same) { ctx, res in switch res { case .finished(let val): result += val default: XCTFail() } } XCTAssertTrue(result==1) } func testNotifyCancelledWithContext() { let fut = Future<Int>() let cancelled = fut.cancel() XCTAssertTrue(cancelled) var result = 0 _ = fut.notify(self, on:.Same) { ctx, res in switch res { case .cancelled: result = 100 default: XCTFail() } } XCTAssertEqual(result, 100) } }
c1f1d0b5181ad725da28c13072fa4f03
20.934985
66
0.459562
false
true
false
false
amraboelela/swift
refs/heads/master
test/SILGen/class_resilience.swift
apache-2.0
4
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-emit-silgen -module-name class_resilience -I %t -enable-resilience %s | %FileCheck %s import resilient_class // Accessing final property of resilient class from different resilience domain // through accessor // CHECK-LABEL: sil [ossa] @$s16class_resilience20finalPropertyOfOtheryy010resilient_A022ResilientOutsideParentCF // CHECK: function_ref @$s15resilient_class22ResilientOutsideParentC13finalPropertySSvg public func finalPropertyOfOther(_ other: ResilientOutsideParent) { _ = other.finalProperty } public class MyResilientClass { public final var finalProperty: String = "MyResilientClass.finalProperty" } // Accessing final property of resilient class from my resilience domain // directly // CHECK-LABEL: sil [ossa] @$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF // CHECK: bb0([[ARG:%.*]] : @guaranteed $MyResilientClass): // CHECK: ref_element_addr [[ARG]] : $MyResilientClass, #MyResilientClass.finalProperty // CHECK: } // end sil function '$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF' public func finalPropertyOfMine(_ other: MyResilientClass) { _ = other.finalProperty } class SubclassOfOutsideChild : ResilientOutsideChild { override func method() {} func newMethod() {} } // Note: no entries for [inherited] methods // CHECK-LABEL: sil_vtable SubclassOfOutsideChild { // CHECK-NEXT: #ResilientOutsideParent.init!allocator.1: (ResilientOutsideParent.Type) -> () -> ResilientOutsideParent : @$s16class_resilience22SubclassOfOutsideChildCACycfC [override] // CHECK-NEXT: #ResilientOutsideParent.method!1: (ResilientOutsideParent) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC6methodyyF [override] // CHECK-NEXT: #SubclassOfOutsideChild.newMethod!1: (SubclassOfOutsideChild) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC9newMethodyyF // CHECK-NEXT: #SubclassOfOutsideChild.deinit!deallocator.1: @$s16class_resilience22SubclassOfOutsideChildCfD // CHECK-NEXT: }
e2140756ee88a7f784bfd194f4c3f932
48.708333
185
0.782062
false
false
false
false
Bartlebys/Bartleby
refs/heads/master
Bartleby.xOS/_generated/operations/ReadBoxesByIds.swift
apache-2.0
1
// // ReadBoxesByIds.swift // Bartleby // // THIS FILE AS BEEN GENERATED BY BARTLEBYFLEXIONS for [Benoit Pereira da Silva] (https://pereira-da-silva.com/contact) // DO NOT MODIFY THIS FILE YOUR MODIFICATIONS WOULD BE ERASED ON NEXT GENERATION! // // Copyright (c) 2016 [Bartleby's org] (https://bartlebys.org) All rights reserved. // import Foundation #if !USE_EMBEDDED_MODULES import Alamofire #endif @objc public class ReadBoxesByIdsParameters : ManagedModel { // Universal type support override open class func typeName() -> String { return "ReadBoxesByIdsParameters" } // public var ids:[String]? // public var result_fields:[String]? // the sort (MONGO DB) public var sort:[String:Int] = [String:Int]() required public init(){ super.init() } // MARK: - Exposed (Bartleby's KVC like generative implementation) /// Return all the exposed instance variables keys. (Exposed == public and modifiable). override open var exposedKeys:[String] { var exposed=super.exposedKeys exposed.append(contentsOf:["ids","result_fields","sort"]) return exposed } /// Set the value of the given key /// /// - parameter value: the value /// - parameter key: the key /// /// - throws: throws an Exception when the key is not exposed override open func setExposedValue(_ value:Any?, forKey key: String) throws { switch key { case "ids": if let casted=value as? [String]{ self.ids=casted } case "result_fields": if let casted=value as? [String]{ self.result_fields=casted } case "sort": if let casted=value as? [String:Int]{ self.sort=casted } default: return try super.setExposedValue(value, forKey: key) } } /// Returns the value of an exposed key. /// /// - parameter key: the key /// /// - throws: throws Exception when the key is not exposed /// /// - returns: returns the value override open func getExposedValueForKey(_ key:String) throws -> Any?{ switch key { case "ids": return self.ids case "result_fields": return self.result_fields case "sort": return self.sort default: return try super.getExposedValueForKey(key) } } // MARK: - Codable public enum CodingKeys: String,CodingKey{ case ids case result_fields case sort } required public init(from decoder: Decoder) throws{ try super.init(from: decoder) try self.quietThrowingChanges { let values = try decoder.container(keyedBy: CodingKeys.self) self.ids = try values.decodeIfPresent([String].self,forKey:.ids) self.result_fields = try values.decodeIfPresent([String].self,forKey:.result_fields) self.sort = try values.decode([String:Int].self,forKey:.sort) } } override open func encode(to encoder: Encoder) throws { try super.encode(to:encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.ids,forKey:.ids) try container.encodeIfPresent(self.result_fields,forKey:.result_fields) try container.encode(self.sort,forKey:.sort) } } @objc(ReadBoxesByIds) open class ReadBoxesByIds : ManagedModel{ // Universal type support override open class func typeName() -> String { return "ReadBoxesByIds" } public static func execute(from documentUID:String, parameters:ReadBoxesByIdsParameters, sucessHandler success:@escaping(_ boxes:[Box])->(), failureHandler failure:@escaping(_ context:HTTPContext)->()){ if let document = Bartleby.sharedInstance.getDocumentByUID(documentUID) { let pathURL=document.baseURL.appendingPathComponent("boxes") let dictionary:[String:Any]? = parameters.dictionaryRepresentation() let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:document.UID,withActionName:"ReadBoxesByIds" ,forMethod:"GET", and: pathURL) do { let r=try URLEncoding().encode(urlRequest,with:dictionary) request(r).responseData(completionHandler: { (response) in let request=response.request let result=response.result let timeline=response.timeline let statusCode=response.response?.statusCode ?? 0 let context = HTTPContext( code: 3862038994, caller: "ReadBoxesByIds.execute", relatedURL:request?.url, httpStatusCode: statusCode) if let request=request{ context.request=HTTPRequest(urlRequest: request) } if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { context.responseString=utf8Text } let metrics=Metrics() metrics.httpContext=context metrics.operationName="ReadBoxesByIds" metrics.latency=timeline.latency metrics.requestDuration=timeline.requestDuration metrics.serializationDuration=timeline.serializationDuration metrics.totalDuration=timeline.totalDuration document.report(metrics) // React according to the situation var reactions = Array<Reaction> () if result.isFailure { let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) }else{ if 200...299 ~= statusCode { do{ if let data = response.data{ let instance = try JSON.decoder.decode([Box].self,from:data) success(instance) }else{ throw BartlebyOperationError.dataNotFound } }catch{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title:"\(error)", body: "\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } }else{ // Bartlby does not currenlty discriminate status codes 100 & 101 // and treats any status code >= 300 the same way // because we consider that failures differentiations could be done by the caller. let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } //Let s react according to the context. document.perform(reactions, forContext: context) }) }catch{ let context = HTTPContext( code:2 , caller: "ReadBoxesByIds.execute", relatedURL:nil, httpStatusCode:500) failure(context) } }else{ let context = HTTPContext( code: 1, caller: "ReadBoxesByIds.execute", relatedURL:nil, httpStatusCode: 417) failure(context) } } }
e8331ca957403acdb92a403ed43080d4
38.170306
150
0.53757
false
false
false
false
iSapozhnik/home-surveillance-osx
refs/heads/master
HomeSurveillance/SignalProvider/SignalProvider.swift
mit
1
// // SignalProvider.swift // HomeSurveillance // // Created by Sapozhnik Ivan on 22/03/17. // Copyright © 2017 Sapozhnik Ivan. All rights reserved. // import Cocoa import AVFoundation class SignalProvider: NSObject { func startMonitoring(onUpdate: @escaping (SignalProvider) -> ()) { //FIXME: remove observer NotificationCenter.default .addObserver(forName: NSNotification.Name.AVCaptureDeviceWasDisconnected, object: nil, queue: nil) { (notif) -> Void in onUpdate(self) } NotificationCenter.default .addObserver(forName: NSNotification.Name.AVCaptureDeviceWasConnected, object: nil, queue: nil) { (notif) -> Void in onUpdate(self) } } func allProviders() -> [SignalProviderItem] { let captureDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as! [AVCaptureDevice] if !captureDevices.isEmpty { let providers = captureDevices.map() { return DefaultCameraProvider.provider(withCaptureDevice: $0 ) } return providers } else { return [NoCameraProvider()] } } /* func setupCameraSession() { let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice let captureDevice = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) do { let deviceInput = try AVCaptureDeviceInput(device: captureDevice) cameraSession.beginConfiguration() if (cameraSession.canAddInput(deviceInput) == true) { cameraSession.addInput(deviceInput) } let dataOutput = AVCaptureVideoDataOutput() dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as UInt32)] dataOutput.alwaysDiscardsLateVideoFrames = true if (cameraSession.canAddOutput(dataOutput) == true) { cameraSession.addOutput(dataOutput) } cameraSession.commitConfiguration() let queue = DispatchQueue(label: "com.invasivecode.videoQueue") dataOutput.setSampleBufferDelegate(self, queue: queue) } catch let error as NSError { NSLog("\(error), \(error.localizedDescription)") } } */ }
d08daec0c8833300a0ce6227e8fde82d
32.571429
163
0.606576
false
false
false
false
ShengQiangLiu/arcgis-runtime-samples-ios
refs/heads/master
OfflineFeatureEditingSample/swift/OfflineFeatureEditing/ViewController.swift
apache-2.0
2
// Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm import Foundation import UIKit import ArcGIS let kTilePackageName = "SanFrancisco" let kFeatureServiceURL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer" class ViewController:UIViewController, AGSLayerDelegate, AGSMapViewTouchDelegate, AGSMapViewLayerDelegate, AGSCalloutDelegate, FeatureTemplatePickerDelegate, AGSPopupsContainerDelegate { @IBOutlet weak var mapView: AGSMapView! @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var geometryEditToolbar: UIToolbar! @IBOutlet weak var liveActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var offlineStatusLabel: UILabel! @IBOutlet weak var logsLabel: UILabel! @IBOutlet weak var logsTextView: UITextView! @IBOutlet weak var goOfflineButton: UIBarButtonItem! @IBOutlet weak var syncButton: UIBarButtonItem! @IBOutlet weak var badgeView: UIView! var badge:JSBadgeView! var geodatabase:AGSGDBGeodatabase! var gdbTask:AGSGDBSyncTask! var cancellable:AGSCancellable! var localTiledLayer:AGSLocalTiledLayer! var featureTemplatePickerVC:FeatureTemplatePickerViewController! var popupsVC:AGSPopupsContainerViewController! var sketchGraphicsLayer:AGSSketchGraphicsLayer! var goingLocal = false var goingLive = false var viewingLocal = false var newlyDownloaded = false var allStatus:String = "" override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // self.navigationController.navigationBarHidden = true } override func viewDidLoad() { super.viewDidLoad() //Add the basemap layer from a tile package self.localTiledLayer = AGSLocalTiledLayer(name: kTilePackageName) //Add layer delegate to catch errors in case the local tiled layer is replaced and problems arise self.localTiledLayer.delegate = self //setup the map view self.mapView.addMapLayer(self.localTiledLayer) self.mapView.touchDelegate = self self.mapView.layerDelegate = self self.mapView.callout.delegate = self //Add a swipe gesture recognizer that will show the logs text view let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showLogsGesture:") swipeGestureRecognizer.direction = .Up self.logsLabel.addGestureRecognizer(swipeGestureRecognizer) //Add a tap gesture recognizer that will hide the logs text view let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideLogsGesture:") self.logsTextView.addGestureRecognizer(tapGestureRecognizer) self.switchToLiveData() } //MARK: - Gesture recognizers func hideLogsGesture(gestureRecognizer:UIGestureRecognizer) { self.logsTextView.hidden = true } func showLogsGesture(gestureRecognizer:UIGestureRecognizer) { self.logsTextView.hidden = false println("textview text \(self.logsTextView.text)") } //MARK: - AGSLayerDelegate methods func layerDidLoad(layer: AGSLayer!) { if layer is AGSFeatureTableLayer { let featureTableLayer = layer as! AGSFeatureTableLayer if self.mapView.mapScale > featureTableLayer.minScale { self.mapView.zoomToScale(featureTableLayer.minScale, animated: true) } SVProgressHUD.popActivity() } } func layer(layer: AGSLayer!, didFailToLoadWithError error: NSError!) { var errormsg:String! if layer is AGSFeatureTableLayer { let featureTableLayer = layer as! AGSFeatureTableLayer errormsg = "Failed to load \(featureTableLayer.name). Error: \(error)" //activity shown when loading online layer, dismiss this SVProgressHUD.popActivity() } else if layer is AGSLocalTiledLayer { errormsg = "Failed to load local tiled layer. Error:\(error)" } self.logStatus(errormsg) } //MARK: - AGSMapViewTouchDelegate methods func mapView(mapView: AGSMapView!, didClickAtPoint screen: CGPoint, mapPoint mappoint: AGSPoint!, features: [NSObject : AnyObject]!) { //Show popups for features that were tapped on var tappedFeatures = [AGSFeature]() for (key, value) in features { let graphics = value as! [AGSFeature] for graphic in graphics as [AGSFeature] { tappedFeatures.append(graphic) } } if tappedFeatures.count > 0 { self.showPopupsForFeatures(tappedFeatures) } else{ self.hidePopupsVC() } } //MARK: - Showing popups func showPopupsForFeatures(features:[AGSFeature]) { var popups = [AGSPopup]() for feature in features as [AGSFeature] { let gdbFeature = feature as! AGSGDBFeature let popupInfo = AGSPopupInfo(forGDBFeatureTable: gdbFeature.table) let popup = AGSPopup(GDBFeature: gdbFeature, popupInfo: popupInfo) popups.append(popup) } self.showPopupsVCForPopups(popups) } func hidePopupsVC() { if self.popupsVC != nil { self.popupsVC.dismissViewControllerAnimated(true, completion: { self.popupsVC = nil }) } } func showPopupsVCForPopups(popups:[AGSPopup]) { self.hidePopupsVC() //Create the view controller for the popups self.popupsVC = AGSPopupsContainerViewController(popups: popups, usingNavigationControllerStack: false) self.popupsVC.delegate = self self.popupsVC.style = .Black self.popupsVC.modalPresentationStyle = .FormSheet self.presentViewController(self.popupsVC, animated: true, completion: nil) } //MARK: - Action methods @IBAction func addFeatureAction(sender:AnyObject) { //Initialize the template picker view controller if self.featureTemplatePickerVC == nil { let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) if let controller = storyboard.instantiateViewControllerWithIdentifier("FeatureTemplatePickerViewController") as? FeatureTemplatePickerViewController { self.featureTemplatePickerVC = controller self.featureTemplatePickerVC.delegate = self self.featureTemplatePickerVC.addTemplatesForLayersInMap(self.mapView) self.featureTemplatePickerVC.modalPresentationStyle = .FormSheet } } self.presentViewController(self.featureTemplatePickerVC, animated: true, completion: nil) } @IBAction func deleteGDBAction(sender:AnyObject) { if self.viewingLocal || self.goingLocal { self.logStatus("cannot delete local data while displaying it") return } self.geodatabase = nil //Remove all files with .geodatabase, .geodatabase-shm and .geodatabase-wal file extensions let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let path = paths[0] as! String let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path, error: nil) for file in files as! [String] { let remove = file.hasSuffix(".geodatabase") || file.hasSuffix(".geodatabase-shm") || file.hasSuffix(".geodatabase-wal") if remove { NSFileManager.defaultManager().removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil) self.logStatus("deleting file: \(file)") } } self.logStatus("deleted all local data") } @IBAction func syncAction() { if (self.cancellable != nil) { //if already syncing just return return } SVProgressHUD.showWithStatus("Synchronizing \n changes") self.logStatus("Starting sync process...") //Create default sync params based on the geodatabase //You can modify the param to change sync options (sync direction, included layers, etc) let params = AGSGDBSyncParameters(geodatabase: self.geodatabase) //kick off the sync operation self.cancellable = self.gdbTask.syncGeodatabase(self.geodatabase, params: params, status: { [weak self] (status, userInfo) -> Void in if let weakSelf = self { let statusString = weakSelf.statusMessageForAsyncStatus(status) weakSelf.logStatus("sync status: \(statusString)") } }, completion: { [weak self] (editErrors, syncError) -> Void in if let weakSelf = self { weakSelf.cancellable = nil if syncError != nil { weakSelf.logStatus("error sync'ing: \(syncError)") SVProgressHUD.showErrorWithStatus("Error encountered") } else { //TODO: Handle sync edit errors weakSelf.logStatus("sync complete") SVProgressHUD.showSuccessWithStatus("Sync complete") //Remove the local edits badge from the sync button weakSelf.showEditsInGeodatabaseAsBadge(nil) } } }) } @IBAction func switchModeAction(sender:AnyObject) { if self.goingLocal { return } if self.viewingLocal { if self.geodatabase.hasLocalEdits() { let alertView = UIAlertView(title: "Local data contains edit", message: "Do you want to sync them with the service?", delegate: nil, cancelButtonTitle: "Later", otherButtonTitles: "Ok") alertView.showWithCompletion({ (alertView, buttonIndex) -> Void in if buttonIndex == 0 { //No just switch to live self.switchToLiveData() } else { //Yes, sync instead self.syncAction() } }) return } else { self.switchToLiveData() } } else { self.switchToLocalData() } } //MARK: - Online/Offline methods func switchToLiveData() { SVProgressHUD.showWithStatus("Loading Live Data") self.goingLive = true self.logStatus("loading live data") //Clear out the template picker so that we create it again when needed using templates in the live data self.featureTemplatePickerVC = nil self.gdbTask = AGSGDBSyncTask(URL: NSURL(string: kFeatureServiceURL)) self.gdbTask.loadCompletion = { [weak self] error in if let weakSelf = self { SVProgressHUD.dismiss() if error != nil { weakSelf.logStatus("Error while switching to live data : \(error)") return } //remove all local feature layers for layer in weakSelf.mapView.mapLayers { //tried using the optional chaining in the for loop but getting an error if layer is AGSFeatureTableLayer { weakSelf.mapView.removeMapLayer(layer as! AGSFeatureTableLayer) } } //Add live feature layers for info in weakSelf.gdbTask.featureServiceInfo.layerInfos as! [AGSMapServiceLayerInfo] { let url = weakSelf.gdbTask.URL.URLByAppendingPathComponent("\(info.layerId)") let featureServiceTable = AGSGDBFeatureServiceTable(serviceURL: url, credential: weakSelf.gdbTask.credential, spatialReference: weakSelf.mapView.spatialReference) let featureTableLayer = AGSFeatureTableLayer(featureTable: featureServiceTable) featureTableLayer.delegate = weakSelf weakSelf.mapView.addMapLayer(featureTableLayer) weakSelf.logStatus("Loading: \(featureServiceTable.serviceURL.absoluteString)") } weakSelf.logStatus("now in live mode") weakSelf.updateStatus() } } self.goingLive = false self.viewingLocal = false } func switchToLocalData() { self.goingLocal = true //Clear out the template picker so that we create it again when needed using templates in the local data self.featureTemplatePickerVC = nil let params = AGSGDBGenerateParameters(featureServiceInfo: self.gdbTask.featureServiceInfo) //NOTE: You should typically set this to a smaller envelope covering an area of interest //Setting to maxEnvelope here because sample data covers limited area in San Franscisco params.extent = self.mapView.maxEnvelope params.outSpatialReference = self.mapView.spatialReference var layers = [UInt]() for layerInfo in self.gdbTask.featureServiceInfo.layerInfos as! [AGSMapServiceLayerInfo] { layers += [layerInfo.layerId] } params.layerIDs = layers self.newlyDownloaded = false SVProgressHUD.showWithStatus("Preparing to \n download") self.gdbTask.generateGeodatabaseWithParameters(params, downloadFolderPath: nil, useExisting: true, status: { [weak self] (status, userInfo) -> Void in if let weakSelf = self { //If we are fetching result, display download progress if status == AGSResumableTaskJobStatus.FetchingResult { weakSelf.newlyDownloaded = true let totalBytesDownloaded: AnyObject? = userInfo?["AGSDownloadProgressTotalBytesDownloaded"] let totalBytesExpected: AnyObject? = userInfo?["AGSDownloadProgressTotalBytesExpected"] if totalBytesDownloaded != nil && totalBytesExpected != nil { let dPercentage = Float(totalBytesDownloaded! as! NSNumber)/Float(totalBytesExpected! as! NSNumber) SVProgressHUD.showProgress(dPercentage, status: "Downloading \n features") } } else { //don't want to log status for "fetching result" state because //status block gets called many times a second when downloading //we only log status for other states here weakSelf.logStatus("Status: \(weakSelf.statusMessageForAsyncStatus(status))") } } }) { [weak self] (geodatabase, error) -> Void in if let weakSelf = self { if (error != nil) { //handle the error weakSelf.goingLocal = false weakSelf.viewingLocal = false weakSelf.logStatus("error taking feature layers offline: \(error)") println(error) SVProgressHUD.showErrorWithStatus("Couldn't download features") } else { //take app into offline mode weakSelf.goingLocal = false weakSelf.viewingLocal = true weakSelf.logStatus("now viewing local data") BackgroundHelper.postLocalNotificationIfAppNotActive("Features downloaded.") //remove the live feature layers for layer in weakSelf.mapView.mapLayers as! [AGSLayer] { //check if explicitly assigning AGSLayer affects layer from being AGSFeatureLayer if layer is AGSFeatureTableLayer { weakSelf.mapView.removeMapLayer(layer) } } //Add layers from local database weakSelf.geodatabase = geodatabase for featureTable in geodatabase.featureTables() as! [AGSFeatureTable] { if featureTable.hasGeometry() { weakSelf.mapView.addMapLayer(AGSFeatureTableLayer(featureTable: featureTable)) } } if weakSelf.newlyDownloaded { SVProgressHUD.showSuccessWithStatus("Finished \n downloading") } else { SVProgressHUD.dismiss() weakSelf.showEditsInGeodatabaseAsBadge(geodatabase) let alertView = UIAlertView(title: "Found local data", message: "It may contain edits or may be out of date. Do you want to synchronize it with the service?", delegate: nil, cancelButtonTitle: "Later", otherButtonTitles: "Yes") alertView.showWithCompletion({ [weak self] (alertView, buttonIndex) -> Void in if let weakSelf = self { if buttonIndex == 1 { //Yes, sync weakSelf.syncAction() } } }) } } weakSelf.updateStatus() } } // } //MARK: - FeatureTemplatePickerViewControllerDelegate methods func featureTemplatePickerViewController(controller: FeatureTemplatePickerViewController, didSelectFeatureTemplate template: AGSFeatureTemplate, forLayer layer: AGSGDBFeatureSourceInfo) { //same for ipad and iphone controller.dismissViewControllerAnimated(true, completion: { () -> Void in //Create new feature with template let featureTable = layer as! AGSGDBFeatureTable let feature = featureTable.featureWithTemplate(template) //Create popup for new feature, commence edit mode let popupInfo = AGSPopupInfo(forGDBFeatureTable: featureTable) let popup = AGSPopup(GDBFeature: feature, popupInfo: popupInfo) self.showPopupsVCForPopups([popup]) self.popupsVC.startEditingCurrentPopup() }) } func featureTemplatePickerViewControllerWasDismissed(controller: FeatureTemplatePickerViewController) { controller.dismissViewControllerAnimated(true, completion: nil) } //MARK: - AGSPopupsContainerDelegate methods func popupsContainer(popupsContainer: AGSPopupsContainer!, wantsNewMutableGeometryForPopup popup: AGSPopup!) -> AGSGeometry! { switch popup.gdbFeatureSourceInfo.geometryType { case .Point: return AGSMutablePoint(spatialReference: self.mapView.spatialReference) case .Polygon: return AGSMutablePolygon(spatialReference: self.mapView.spatialReference) case .Polyline: return AGSMutablePolyline(spatialReference: self.mapView.spatialReference) default: return AGSMutablePoint(spatialReference: self.mapView.spatialReference) } } func popupsContainer(popupsContainer: AGSPopupsContainer!, readyToEditGeometry geometry: AGSGeometry!, forPopup popup: AGSPopup!) { if self.sketchGraphicsLayer == nil { self.sketchGraphicsLayer = AGSSketchGraphicsLayer(geometry: geometry) self.mapView.addMapLayer(self.sketchGraphicsLayer) self.mapView.touchDelegate = sketchGraphicsLayer } else { sketchGraphicsLayer.geometry = geometry } //Hide the popupsVC and show editing UI self.popupsVC.dismissViewControllerAnimated(true, completion: nil) self.toggleGeometryEditUI() } func popupsContainerDidFinishViewingPopups(popupsContainer: AGSPopupsContainer!) { //this clears _currentPopups self.hidePopupsVC() } func popupsContainer(popupsContainer: AGSPopupsContainer!, didCancelEditingForPopup popup: AGSPopup!) { self.mapView.removeMapLayer(self.sketchGraphicsLayer) self.sketchGraphicsLayer = nil self.mapView.touchDelegate = self self.hidePopupsVC() } func popupsContainer(popupsContainer: AGSPopupsContainer!, didFinishEditingForPopup popup: AGSPopup!) { //Remove sketch layer self.mapView.removeMapLayer(self.sketchGraphicsLayer) self.sketchGraphicsLayer = nil self.mapView.touchDelegate = self //popup vc has already committed edits to the local geodatabase at this point if self.viewingLocal { //if we are in local data mode, show edits as badge over the sync button //and wait for the user to explicitly sync changes back up to the service self.showEditsInGeodatabaseAsBadge(popup.gdbFeatureTable.geodatabase) self.logStatus("feature saved in local geodatabase") self.hidePopupsVC() } else { //we are in live data mode, apply edits to the service immediately SVProgressHUD.showWithStatus("Applying edit to server...") let featureServiceTable = popup.gdbFeatureTable as! AGSGDBFeatureServiceTable featureServiceTable.applyFeatureEditsWithCompletion({ [weak self] (featureEditErrors, error) -> Void in if let weakSelf = self { SVProgressHUD.dismiss() if error != nil { let alertView = UIAlertView(title: "Error", message: "Could not apply edit to server", delegate: nil, cancelButtonTitle: "OK") alertView.show() weakSelf.logStatus("Error while applying edit: \(error.localizedDescription)") } else { for featureEditError in featureEditErrors as! [AGSGDBFeatureEditError] { weakSelf.logStatus("Edit to feature (OBJECTID = \(featureEditError.objectID) rejected by server because : \(featureEditError.localizedDescription))") } //if the dataset support attachments, apply attachment edits if featureServiceTable.hasAttachments { SVProgressHUD.showWithStatus("Applying attachment edits to server...") featureServiceTable.applyAttachmentEditsWithCompletion({ [weak self] (attachmentEditErrors, error) -> Void in if let weakSelf = self { SVProgressHUD.dismiss() if error != nil { UIAlertView(title: "Error", message: "Could not apply edit to server", delegate: nil, cancelButtonTitle: "OK").show() weakSelf.logStatus("Error while applying attachment edit : \(error.localizedDescription)") } else { if attachmentEditErrors != nil { for attachmentEditError in attachmentEditErrors as! [AGSGDBFeatureEditError] { weakSelf.logStatus("Edit to attachment (OBJECTID = \(attachmentEditError.attachmentID) rejected by server because : \(attachmentEditError.localizedDescription))") } } //Dismiss the popups VC, All edits have been applied weakSelf.hidePopupsVC() } } }) } } } }) } } func popupsContainer(popupsContainer: AGSPopupsContainer!, didDeleteForPopup popup: AGSPopup!) { //popup vc has already committed edits to the local geodatabase at this point if self.viewingLocal { //if we are in local data mode, show edits as badge over the sync button //and wait for the user to explicitly sync changes back up to the service self.logStatus("delete succeeded") self.showEditsInGeodatabaseAsBadge(popup.gdbFeatureTable.geodatabase) self.hidePopupsVC() } else { //we are in live data mode, apply edits to the service immediately SVProgressHUD.showWithStatus("Applying edit to server...") let featureServiceTable = popup.gdbFeatureTable as! AGSGDBFeatureServiceTable featureServiceTable.applyFeatureEditsWithCompletion({ [weak self] (featureEditErrors, error) -> Void in if let weakSelf = self { SVProgressHUD.dismiss() if error != nil { let alertView = UIAlertView(title: "Error", message: "Could not apply edit to server", delegate: nil, cancelButtonTitle: "OK") alertView.show() weakSelf.logStatus("Error while applying edit: \(error.localizedDescription)") } else { for featureEditError in featureEditErrors as! [AGSGDBFeatureEditError] { weakSelf.logStatus("Deleting feature (OBJECTID = \(featureEditError.objectID) rejected by server because : \(featureEditError.localizedDescription))") } weakSelf.logStatus("feature deleted in server") weakSelf.hidePopupsVC() } } }) } } //MARK: - Convenience methods func numberOfEditsInGeodatabase(geodatabase:AGSGDBGeodatabase) -> Int { var total = 0 for featureTable in geodatabase.featureTables() as! [AGSGDBFeatureTable] { total += featureTable.addedFeatures().count + featureTable.deletedFeatures().count + featureTable.updatedFeatures().count } return total } func logStatus(var status:String) { dispatch_async(dispatch_get_main_queue(), { //show basic status self.logsLabel.text = status let hideText = "\nTap to hide..." let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .ShortStyle status = "\(dateFormatter.stringFromDate(NSDate())) - \(status)\n\n" self.allStatus = status+self.allStatus // println("self.allStatus \(self.allStatus)") self.logsTextView.text = hideText + "\n\n" + self.allStatus // println("textview text \(self.logsTextView.text)") //write to log file let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.logAppStatus(status) let delay = 2 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { self.clearStatus() }) }) } func clearStatus() { self.logsLabel.text = "swipe up to show activity log" } func updateStatus() { dispatch_async(dispatch_get_main_queue(), { //set status if self.goingLocal { self.offlineStatusLabel.text = "switching to local data..." } else if self.goingLive { self.offlineStatusLabel.text = "switching to live data..." } else if self.viewingLocal { self.offlineStatusLabel.text = "Local data" self.goOfflineButton.title = "switch to live" } else if !self.viewingLocal { self.offlineStatusLabel.text = "Live data" self.goOfflineButton.title = "download" self.showEditsInGeodatabaseAsBadge(nil) } self.goOfflineButton.enabled = !self.goingLocal && !self.goingLive self.syncButton.enabled = self.viewingLocal }) } func statusMessageForAsyncStatus(status:AGSResumableTaskJobStatus) -> String { return AGSResumableTaskJobStatusAsString(status) } func showEditsInGeodatabaseAsBadge(geodatabase:AGSGDBGeodatabase?) { if self.badge != nil { self.badge.removeFromSuperview() } if geodatabase != nil && geodatabase!.hasLocalEdits() { self.badge = JSBadgeView(parentView: self.badgeView, alignment: .CenterRight) self.badge.badgeText = "\(self.numberOfEditsInGeodatabase(geodatabase!))" } } //MARK: - Sketch toolbar UI func toggleGeometryEditUI() { self.geometryEditToolbar.hidden = !self.geometryEditToolbar.hidden } @IBAction func cancelEditGeometry(sender:AnyObject) { self.doneEditingGeometry() } @IBAction func doneEditingGeometry() { if self.sketchGraphicsLayer != nil { self.mapView.removeMapLayer(self.sketchGraphicsLayer) self.sketchGraphicsLayer = nil self.mapView.touchDelegate = self self.toggleGeometryEditUI() self.presentViewController(self.popupsVC, animated: true, completion: nil) } } }
36f1db95dc889d93da203d1e5f1b4545
44.079595
255
0.58676
false
false
false
false
kaltura/playkit-ios
refs/heads/develop
Example/PlayKit/ViewController.swift
agpl-3.0
1
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, // unless a different license for a particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import UIKit import PlayKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
6f682b77cb76b2b1e7b6237c1e444ccb
19.684211
102
0.505089
false
false
false
false
laszlokorte/reform-swift
refs/heads/master
ReformCore/ReformCore/StaticPoint.swift
mit
1
// // StaticPoint.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformMath struct StaticPoint : WriteableRuntimePoint { fileprivate let formId : FormIdentifier fileprivate let offset : Int init(formId: FormIdentifier, offset: Int) { self.formId = formId self.offset = offset } func getPositionFor<R:Runtime>(_ runtime: R) -> Vec2d? { guard let x = runtime.read(formId, offset: offset), let y = runtime.read(formId, offset: offset+1) else { return nil } return Vec2d(x: Double(bitPattern: x), y:Double(bitPattern: y)) } func setPositionFor<R:Runtime>(_ runtime: R, position: Vec2d) { runtime.write(formId, offset: offset, value: position.x.bitPattern) runtime.write(formId, offset: offset+1, value: position.y.bitPattern) } } extension StaticPoint : Equatable { } func ==(lhs: StaticPoint, rhs: StaticPoint) -> Bool { return lhs.formId == rhs.formId && lhs.offset == rhs.offset }
edccdd1b27f6dc6a38feeff71bf38328
24.636364
77
0.625
false
false
false
false
duemunk/Thread
refs/heads/master
Source/Thread.swift
mit
1
// // Thread.swift // Thread // // This code is based on the following StackOverflow answer: http://stackoverflow.com/a/22091859 // Permission to redristribute has been granted by the original author (Marc Haisenko). // // Created by Tobias Due Munk on 27/11/15. // Copyright (c) 2015 Tobias Due Munk. All rights reserved. // import Foundation /// FIFO. First-In-First-Out guaranteed on exactly same thread. class Thread: NSThread { typealias Block = () -> () private let condition = NSCondition() private(set) var queue = [Block]() private(set) var paused: Bool = false /** Designated initializer. - parameters: - start: Boolean whether thread should start immediately. Defaults to true. - queue: Initial array of blocks to add to enqueue. Executed in order of objects in array. */ init(start: Bool = true, queue: [Block]? = nil) { super.init() // Add blocks initially to queue if let queue = queue { for block in queue { enqueue(block) } } // Start thread if start { self.start() } } /** The main entry point routine for the thread. You should never invoke this method directly. You should always start your thread by invoking the start method. Shouldn't invoke `super`. */ final override func main() { // Infinite loops until thread is cancelled while true { // Use NSCondition. Comments are from Apple documentation on NSCondition // 1. Lock the condition object. condition.lock() // 2. Test a boolean predicate. (This predicate is a boolean flag or other variable in your code that indicates whether it is safe to perform the task protected by the condition.) // If no blocks (or paused) and not cancelled while (queue.count == 0 || paused) && !cancelled { // 3. If the boolean predicate is false, call the condition object’s wait or waitUntilDate: method to block the thread. Upon returning from these methods, go to step 2 to retest your boolean predicate. (Continue waiting and retesting the predicate until it is true.) condition.wait() } // 4. If the boolean predicate is true, perform the task. // If your thread supports cancellation, it should check this property periodically and exit if it ever returns true. if (cancelled) { condition.unlock() return } // As per http://stackoverflow.com/a/22091859 by Marc Haisenko: // Execute block outside the condition, since it's also a lock! // We want to give other threads the possibility to enqueue // a new block while we're executing a block. let block = queue.removeFirst() condition.unlock() // Run block block() } } /** Add a block to be run on the thread. FIFO. - parameters: - block: The code to run. */ final func enqueue(block: Block) { // Lock to ensure first-in gets added to array first condition.lock() // Add to queue queue.append(block) // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Start the thread. - Warning: Don't start thread again after it has been cancelled/stopped. - SeeAlso: .start() - SeeAlso: .pause() */ final override func start() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Unpause. Might be in pause state // Start super.start() // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Cancels the thread. - Warning: Don't start thread again after it has been cancelled/stopped. Use .pause() instead. - SeeAlso: .start() - SeeAlso: .pause() */ final override func cancel() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Cancel NSThread super.cancel() // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Pause the thread. To completely stop it (i.e. remove it from the run-time), use `.cancel()` - Warning: Thread is still runnin, - SeeAlso: .start() - SeeAlso: .cancel() */ final func pause() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // paused = true // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Resume the execution of blocks from the queue on the thread. - Warning: Can't resume if thread was cancelled/stopped. - SeeAlso: .start() - SeeAlso: .cancel() */ final func resume() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // paused = false // Release from .wait() condition.signal() // Release lock condition.unlock() } /** Empty the queue for any blocks that hasn't been run yet - SeeAlso: - .enqueue(block: Block) - .cancel() */ final func emptyQueue() { // Lock to let all mutations to behaviour obey FIFO condition.lock() // Remove any blocks from the queue queue.removeAll() // Release from .wait() condition.signal() // Release lock condition.unlock() } }
e5c692e20997f568caa72f6d11e1660d
30.480874
282
0.580628
false
false
false
false
danielrhodes/Swift-ActionCableClient
refs/heads/master
Example/ActionCableClient/ChatViewController.swift
mit
1
// // Copyright (c) 2016 Daniel Rhodes <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import ActionCableClient import SnapKit import SwiftyJSON class ChatViewController: UIViewController { static var MessageCellIdentifier = "MessageCell" static var ChannelIdentifier = "ChatChannel" static var ChannelAction = "talk" let client = ActionCableClient(url: URL(string:"wss://actioncable-echo.herokuapp.com/cable")!) var channel: Channel? var history: Array<ChatMessage> = Array() var name: String? var chatView: ChatView? override func viewDidLoad() { super.viewDidLoad() self.title = "Chat" chatView = ChatView(frame: view.bounds) view.addSubview(chatView!) chatView?.snp.remakeConstraints({ (make) -> Void in make.top.bottom.left.right.equalTo(self.view) }) chatView?.tableView.delegate = self chatView?.tableView.dataSource = self chatView?.tableView.separatorInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) chatView?.tableView.allowsSelection = false chatView?.tableView.register(ChatCell.self, forCellReuseIdentifier: ChatViewController.MessageCellIdentifier) chatView?.textField.delegate = self setupClient() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let alert = UIAlertController(title: "Chat", message: "What's Your Name?", preferredStyle: UIAlertControllerStyle.alert) var nameTextField: UITextField? alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "Name" //🙏 Forgive me father, for I have sinned. 🙏 nameTextField = textField }) alert.addAction(UIAlertAction(title: "Start", style: UIAlertActionStyle.default) {(action: UIAlertAction) in self.name = nameTextField?.text self.chatView?.textField.becomeFirstResponder() }) self.present(alert, animated: true, completion: nil) } } // MARK: ActionCableClient extension ChatViewController { func setupClient() -> Void { self.client.willConnect = { print("Will Connect") } self.client.onConnected = { print("Connected to \(self.client.url)") } self.client.onDisconnected = {(error: ConnectionError?) in print("Disconected with error: \(String(describing: error))") } self.client.willReconnect = { print("Reconnecting to \(self.client.url)") return true } self.channel = client.create(ChatViewController.ChannelIdentifier) self.channel?.onSubscribed = { print("Subscribed to \(ChatViewController.ChannelIdentifier)") } self.channel?.onReceive = {(data: Any?, error: Error?) in if let error = error { print(error.localizedDescription) return } let JSONObject = JSON(data!) let msg = ChatMessage(name: JSONObject["name"].string!, message: JSONObject["message"].string!) self.history.append(msg) self.chatView?.tableView.reloadData() // Scroll to our new message! if (msg.name == self.name) { let indexPath = IndexPath(row: self.history.count - 1, section: 0) self.chatView?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) } } self.client.connect() } func sendMessage(_ message: String) { let prettyMessage = message.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (!prettyMessage.isEmpty) { print("Sending Message: \(ChatViewController.ChannelIdentifier)#\(ChatViewController.ChannelAction)") _ = self.channel?.action(ChatViewController.ChannelAction, with: ["name": self.name!, "message": prettyMessage] ) } } } //MARK: UITextFieldDelegate extension ChatViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.sendMessage(textField.text!) textField.text = "" return true } } //MARK: UITableViewDelegate extension ChatViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let message = history[(indexPath as NSIndexPath).row] let attrString = message.attributedString() let width = self.chatView?.tableView.bounds.size.width; let rect = attrString.boundingRect(with: CGSize(width: width! - (ChatCell.Inset * 2.0), height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context:nil) return rect.size.height + (ChatCell.Inset * 2.0) } } //MARK: UITableViewDataSource extension ChatViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return history.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ChatViewController.MessageCellIdentifier, for: indexPath) as! ChatCell let msg = history[(indexPath as NSIndexPath).row] cell.message = msg return cell } } //MARK: ChatMessage struct ChatMessage { var name: String var message: String func attributedString() -> NSAttributedString { let messageString: String = "\(self.name) \(self.message)" let nameRange = NSRange(location: 0, length: self.name.characters.count) let nonNameRange = NSRange(location: nameRange.length, length: messageString.characters.count - nameRange.length) let string: NSMutableAttributedString = NSMutableAttributedString(string: messageString) string.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 18.0), range: nameRange) string.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 18.0), range: nonNameRange) return string } }
9711804b0108b15712373f1e6f643370
37.26
137
0.648327
false
false
false
false
jeremiahyan/ResearchKit
refs/heads/main
Testing/ORKTest/ORKTest/Charts/ChartListViewController.swift
bsd-3-clause
3
/* Copyright (c) 2015, James Cox. All rights reserved. Copyright (c) 2015, Ricardo Sánchez-Sáez. Copyright (c) 2018, Brian Ganninger. 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 UIKit import ResearchKit func executeAfterDelay(_ delay: Double, closure: @escaping () -> Void) { let delayTime = DispatchTime.now() + delay let dispatchWorkItem = DispatchWorkItem(block: closure) DispatchQueue.main.asyncAfter( deadline: delayTime, execute: dispatchWorkItem) } class ChartListViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! let colorlessPieChartDataSource = ColorlessPieChartDataSource() let randomColorPieChartDataSource = RandomColorPieChartDataSource() let lineGraphChartDataSource = LineGraphChartDataSource() let coloredLineGraphChartDataSource = ColoredLineGraphChartDataSource() let discreteGraphChartDataSource = DiscreteGraphChartDataSource() let coloredDiscreteGraphChartDataSource = ColoredDiscreteGraphChartDataSource() let barGraphChartDataSource = BarGraphChartDataSource() let coloredBarGraphChartDataSource = ColoredBarGraphChartDataSource() let pieChartIdentifier = "PieChartCell" let lineGraphChartIdentifier = "LineGraphChartCell" let discreteGraphChartIdentifier = "DiscreteGraphChartCell" let barGraphChartIdentifier = "BarGraphChartCell" var pieChartTableViewCell: PieChartTableViewCell! var lineGraphChartTableViewCell: LineGraphChartTableViewCell! var discreteGraphChartTableViewCell: DiscreteGraphChartTableViewCell! var barGraphChartTableViewCell: BarGraphChartTableViewCell! var chartTableViewCells: [UITableViewCell]! @IBAction func dimiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self // ORKPieChartView pieChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: pieChartIdentifier) as? PieChartTableViewCell let pieChartView = pieChartTableViewCell.pieChartView pieChartView?.dataSource = randomColorPieChartDataSource // Optional custom configuration pieChartView?.title = "TITLE" pieChartView?.text = "TEXT" pieChartView?.lineWidth = 1000 pieChartView?.showsTitleAboveChart = true pieChartView?.showsPercentageLabels = false pieChartView?.drawsClockwise = false pieChartView?.titleFont = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.bold) pieChartView?.subtitleFont = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.thin) pieChartView?.noDataFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.black) pieChartView?.percentageLabelFont = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.light) pieChartView?.legendFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.heavy) executeAfterDelay(2.5) { pieChartView?.showsTitleAboveChart = false pieChartView?.lineWidth = 12 pieChartView?.title = "UPDATED" pieChartView?.text = "UPDATED TEXT" pieChartView?.titleColor = UIColor.red pieChartView?.textColor = UIColor.orange pieChartView?.titleFont = nil pieChartView?.subtitleFont = nil pieChartView?.noDataFont = nil pieChartView?.percentageLabelFont = nil pieChartView?.legendFont = nil } executeAfterDelay(3.5) { pieChartView?.drawsClockwise = true pieChartView?.dataSource = self.colorlessPieChartDataSource } executeAfterDelay(4.5) { pieChartView?.showsPercentageLabels = true pieChartView?.tintColor = UIColor.purple pieChartView?.percentageLabelFont = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.light) pieChartView?.legendFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.heavy) } executeAfterDelay(5.5) { pieChartView?.titleColor = nil pieChartView?.textColor = nil pieChartView?.percentageLabelFont = nil pieChartView?.legendFont = nil } // ORKBarGraphChartView barGraphChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: barGraphChartIdentifier) as? BarGraphChartTableViewCell let barGraphChartView = barGraphChartTableViewCell.graphChartView as! ORKBarGraphChartView barGraphChartView.dataSource = barGraphChartDataSource executeAfterDelay(1.5) { barGraphChartView.tintColor = UIColor.purple barGraphChartView.showsHorizontalReferenceLines = true barGraphChartView.showsVerticalReferenceLines = true } executeAfterDelay(2.5) { barGraphChartView.axisColor = UIColor.red barGraphChartView.verticalAxisTitleColor = UIColor.red barGraphChartView.referenceLineColor = UIColor.orange barGraphChartView.scrubberLineColor = UIColor.blue barGraphChartView.scrubberThumbColor = UIColor.green barGraphChartView.xAxisFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.light) barGraphChartView.yAxisFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.light) barGraphChartView.noDataFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.heavy) barGraphChartView.scrubberFont = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium) } executeAfterDelay(3.5) { barGraphChartView.axisColor = nil barGraphChartView.verticalAxisTitleColor = nil barGraphChartView.referenceLineColor = nil barGraphChartView.scrubberLineColor = nil barGraphChartView.scrubberThumbColor = nil barGraphChartView.xAxisFont = nil barGraphChartView.yAxisFont = nil barGraphChartView.noDataFont = nil barGraphChartView.scrubberFont = nil } executeAfterDelay(4.5) { barGraphChartView.dataSource = self.coloredBarGraphChartDataSource } executeAfterDelay(5.5) { let maximumValueImage = UIImage(named: "GraphMaximumValueTest")! let minimumValueImage = UIImage(named: "GraphMinimumValueTest")! barGraphChartView.maximumValueImage = maximumValueImage barGraphChartView.minimumValueImage = minimumValueImage } // ORKLineGraphChartView lineGraphChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: lineGraphChartIdentifier) as? LineGraphChartTableViewCell let lineGraphChartView = lineGraphChartTableViewCell.graphChartView as! ORKLineGraphChartView lineGraphChartView.dataSource = lineGraphChartDataSource // Optional custom configuration executeAfterDelay(1.5) { lineGraphChartView.tintColor = UIColor.purple lineGraphChartView.showsHorizontalReferenceLines = true lineGraphChartView.showsVerticalReferenceLines = true } executeAfterDelay(2.5) { lineGraphChartView.axisColor = UIColor.red lineGraphChartView.verticalAxisTitleColor = UIColor.red lineGraphChartView.referenceLineColor = UIColor.orange lineGraphChartView.scrubberLineColor = UIColor.blue lineGraphChartView.scrubberThumbColor = UIColor.green lineGraphChartView.xAxisFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.light) lineGraphChartView.yAxisFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.light) lineGraphChartView.noDataFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.heavy) lineGraphChartView.scrubberFont = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium) } executeAfterDelay(3.5) { lineGraphChartView.axisColor = nil lineGraphChartView.verticalAxisTitleColor = nil lineGraphChartView.referenceLineColor = nil lineGraphChartView.scrubberLineColor = nil lineGraphChartView.scrubberThumbColor = nil } executeAfterDelay(4.5) { lineGraphChartView.dataSource = self.coloredLineGraphChartDataSource lineGraphChartView.xAxisFont = nil lineGraphChartView.yAxisFont = nil lineGraphChartView.noDataFont = nil lineGraphChartView.scrubberFont = nil } executeAfterDelay(5.5) { let maximumValueImage = UIImage(named: "GraphMaximumValueTest")! let minimumValueImage = UIImage(named: "GraphMinimumValueTest")! lineGraphChartView.maximumValueImage = maximumValueImage lineGraphChartView.minimumValueImage = minimumValueImage } // ORKDiscreteGraphChartView discreteGraphChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: discreteGraphChartIdentifier) as? DiscreteGraphChartTableViewCell let discreteGraphChartView = discreteGraphChartTableViewCell.graphChartView as! ORKDiscreteGraphChartView discreteGraphChartView.dataSource = discreteGraphChartDataSource // Optional custom configuration discreteGraphChartView.showsHorizontalReferenceLines = true discreteGraphChartView.showsVerticalReferenceLines = true discreteGraphChartView.drawsConnectedRanges = true discreteGraphChartView.xAxisFont = UIFont.systemFont(ofSize: 9, weight: UIFont.Weight.thin) discreteGraphChartView.yAxisFont = UIFont.systemFont(ofSize: 8, weight: UIFont.Weight.light) discreteGraphChartView.noDataFont = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.heavy) discreteGraphChartView.scrubberFont = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium) executeAfterDelay(2.5) { discreteGraphChartView.tintColor = UIColor.purple } executeAfterDelay(3.5) { discreteGraphChartView.drawsConnectedRanges = false } executeAfterDelay(4.5) { discreteGraphChartView.dataSource = self.coloredDiscreteGraphChartDataSource discreteGraphChartView.xAxisFont = nil discreteGraphChartView.yAxisFont = nil discreteGraphChartView.noDataFont = nil discreteGraphChartView.scrubberFont = nil } executeAfterDelay(5.5) { discreteGraphChartView.drawsConnectedRanges = true } chartTableViewCells = [pieChartTableViewCell, barGraphChartTableViewCell, lineGraphChartTableViewCell, discreteGraphChartTableViewCell] tableView.tableFooterView = UIView(frame: CGRect.zero) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chartTableViewCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = chartTableViewCells[(indexPath as NSIndexPath).row] return cell } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.layoutIfNeeded() pieChartTableViewCell.pieChartView.animate(withDuration: 0.5) lineGraphChartTableViewCell.graphChartView.animate(withDuration: 0.5) discreteGraphChartTableViewCell.graphChartView.animate(withDuration: 0.5) discreteGraphChartTableViewCell.graphChartView.animate(withDuration: 2.5) } } class ChartPerformanceListViewController: UIViewController, UITableViewDataSource { @IBOutlet var tableView: UITableView! let lineGraphChartIdentifier = "LineGraphChartCell" let discreteGraphChartIdentifier = "DiscreteGraphChartCell" let graphChartDataSource = PerformanceLineGraphChartDataSource() var lineGraphChartTableViewCell: LineGraphChartTableViewCell! let discreteGraphChartDataSource = DiscreteGraphChartDataSource() var discreteGraphChartTableViewCell: DiscreteGraphChartTableViewCell! var chartTableViewCells: [UITableViewCell]! @IBAction func dimiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self // ORKLineGraphChartView lineGraphChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: lineGraphChartIdentifier) as? LineGraphChartTableViewCell let lineGraphChartView = lineGraphChartTableViewCell.graphChartView as! ORKLineGraphChartView lineGraphChartView.dataSource = graphChartDataSource // Optional custom configuration lineGraphChartView.showsHorizontalReferenceLines = true lineGraphChartView.showsVerticalReferenceLines = true // ORKDiscreteGraphChartView discreteGraphChartTableViewCell = tableView.dequeueReusableCell(withIdentifier: discreteGraphChartIdentifier) as? DiscreteGraphChartTableViewCell let discreteGraphChartView = discreteGraphChartTableViewCell.graphChartView as! ORKDiscreteGraphChartView discreteGraphChartView.dataSource = graphChartDataSource // Optional custom configuration discreteGraphChartView.showsHorizontalReferenceLines = true discreteGraphChartView.showsVerticalReferenceLines = true discreteGraphChartView.drawsConnectedRanges = true chartTableViewCells = [lineGraphChartTableViewCell, discreteGraphChartTableViewCell] tableView.tableFooterView = UIView(frame: CGRect.zero) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chartTableViewCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = chartTableViewCells[(indexPath as NSIndexPath).row] return cell } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) lineGraphChartTableViewCell.graphChartView.animate(withDuration: 0.5) } }
50eb9d9685584b07a7911f1d2943bad6
49.155556
153
0.728907
false
false
false
false
JGiola/swift
refs/heads/main
test/SILGen/inlinable_attribute.swift
apache-2.0
5
// RUN: %target-swift-emit-silgen -module-name inlinable_attribute -emit-verbose-sil -warnings-as-errors -disable-availability-checking %s | %FileCheck %s // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute15fragileFunctionyyF : $@convention(thin) () -> () @inlinable public func fragileFunction() { } public struct MySt { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV6methodyyF : $@convention(method) (MySt) -> () @inlinable public func method() {} // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStV8propertySivg : $@convention(method) (MySt) -> Int @inlinable public var property: Int { return 5 } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute4MyStVyS2icig : $@convention(method) (Int, MySt) -> Int @inlinable public subscript(x: Int) -> Int { return x } } public class MyCls { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyClsCfD : $@convention(method) (@owned MyCls) -> () @inlinable deinit {} // Allocating entry point is [serialized] // CHECK-LABEL: sil [serialized] [exact_self_class] [ossa] @$s19inlinable_attribute5MyClsC14designatedInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public init(designatedInit: ()) {} // Note -- convenience init is intentionally not [serialized] // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyClsC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls public convenience init(convenienceInit: ()) { self.init(designatedInit: ()) } } public actor MyAct { // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyActCfD : $@convention(method) (@owned MyAct) -> () @inlinable deinit {} /// whether delegating or not, the initializers for an actor are not serialized unless marked inlinable. // CHECK-LABEL: sil [exact_self_class] [ossa] @$s19inlinable_attribute5MyActC14designatedInitACyt_tcfC : $@convention(method) (@thick MyAct.Type) -> @owned MyAct // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyActC14designatedInitACyt_tcfc : $@convention(method) (@owned MyAct) -> @owned MyAct public init(designatedInit: ()) {} // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute5MyActC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyAct.Type) -> @owned MyAct public init(convenienceInit: ()) { self.init(designatedInit: ()) } // CHECK-LABEL: sil [serialized] [exact_self_class] [ossa] @$s19inlinable_attribute5MyActC0A14DesignatedInitACyt_tcfC : $@convention(method) (@thick MyAct.Type) -> @owned MyAct // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyActC0A14DesignatedInitACyt_tcfc : $@convention(method) (@owned MyAct) -> @owned MyAct @inlinable public init(inlinableDesignatedInit: ()) {} // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute5MyActC0A15ConvenienceInitACyt_tcfC : $@convention(method) (@thick MyAct.Type) -> @owned MyAct @inlinable public init(inlinableConvenienceInit: ()) { self.init(designatedInit: ()) } } // Make sure enum case constructors for public and versioned enums are // [serialized]. @usableFromInline enum MyEnum { case c(MySt) } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16referencesMyEnumyyFAA0dE0OAA0D2StVcADmcfu_ : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16referencesMyEnumyyFAA0dE0OAA0D2StVcADmcfu_AdFcfu0_ : $@convention(thin) (MySt, @thin MyEnum.Type) -> MyEnum { @inlinable public func referencesMyEnum() { _ = MyEnum.c } // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1xSivpfi : $@convention(thin) () -> Int // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s19inlinable_attribute15HasInitializersV1ySivpfi : $@convention(thin) () -> Int @frozen public struct HasInitializers { public let x = 1234 internal let y = 4321 @inlinable public init() {} } public class Horse { public func gallop() {} } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_ : $@convention(thin) (@guaranteed Horse) -> @owned @callee_guaranteed () -> () { // CHECK: function_ref @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_yycfu0_ // CHECK: return // CHECK: } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute15talkAboutAHorse1hyAA5HorseC_tFyycAEcfu_yycfu0_ : $@convention(thin) (@guaranteed Horse) -> () { // CHECK: class_method %0 : $Horse, #Horse.gallop : (Horse) -> () -> (), $@convention(method) (@guaranteed Horse) -> () // CHECK: return // CHECK: } @inlinable public func talkAboutAHorse(h: Horse) { _ = h.gallop } @_fixed_layout public class PublicBase { @inlinable public init(horse: Horse) {} } @usableFromInline @_fixed_layout class UFIBase { @usableFromInline @inlinable init(horse: Horse) {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0Cfd : $@convention(method) (@guaranteed PublicDerivedFromPublic) -> @owned Builtin.NativeObject // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0CfD : $@convention(method) (@owned PublicDerivedFromPublic) -> () // Make sure the synthesized delegating initializer is inlinable also // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute017PublicDerivedFromC0C5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PublicDerivedFromPublic) -> @owned PublicDerivedFromPublic @_fixed_layout public class PublicDerivedFromPublic : PublicBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute20UFIDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromPublic) -> @owned UFIDerivedFromPublic @usableFromInline @_fixed_layout class UFIDerivedFromPublic : PublicBase { } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute17UFIDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned UFIDerivedFromUFI) -> @owned UFIDerivedFromUFI @usableFromInline @_fixed_layout class UFIDerivedFromUFI : UFIBase { // Allow @inlinable deinits @inlinable deinit {} } // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute25InternalDerivedFromPublicC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromPublic) -> @owned InternalDerivedFromPublic class InternalDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil hidden [ossa] @$s19inlinable_attribute22InternalDerivedFromUFIC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned InternalDerivedFromUFI) -> @owned InternalDerivedFromUFI class InternalDerivedFromUFI : UFIBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute24PrivateDerivedFromPublic{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromPublic) -> @owned PrivateDerivedFromPublic private class PrivateDerivedFromPublic : PublicBase {} // CHECK-LABEL: sil private [ossa] @$s19inlinable_attribute21PrivateDerivedFromUFI{{.+}}LLC5horseAdA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned PrivateDerivedFromUFI) -> @owned PrivateDerivedFromUFI private class PrivateDerivedFromUFI : UFIBase {} // Make sure that nested functions are also serializable. // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute3basyyF @inlinable public func bas() { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF func zim() { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyF3zimL_yyF4zangL_yyF func zang() { } } // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3bas{{[_0-9a-zA-Z]*}}U_ let _ = { // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute3basyyFyycfU_7zippityL_yyF func zippity() { } } } // CHECK-LABEL: sil [ossa] @$s19inlinable_attribute6globalyS2iF : $@convention(thin) (Int) -> Int public func global(_ x: Int) -> Int { return x } // CHECK-LABEL: sil [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF : $@convention(thin) () -> () @inlinable func cFunctionPointer() { // CHECK: function_ref @$s19inlinable_attribute6globalyS2iFTo let _: @convention(c) (Int) -> Int = global // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To let _: @convention(c) (Int) -> Int = { return $0 } func local(_ x: Int) -> Int { return x } // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo let _: @convention(c) (Int) -> Int = local } // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute6globalyS2iFTo : $@convention(c) (Int) -> Int // CHECK: function_ref @$s19inlinable_attribute6globalyS2iF // CHECK: return // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_To : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyFS2icfU_ // CHECK: return // CHECK-LABEL: sil shared [serialized] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF : $@convention(thin) (Int) -> Int { // CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iFTo : $@convention(c) (Int) -> Int { // CHECK: function_ref @$s19inlinable_attribute16cFunctionPointeryyF5localL_yS2iF // CHECK: return
03d5086b2992ef03bea18fc65ebde93c
45.317536
221
0.738975
false
false
false
false
hearther/ZipArchive
refs/heads/master
SwiftExample/SwiftExample/ViewController.swift
mit
1
// // ViewController.swift // SwiftExample // // Created by Sean Soper on 10/23/15. // // import UIKit #if UseCarthage import ZipArchive #else import SSZipArchive #endif class ViewController: UIViewController { @IBOutlet weak var zipButton: UIButton! @IBOutlet weak var unzipButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var file1: UILabel! @IBOutlet weak var file2: UILabel! @IBOutlet weak var file3: UILabel! var zipPath: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. file1.text = "" file2.text = "" file3.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: IBAction @IBAction func zipPressed(_: UIButton) { let sampleDataPath = Bundle.main.bundleURL.appendingPathComponent("Sample Data").path zipPath = tempZipPath() let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: sampleDataPath) if success { unzipButton.isEnabled = true zipButton.isEnabled = false } } @IBAction func unzipPressed(_: UIButton) { guard let zipPath = self.zipPath else { return } guard let unzipPath = tempUnzipPath() else { return } let success = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath) if !success { return } var items: [String] do { items = try FileManager.default.contentsOfDirectory(atPath: unzipPath) } catch { return } for (index, item) in items.enumerated() { switch index { case 0: file1.text = item case 1: file2.text = item case 2: file3.text = item default: print("Went beyond index of assumed files") } } unzipButton.isEnabled = false resetButton.isEnabled = true } @IBAction func resetPressed(_: UIButton) { file1.text = "" file2.text = "" file3.text = "" zipButton.isEnabled = true unzipButton.isEnabled = false resetButton.isEnabled = false } // MARK: Private func tempZipPath() -> String { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString).zip" return path } func tempUnzipPath() -> String? { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString)" let url = URL(fileURLWithPath: path) do { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { return nil } return url.path } }
84108892ce4865eddbb08ffbb38d458f
24.095238
112
0.582543
false
false
false
false
festrs/Plantinfo
refs/heads/master
PlantInfo/CoreDataTableViewController.swift
mit
1
// // CoreDataTableViewController.swift // IBoleto-Project // // Created by Felipe Dias Pereira on 2016-02-27. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit import CoreData class CoreDataTableViewController: UIViewController, CoreDataTableViewControllerProtocol, UITableViewDelegate { var coreDataTableView:UITableView! var _fetchedResultsController:NSFetchedResultsController? var fetchedResultsController:NSFetchedResultsController?{ get { return _fetchedResultsController } set (newValue){ _fetchedResultsController = newValue if self.coreDataTableView != nil { self.performFetch() } } } func performFetch(){ do{ try self.fetchedResultsController!.performFetch() coreDataTableView.reloadData() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } // MARK: - Table view data source func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") return cell! } func numberOfSectionsInTableView(tableView: UITableView) -> Int { if (self.fetchedResultsController!.sections != nil){ return (self.fetchedResultsController!.sections?.count)! } return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController!.sections { let currentSection = sections[section] return currentSection.numberOfObjects } return 0 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sections = fetchedResultsController!.sections { let currentSection = sections[section] return currentSection.name } return nil } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return self.fetchedResultsController!.sectionForSectionIndexTitle(title, atIndex: index) } // func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { // return self.fetchedResultsController.sectionIndexTitles // } //MARK - NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { self.coreDataTableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch(type){ case .Insert: self.coreDataTableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) break case .Delete: self.coreDataTableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) break default: break } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type{ case .Insert: self.coreDataTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) break case .Delete: self.coreDataTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) break case .Update: self.coreDataTableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) break case .Move: self.coreDataTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade) self.coreDataTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade) break } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.coreDataTableView.endUpdates() } }
bb5199ce6ae3e84ea2fc661d88334c95
37.405172
211
0.678339
false
false
false
false
mixalich7b/SwiftTBot
refs/heads/master
Pods/ObjectMapper/Sources/Mapper.swift
gpl-3.0
1
// // Mapper.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public enum MappingType { case fromJSON case toJSON } /// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects public final class Mapper<N: BaseMappable> { public var context: MapContext? public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){ self.context = context self.shouldIncludeNilValues = shouldIncludeNilValues } // MARK: Mapping functions that map to an existing object toObject /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is public func map(JSONObject: Any?, toObject object: N) -> N { if let JSON = JSONObject as? [String: Any] { return map(JSON: JSON, toObject: object) } return object } /// Map a JSON string onto an existing object public func map(JSONString: String, toObject object: N) -> N { if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { return map(JSON: JSON, toObject: object) } return object } /// Maps a JSON dictionary to an existing object that conforms to Mappable. /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject public func map(JSON: [String: Any], toObject object: N) -> N { var mutableObject = object let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues) mutableObject.mapping(map: map) return mutableObject } //MARK: Mapping functions that create an object /// Map a JSON string to an object that conforms to Mappable public func map(JSONString: String) -> N? { if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { return map(JSON: JSON) } return nil } /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. public func map(JSONObject: Any?) -> N? { if let JSON = JSONObject as? [String: Any] { return map(JSON: JSON) } return nil } /// Maps a JSON dictionary to an object that conforms to Mappable public func map(JSON: [String: Any]) -> N? { let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable if var object = klass.objectForMapping(map: map) as? N { object.mapping(map: map) return object } } else if let klass = N.self as? Mappable.Type { // Check if object is Mappable if var object = klass.init(map: map) as? N { object.mapping(map: map) return object } } else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable do { return try klass.init(map: map) as? N } catch let error { #if DEBUG #if os(Linux) if let mapError = error as? MapError { assert(false, "MapError\n\(mapError.description)") } else { assert(false, "ImmutableMappableError\n\(error.localizedDescription)") } #else let exception: NSException if let mapError = error as? MapError { exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil) } else { exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil) } exception.raise() #endif #endif } } else { // Ensure BaseMappable is not implemented directly assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable") } return nil } // MARK: Mapping functions for Arrays and Dictionaries /// Maps a JSON array to an object that conforms to Mappable public func mapArray(JSONString: String) -> [N]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) if let objectArray = mapArray(JSONObject: parsedJSON) { return objectArray } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(JSONObject: parsedJSON) { return [object] } return nil } /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapArray(JSONObject: Any?) -> [N]? { if let JSONArray = JSONObject as? [[String: Any]] { return mapArray(JSONArray: JSONArray) } return nil } /// Maps an array of JSON dictionary to an array of Mappable objects public func mapArray(JSONArray: [[String: Any]]) -> [N] { // map every element in JSON array to type N #if swift(>=4.1) let result = JSONArray.compactMap(map) #else let result = JSONArray.flatMap(map) #endif return result } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONString: String) -> [String: N]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) return mapDictionary(JSONObject: parsedJSON) } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONObject: Any?) -> [String: N]? { if let JSON = JSONObject as? [String: [String: Any]] { return mapDictionary(JSON: JSON) } return nil } /// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? { // map every value in dictionary to type N let result = JSON.filterMap(map) if result.isEmpty == false { return result } return nil } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] { if let JSON = JSONObject as? [String : [String : Any]] { return mapDictionary(JSON: JSON, toDictionary: dictionary) } return dictionary } /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] { var mutableDictionary = dictionary for (key, value) in JSON { if let object = dictionary[key] { _ = map(JSON: value, toObject: object) } else { mutableDictionary[key] = map(JSON: value) } } return mutableDictionary } /// Maps a JSON object to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? { if let JSON = JSONObject as? [String: [[String: Any]]] { return mapDictionaryOfArrays(JSON: JSON) } return nil } ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? { // map every value in dictionary to type N let result = JSON.filterMap { mapArray(JSONArray: $0) } if result.isEmpty == false { return result } return nil } /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? { if let JSONArray = JSONObject as? [[[String: Any]]] { var objectArray = [[N]]() for innerJSONArray in JSONArray { let array = mapArray(JSONArray: innerJSONArray) objectArray.append(array) } if objectArray.isEmpty == false { return objectArray } } return nil } // MARK: Utility functions for converting strings to JSON objects /// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) return parsedJSON as? [String: Any] } /// Convert a JSON String into an Object using NSJSONSerialization public static func parseJSONString(JSONString: String) -> Any? { let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) if let data = data { let parsedJSON: Any? do { parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON } return nil } } extension Mapper { // MARK: Functions that create model from JSON file /// JSON file to Mappable object /// - parameter JSONfile: Filename /// - Returns: Mappable object public func map(JSONfile: String) -> N? { if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { do { let JSONString = try String(contentsOfFile: path) do { return self.map(JSONString: JSONString) } } catch { return nil } } return nil } /// JSON file to Mappable object array /// - parameter JSONfile: Filename /// - Returns: Mappable object array public func mapArray(JSONfile: String) -> [N]? { if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { do { let JSONString = try String(contentsOfFile: path) do { return self.mapArray(JSONString: JSONString) } } catch { return nil } } return nil } } extension Mapper { // MARK: Functions that create JSON from objects ///Maps an object that conforms to Mappable to a JSON dictionary <String, Any> public func toJSON(_ object: N) -> [String: Any] { var mutableObject = object let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues) mutableObject.mapping(map: map) return map.JSON } ///Maps an array of Objects to an array of JSON dictionaries [[String: Any]] public func toJSONArray(_ array: [N]) -> [[String: Any]] { return array.map { // convert every element in array to JSON dictionary equivalent self.toJSON($0) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { return dictionary.map { (arg: (key: String, value: N)) in // convert every value in dictionary to its JSON dictionary equivalent return (arg.key, self.toJSON(arg.value)) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { return dictionary.map { (arg: (key: String, value: [N])) in // convert every value (array) in dictionary to its JSON dictionary equivalent return (arg.key, self.toJSONArray(arg.value)) } } /// Maps an Object to a JSON string with option of pretty formatting public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? { let JSONDict = toJSON(object) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } /// Maps an array of Objects to a JSON string with option of pretty formatting public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? { let JSONDict = toJSONArray(array) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } /// Converts an Object to a JSON string with option of pretty formatting public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? { let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] if let JSON = Mapper.toJSONData(JSONObject, options: options) { return String(data: JSON, encoding: String.Encoding.utf8) } return nil } /// Converts an Object to JSON data with options public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? { if JSONSerialization.isValidJSONObject(JSONObject) { let JSONData: Data? do { JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options) } catch let error { print(error) JSONData = nil } return JSONData } return nil } } extension Mapper where N: Hashable { /// Maps a JSON array to an object that conforms to Mappable public func mapSet(JSONString: String) -> Set<N>? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) if let objectArray = mapArray(JSONObject: parsedJSON) { return Set(objectArray) } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(JSONObject: parsedJSON) { return Set([object]) } return nil } /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapSet(JSONObject: Any?) -> Set<N>? { if let JSONArray = JSONObject as? [[String: Any]] { return mapSet(JSONArray: JSONArray) } return nil } /// Maps an Set of JSON dictionary to an array of Mappable objects public func mapSet(JSONArray: [[String: Any]]) -> Set<N> { // map every element in JSON array to type N #if swift(>=4.1) return Set(JSONArray.compactMap(map)) #else return Set(JSONArray.flatMap(map)) #endif } ///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]] public func toJSONSet(_ set: Set<N>) -> [[String: Any]] { return set.map { // convert every element in set to JSON dictionary equivalent self.toJSON($0) } } /// Maps a set of Objects to a JSON string with option of pretty formatting public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? { let JSONDict = toJSONSet(set) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } } extension Dictionary { internal func map<K, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { var mapped = [K: V]() for element in self { let newElement = try f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func map<K, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { var mapped = [K: [V]]() for element in self { let newElement = try f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] { var mapped = [Key: U]() for (key, value) in self { if let newValue = try f(value) { mapped[key] = newValue } } return mapped } }
95c4eda88f55d0c4993072fadaabd7fd
31.078
145
0.693435
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNM Text Editor/DNM Text Editor/SyntaxHighlighter.swift
gpl-2.0
1
// // SyntaxHighlighter.swift // DNMIDE // // Created by James Bean on 11/13/15. // Copyright © 2015 James Bean. All rights reserved. // import Cocoa import DNMModel public class SyntaxHighlighter { public init() { } public class StyleSheet { class var sharedInstance: JSON { struct Static { static let instance: JSON = Static.getInstance() static func getInstance() -> JSON { let bundle = NSBundle(forClass: StyleSheet.self) let filePath = bundle.pathForResource("SyntaxHighlightingStyleSheet", ofType: "json" )! let jsonData = NSData(contentsOfFile: filePath)! let jsonObj: JSON = JSON(data: jsonData) return jsonObj } } return Static.instance } } }
350a24492c67ce16968c7747e8389466
25.771429
89
0.521878
false
false
false
false
rapthi/GT6TuneAssistant
refs/heads/master
GT6TuneAssistant/GT6TuneAssistant/RealmData/TuneValue.swift
mit
1
// // TuneValue.swift // GT6TuneAssistant // // Created by Thierry Rapillard on 12/11/14. // Copyright (c) 2014 Quantesys. All rights reserved. // import Foundation import Realm class TuneValue: RLMObject { // {{{ Constructos override init() { self.tuneParam = TuneParam() super.init() } init(tuneParam: TuneParam) { self.tuneParam = tuneParam; super.init() } // }}} func ignoredProperties() -> NSArray { return [ self.customEntryExitBalanceAverage!, self.customRideHeightPercentageOfRange!, self.customSpringRatePercentageOfRange!, self.customBaseSpringRateValue!, self.customBaseDamperValue!, self.customBaseAntirollBarValue!, self.customWeightPowerRatio!, self.customHorsePowerTorqueRatio!, self.customWeightPowerSpread!, self.customPowerBandSpread!, self.customTotalSpread!, self.customCorrectedPower!, self.customCorrectedTorque!, self.customCorrectedWeightDistribution!, self.customWeightPowerBrakeEven!, self.customWeightPowerMin!, self.customWeightPowerMax!, self.customHorsePowerTorqueBreakEven!, self.customHorsePowerTorqueMin!, self.customHorsePowerTorqueMax!, self.customDriveTrainFactor!, self.customPowerWeightFactor!, self.customPowerBandFactor! ]; } // {{{ ivar // {{{ public vars dynamic var tuneParam: TuneParam dynamic var entryExitBalanceAverage: Int { get { return self.customEntryExitBalanceAverage ?? self.tuneParam.entryExitBalanceAverage } set { self.customEntryExitBalanceAverage = newValue } } dynamic var rideHeightPercentageOfRange: Double { get { return self.customRideHeightPercentageOfRange ?? self.tuneParam.rideHeightPercentageOfRange } set { self.customRideHeightPercentageOfRange = newValue } } dynamic var springRatePercentageOfRange: Double { get { return self.customSpringRatePercentageOfRange ?? self.tuneParam.springRatePercentageOfRange } set { self.customSpringRatePercentageOfRange = newValue } } dynamic var baseSpringRateValue: Double { get { return self.customBaseSpringRateValue ?? self.tuneParam.baseSpringRateValue } set { self.customBaseSpringRateValue = newValue } } dynamic var baseDamperValue: Int { get { return self.customBaseDamperValue ?? self.tuneParam.baseDamperValue } set { self.customBaseDamperValue = newValue } } dynamic var baseAntirollBarValue: Int { get { return self.customBaseAntirollBarValue ?? self.tuneParam.baseAntirollBarValue } set { self.customBaseAntirollBarValue = newValue } } dynamic var weightPowerRatio: Double { get { return self.customWeightPowerRatio ?? self.tuneParam.weightPowerRatio } set { self.customWeightPowerRatio = newValue } } dynamic var horsePowerTorqueRatio: Double { get { return self.customHorsePowerTorqueRatio ?? self.tuneParam.horsePowerTorqueRatio } set { self.customHorsePowerTorqueRatio = newValue } } dynamic var weightPowerSpread: Double { get { return self.customWeightPowerSpread ?? self.tuneParam.weightPowerSpread } set { self.customWeightPowerSpread = newValue } } dynamic var powerBandSpread: Double { get { return self.customPowerBandSpread ?? self.tuneParam.powerBandSpread } set { self.customPowerBandSpread = newValue } } dynamic var totalSpread: Double { get { return self.customTotalSpread ?? self.tuneParam.totalSpread } set { self.customTotalSpread = newValue } } dynamic var correctedPower: Double { get { return self.customCorrectedPower ?? self.tuneParam.correctedPower } set { self.customCorrectedPower = newValue } } dynamic var correctedTorque: Double { get { return self.customCorrectedTorque ?? self.tuneParam.correctedTorque } set { self.customCorrectedTorque = newValue } } dynamic var correctedWeightDistribution: Double { get { return self.customCorrectedWeightDistribution ?? self.tuneParam.correctedWeightDistribution } set { self.customCorrectedWeightDistribution = newValue } } dynamic var weightPowerBrakeEven: Double { get { return self.customWeightPowerBrakeEven ?? self.tuneParam.weightPowerBrakeEven } set { self.customWeightPowerBrakeEven = newValue } } dynamic var weightPowerMin: Double { get { return self.customWeightPowerMin ?? self.tuneParam.weightPowerMin } set { self.customWeightPowerMin = newValue } } dynamic var weightPowerMax: Double { get { return self.customWeightPowerMax ?? self.tuneParam.weightPowerMax } set { self.customWeightPowerMax = newValue } } dynamic var horsePowerTorqueBreakEven: Double { get { return self.customHorsePowerTorqueBreakEven ?? self.tuneParam.horsePowerTorqueBreakEven } set { self.customHorsePowerTorqueBreakEven = newValue } } dynamic var horsePowerTorqueMin: Double { get { return self.customHorsePowerTorqueMin ?? self.tuneParam.horsePowerTorqueMin } set { self.customHorsePowerTorqueMin = newValue } } dynamic var horsePowerTorqueMax: Double { get { return self.customHorsePowerTorqueMax ?? self.tuneParam.horsePowerTorqueMax } set { self.customHorsePowerTorqueMax = newValue } } dynamic var driveTrainFactor: Double { get { return self.customDriveTrainFactor ?? self.tuneParam.driveTrainFactor } set { self.customDriveTrainFactor = newValue } } dynamic var powerWeightFactor: Double { get { return self.customPowerWeightFactor ?? self.tuneParam.powerWeightFactor } set { self.customPowerWeightFactor = newValue } } dynamic var powerBandFactor: Double { get { return self.customPowerBandFactor ?? self.tuneParam.powerBandFactor } set { self.customPowerBandFactor = newValue } } // }}} // {{{ private vars private var customEntryExitBalanceAverage: Int? private var customRideHeightPercentageOfRange: Double? private var customSpringRatePercentageOfRange: Double? private var customBaseSpringRateValue: Double? private var customBaseDamperValue: Int? private var customBaseAntirollBarValue: Int? private var customWeightPowerRatio: Double? private var customHorsePowerTorqueRatio: Double? private var customWeightPowerSpread: Double? private var customPowerBandSpread: Double? private var customTotalSpread: Double? private var customCorrectedPower: Double? private var customCorrectedTorque: Double? private var customCorrectedWeightDistribution: Double? private var customWeightPowerBrakeEven: Double? private var customWeightPowerMin: Double? private var customWeightPowerMax: Double? private var customHorsePowerTorqueBreakEven: Double? private var customHorsePowerTorqueMin: Double? private var customHorsePowerTorqueMax: Double? private var customDriveTrainFactor: Double? private var customPowerWeightFactor: Double? private var customPowerBandFactor: Double? // }}} // }}} }
899fe95eb5e3a767b1b0708df481c41f
29.973684
103
0.632116
false
false
false
false
zambelz48/swift-sample-dependency-injection
refs/heads/master
SampleDITests/MockObjects/UserModelMock.swift
mit
1
// // UserModelMock.swift // SampleDI // // Created by Nanda Julianda Akbar on 8/23/17. // Copyright © 2017 Nanda Julianda Akbar. All rights reserved. // import Foundation import RxSwift @testable import SampleDI final class UserModelMock: UserModelProtocol { // MARK: Private properties private let disposeBag = DisposeBag() private let userStorageMock = UserStorageMock() private let userDataSuccessfullyChangedSubject = PublishSubject<Void>() private let userDataFailChangedSubject = PublishSubject<NSError>() // MARK: Public properties var userDataSuccessfullyChangedObservable: Observable<Void> { return userDataSuccessfullyChangedSubject.asObservable() } var userDataFailChangedObservable: Observable<NSError> { return userDataFailChangedSubject.asObservable() } var userData: User { guard let userData = userStorageMock.getData() as? NSDictionary else { return User() } return User(dictionary: userData) } var isAlreadyLoggedIn: Bool { return !userData.name.isEmpty } init() { configureDataChangesObservable() } // MARK: Private methods private func configureDataChangesObservable() { userStorageMock.dataChangesResultObservable .subscribe(onNext: { [weak self] isSuccess in guard !isSuccess else { self?.userDataSuccessfullyChangedSubject.onNext() return } let error: NSError = NSError( domain: "SampleDI", code: -4, userInfo: [ NSLocalizedDescriptionKey : "Failed to change user data in storage !" ] ) self?.userDataFailChangedSubject.onNext(error) }) .disposed(by: disposeBag) } // MARK: Public methods func storeUserData(with user: User) { userStorageMock.save(data: user) } func clearUserData() { userStorageMock.remove(with: "") } }
9edab95287ae4bd88b8485d75bbcf766
21.197531
88
0.72525
false
false
false
false
Eliothu/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingDetailsViewController.swift
gpl-2.0
5
import Foundation /** * @class NotificationSettingDetailsViewController * @brief The purpose of this class is to render a collection of NotificationSettings for a given * Stream, encapsulated in the class NotificationSettings.Stream, and to provide the user * a simple interface to update those settings, as needed. */ public class NotificationSettingDetailsViewController : UITableViewController { // MARK: - Initializers public convenience init(settings: NotificationSettings) { self.init(settings: settings, stream: settings.streams.first!) } public convenience init(settings: NotificationSettings, stream: NotificationSettings.Stream) { self.init(style: .Grouped) self.settings = settings self.stream = stream } // MARK: - View Lifecycle public override func viewDidLoad() { super.viewDidLoad() setupTitle() setupNotifications() setupTableView() reloadTable() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) WPAnalytics.track(.OpenedNotificationSettingDetails) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) saveSettingsIfNeeded() } // MARK: - Setup Helpers private func setupTitle() { switch settings!.channel { case .WordPressCom: title = NSLocalizedString("WordPress.com Updates", comment: "WordPress.com Notification Settings Title") default: title = stream!.kind.description() } } private func setupNotifications() { // Reload whenever the app becomes active again since Push Settings may have changed in the meantime! let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "reloadTable", name: UIApplicationDidBecomeActiveNotification, object: nil) } private func setupTableView() { // Register the cells tableView.registerClass(SwitchTableViewCell.self, forCellReuseIdentifier: Row.Kind.Setting.rawValue) tableView.registerClass(WPTableViewCell.self, forCellReuseIdentifier: Row.Kind.Text.rawValue) // Hide the separators, whenever the table is empty tableView.tableFooterView = UIView() // Style! WPStyleGuide.configureColorsForView(view, andTableView: tableView) } @IBAction private func reloadTable() { sections = isDeviceStreamDisabled() ? sectionsForDisabledDeviceStream() : sectionsForSettings(settings!, stream: stream!) tableView.reloadData() } // MARK: - Private Helpers private func sectionsForSettings(settings: NotificationSettings, stream: NotificationSettings.Stream) -> [Section] { // WordPress.com Channel requires a brief description per row. // For that reason, we'll render each row in its own section, with it's very own footer let singleSectionMode = settings.channel != .WordPressCom // Parse the Rows var rows = [Row]() for key in settings.sortedPreferenceKeys(stream) { let description = settings.localizedDescription(key) let value = stream.preferences?[key] ?? true let row = Row(kind: .Setting, description: description, key: key, value: value) rows.append(row) } // Single Section Mode: A single section will contain all of the rows if singleSectionMode { return [Section(rows: rows)] } // Multi Section Mode: We'll have one Section per Row var sections = [Section]() for row in rows { let unwrappedKey = row.key ?? String() let details = settings.localizedDetails(unwrappedKey) let section = Section(rows: [row], footerText: details) sections.append(section) } return sections } private func sectionsForDisabledDeviceStream() -> [Section] { let description = NSLocalizedString("Go to iPhone Settings", comment: "Opens WPiOS Settings.app Section") let row = Row(kind: .Text, description: description, key: nil, value: nil) let footerText = NSLocalizedString("Push Notifications have been turned off in iOS Settings App. " + "Toggle \"Allow Notifications\" to turn them back on.", comment: "Suggests to enable Push Notification Settings in Settings.app") let section = Section(rows: [row], footerText: footerText) return [section] } // MARK: - UITableView Delegate Methods public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = sections[indexPath.section] let row = section.rows[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(row.kind.rawValue) switch row.kind { case .Text: configureTextCell(cell as! WPTableViewCell, row: row) case .Setting: configureSwitchCell(cell as! SwitchTableViewCell, row: row) } return cell! } public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let footerText = sections[section].footerText { return WPTableViewSectionHeaderFooterView.heightForFooter(footerText, width: view.bounds.width) } return CGFloat.min } public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if let footerText = sections[section].footerText { let footerView = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer) footerView.title = footerText return footerView } return nil } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectSelectedRowWithAnimation(true) if isDeviceStreamDisabled() { openApplicationSettings() } } // MARK: - UITableView Helpers private func configureTextCell(cell: WPTableViewCell, row: Row) { cell.textLabel?.text = row.description WPStyleGuide.configureTableViewCell(cell) } private func configureSwitchCell(cell: SwitchTableViewCell, row: Row) { let settingKey = row.key ?? String() cell.name = row.description cell.on = newValues[settingKey] ?? (row.value ?? true) cell.onChange = { [weak self] (newValue: Bool) in self?.newValues[settingKey] = newValue } } // MARK: - Disabled Push Notifications Handling private func isDeviceStreamDisabled() -> Bool { return stream?.kind == .Device && !NotificationsManager.pushNotificationsEnabledInDeviceSettings() } private func openApplicationSettings() { if #available(iOS 8.0, *) { let targetURL = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(targetURL!) } } // MARK: - Service Helpers private func saveSettingsIfNeeded() { if newValues.count == 0 || settings == nil { return } let context = ContextManager.sharedInstance().mainContext let service = NotificationsService(managedObjectContext: context) service.updateSettings(settings!, stream : stream!, newValues : newValues, success : { WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : true]) }, failure : { (error: NSError!) in WPAnalytics.track(.NotificationsSettingsUpdated, withProperties: ["success" : false]) self.handleUpdateError() }) } private func handleUpdateError() { UIAlertView.showWithTitle(NSLocalizedString("Oops!", comment: ""), message : NSLocalizedString("There has been an unexpected error while updating " + "your Notification Settings", comment: "Displayed after a failed Notification Settings call"), style : .Default, cancelButtonTitle : NSLocalizedString("Cancel", comment: "Cancel. Action."), otherButtonTitles : [ NSLocalizedString("Retry", comment: "Retry. Action") ], tapBlock : { (alertView: UIAlertView!, buttonIndex: Int) -> Void in if alertView.cancelButtonIndex == buttonIndex { return } self.saveSettingsIfNeeded() }) } // MARK: - Private Nested Class'ess private class Section { var rows : [Row] var footerText : String? init(rows: [Row], footerText: String? = nil) { self.rows = rows self.footerText = footerText } } private class Row { let description : String let kind : Kind let key : String? let value : Bool? init(kind: Kind, description: String, key: String? = nil, value: Bool? = nil) { self.description = description self.kind = kind self.key = key self.value = value } enum Kind : String { case Setting = "SwitchCell" case Text = "TextCell" } } // MARK: - Private Properties private var settings : NotificationSettings? private var stream : NotificationSettings.Stream? // MARK: - Helpers private var sections = [Section]() private var newValues = [String: Bool]() }
11bff773d1ba18b7f5d33392934e00c6
35.996633
129
0.587459
false
false
false
false
montionugera/yellow
refs/heads/master
yellow-ios/yellow/CustomUI/TopCurveFloatingView.swift
mit
1
// // FloatingView.swift // YellowModule // // Created by Nattapong Unaregul on 9/10/17. // Copyright © 2017 Nattapong Unaregul. All rights reserved. // import UIKit @IBDesignable class TopCurveFloatingView : UIView { private let beginingYPoint : CGFloat = 40 lazy var maskLayer = CAShapeLayer() lazy var maskPath : UIBezierPath = { let b = UIBezierPath() return b }() @IBInspectable var topCurveColor : UIColor = UIColor.black { didSet{ topEdgeCurveLayer.strokeColor = topCurveColor.cgColor } } lazy var topEdgeCurveLayer : CAShapeLayer = { let c = CAShapeLayer() c.fillColor = UIColor.clear.cgColor c.lineWidth = 7.0 c.lineCap = kCALineCapRound return c }() override init(frame: CGRect) { super.init(frame: frame) sharedInitilization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInitilization() } func sharedInitilization() { topEdgeCurveLayer.strokeColor = topCurveColor.cgColor self.layer.mask = maskLayer self.layer.addSublayer(topEdgeCurveLayer) } func buildCurveOnTop(isStrokeLine : Bool = false) -> UIBezierPath { let b = UIBezierPath() let ratio : CGFloat = 3.5/4 let additionalPlus : CGFloat = isStrokeLine == true ? 0 : 0 b.move(to: CGPoint(x: 0 + (additionalPlus * -1) , y: beginingYPoint)) b.addQuadCurve(to: CGPoint(x: self.bounds.width / 2 , y: 0) , controlPoint: CGPoint(x: self.bounds.width * (1 - ratio) , y: 0)) b.addQuadCurve(to: CGPoint(x: self.bounds.width + additionalPlus , y: beginingYPoint) , controlPoint: CGPoint(x: self.bounds.width * ratio, y: 0)) return b } override func layoutSubviews() { super.layoutSubviews() topEdgeCurveLayer.path = buildCurveOnTop(isStrokeLine: true).cgPath maskPath.append(buildCurveOnTop()) maskPath.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height)) maskPath.addLine(to: CGPoint(x: 0, y: self.bounds.height)) maskPath.close() maskLayer.path = maskPath.cgPath } lazy var centerBound : CGPoint = CGPoint(x: self.bounds.width / 2 , y: self.bounds.height / 2) override func draw(_ rect: CGRect) { super.draw(rect) let centerLinePath = UIBezierPath() let centerRect = CGPoint(x: rect.width / 2 , y: rect.height / 2) let size : CGFloat = rect.width * 0.15 centerLinePath.move(to: CGPoint(x: centerRect.x - size / 2 , y: 20 )) centerLinePath.addLine(to: CGPoint(x: centerRect.x + size / 2 , y: 20 )) centerLinePath.lineWidth = 5 UIColor.black.setStroke() centerLinePath.stroke() } }
06973cc4c84b05bd9e1a850188a277e1
35.87013
100
0.62522
false
false
false
false