repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
XCEssentials/ProjectGenerator
Sources/Spec/Spec.1.2.1.swift
1
15409
import Foundation //=== enum Spec_1_2_1 { static func generate(for p: Project) -> RawSpec { var result: RawSpec = [] var idention: Int = 0 //=== result <<< (idention, "# generated with MKHProjGen") result <<< (idention, "# https://github.com/maximkhatskevich/MKHProjGen") //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#version-number result <<< (idention, Spec.key("version") + " \(Spec.Format.v1_2_1.rawValue)") //=== result <<< process(&idention, p.configurations) //=== result <<< process(&idention, p.targets) //=== result <<< (idention, Spec.key("variants")) idention += 1 result <<< (idention, Spec.key("$base")) idention += 1 result <<< (idention, Spec.key("abstract") + " true") idention -= 1 result <<< (idention, Spec.key(p.name)) idention -= 1 //=== result <<< (0, "") // empty line in the EOF //=== return result } //=== static func process( _ idention: inout Int, _ set: Project.BuildConfigurations ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#configurations //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key("configurations")) //=== idention += 1 //=== result <<< process(&idention, set.all, set.debug) result <<< process(&idention, set.all, set.release) //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, _ b: Project.BuildConfiguration.Base, _ c: Project.BuildConfiguration ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#configurations //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key(c.name)) //=== idention += 1 //=== result <<< (idention, Spec.key("type") + Spec.value(c.type)) //=== if let externalConfig = c.externalConfig { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#xcconfig-references // NOTE: when using xcconfig files, // any overrides or profiles will be ignored. result <<< (idention, Spec.key("source") + Spec.value(externalConfig) ) } else { // NO source/xcconfig provided //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#profiles result <<< (idention, Spec.key("profiles")) for p in b.profiles + c.profiles { result <<< (idention, "-" + Spec.value(p)) } //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#overrides result <<< (idention, Spec.key("overrides")) idention += 1 for o in b.overrides + c.overrides { result <<< (idention, Spec.key(o.key) + Spec.value(o.value)) } idention -= 1 } //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, _ targets: [Project.Target] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#targets //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key("targets")) //=== idention += 1 //=== for t in targets { result <<< process(&idention, t) //=== for tst in t.tests { result <<< process(&idention, tst) } } //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, _ t: Project.Target ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#targets //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key(t.name)) //=== idention += 1 //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#platform result <<< (idention, Spec.key("platform") + Spec.value(t.platform.rawValue)) //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#type result <<< (idention, Spec.key("type") + Spec.value(t.type.rawValue)) //=== result <<< process(&idention, t.dependencies) //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#sources if !t.includes.isEmpty { result <<< (idention, "sources:") for path in t.includes { result <<< (idention, "-" + Spec.value(path)) } } //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#excludes if !t.excludes.isEmpty { result <<< (idention, Spec.key("excludes")) idention += 1 result <<< (idention, Spec.key("files")) for path in t.excludes { result <<< (idention, "-" + Spec.value(path)) } idention -= 1 } //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#i18n-resources if !t.i18nResources.isEmpty { result <<< (idention, Spec.key("i18n-resources")) for path in t.i18nResources { result <<< (idention, "-" + Spec.value(path)) } } //=== result <<< process(&idention, t.configurations) //=== result <<< process(&idention, scripts: t.scripts) //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#cocoapods if t.includeCocoapods { result <<< (idention, Spec.key("includes_cocoapods") + Spec.value(t.includeCocoapods)) } //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, _ deps: Project.Target.Dependencies ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#references //=== var result: RawSpec = [] //=== if !deps.fromSDKs.isEmpty || !deps.otherTargets.isEmpty || !deps.binaries.isEmpty || !deps.projects.isEmpty { result <<< (idention, Spec.key("references")) //=== result <<< processDependencies(&idention, fromSDK: deps.fromSDKs) result <<< processDependencies(&idention, targets: deps.otherTargets) result <<< processDependencies(&idention, binaries: deps.binaries) result <<< processDependencies(&idention, projects: deps.projects) } //=== return result } //=== static func processDependencies( _ idention: inout Int, fromSDK: [String] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#references //=== var result: RawSpec = [] //=== for dep in fromSDK { result <<< (idention, "-" + Spec.value("sdkroot:\(dep)")) } //=== return result } //=== static func processDependencies( _ idention: inout Int, targets: [String] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#references //=== var result: RawSpec = [] //=== for t in targets { result <<< (idention, "-" + Spec.value(t)) } //=== return result } //=== static func processDependencies( _ idention: inout Int, binaries: [Project.Target.BinaryDependency] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#references //=== var result: RawSpec = [] //=== for b in binaries { result <<< (idention, Spec.key("- location") + Spec.value(b.location)) result <<< (idention, Spec.key(" codeSignOnCopy") + Spec.value(b.codeSignOnCopy)) } //=== return result } //=== static func processDependencies( _ idention: inout Int, projects: [Project.Target.ProjectDependencies] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#references //=== var result: RawSpec = [] //=== for p in projects { result <<< (idention, Spec.key("- location") + Spec.value(p.location)) result <<< (idention, Spec.key(" frameworks")) for f in p.frameworks { result <<< (idention, Spec.key(" - name") + Spec.value(f.name)) result <<< (idention, Spec.key(" copy") + Spec.value(f.copy)) result <<< (idention, Spec.key(" codeSignOnCopy") + Spec.value(f.codeSignOnCopy)) } } //=== return result } //=== static func process( _ idention: inout Int, _ set: Project.Target.BuildConfigurations ) -> RawSpec { // https://github.com/lyptt/struct/issues/77#issuecomment-287573381 //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key("configurations")) //=== idention += 1 //=== result <<< process(&idention, set.all, set.debug) result <<< process(&idention, set.all, set.release) //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, _ b: Project.Target.BuildConfiguration.Base, _ c: Project.Target.BuildConfiguration ) -> RawSpec { // https://github.com/lyptt/struct/issues/77#issuecomment-287573381 //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key(c.name)) //=== idention += 1 //=== // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#overrides for o in b.overrides + c.overrides { result <<< (idention, Spec.key(o.key) + Spec.value(o.value)) } //=== idention -= 1 //=== return result } //=== static func process( _ idention: inout Int, scripts: Project.Target.Scripts ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#scripts //=== var result: RawSpec = [] //=== if !scripts.regulars.isEmpty || !scripts.beforeBuilds.isEmpty || !scripts.afterBuilds.isEmpty { result <<< (idention, Spec.key("scripts")) //=== idention += 1 //=== if !scripts.regulars.isEmpty { result <<< processScripts(&idention, regulars: scripts.regulars) } if !scripts.beforeBuilds.isEmpty { result <<< processScripts(&idention, beforeBuild: scripts.beforeBuilds) } if !scripts.afterBuilds.isEmpty { result <<< processScripts(&idention, afterBuild: scripts.afterBuilds) } //=== idention -= 1 } //=== return result } //=== static func processScripts( _ idention: inout Int, regulars: [String] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#scripts //=== var result: RawSpec = [] //=== for s in regulars { result <<< (idention, "-" + Spec.value(s)) } //=== return result } //=== static func processScripts( _ idention: inout Int, beforeBuild: [String] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#scripts //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key("prebuild")) for s in beforeBuild { result <<< (idention, "-" + Spec.value(s)) } //=== return result } //=== static func processScripts( _ idention: inout Int, afterBuild: [String] ) -> RawSpec { // https://github.com/lyptt/struct/wiki/Spec-format:-v1.2#scripts //=== var result: RawSpec = [] //=== result <<< (idention, Spec.key("postbuild")) for s in afterBuild { result <<< (idention, "-" + Spec.value(s)) } //=== return result } }
mit
218b1cfc2a1a68155bf9efe8de973b6b
21.044349
100
0.405802
4.837991
false
false
false
false
stulevine/firefox-ios
Sync/State.swift
1
13328
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() /* * This file includes types that manage intra-sync and inter-sync metadata * for the use of synchronizers and the state machine. * * See docs/sync.md for details on what exactly we need to persist. */ public struct Fetched<T: Equatable>: Equatable { let value: T let timestamp: Timestamp } public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool { return lhs.timestamp == rhs.timestamp && lhs.value == rhs.value } /* * Persistence pref names. * Note that syncKeyBundle isn't persisted by us. * * Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"), * and we keep a 'label'. This label is used to find the real fetched keys in the Keychain. */ private let PrefVersion = "_v" private let PrefGlobal = "global" private let PrefGlobalTS = "globalTS" private let PrefKeyLabel = "keyLabel" private let PrefKeysTS = "keysTS" private let PrefLastFetched = "lastFetched" private let PrefClientName = "clientName" private let PrefClientLastUpload = "clientLastUpload" /** * The scratchpad consists of the following: * * 1. Cached records. We cache meta/global and crypto/keys until they change. * 2. Metadata like timestamps, both for cached records and for server fetches. * 3. User preferences -- engine enablement. * 4. Client record state. * * Note that the scratchpad itself is immutable, but is a class passed by reference. * Its mutable fields can be mutated, but you can't accidentally e.g., switch out * meta/global and get confused. * * TODO: the Scratchpad needs to be loaded from persistent storage, and written * back at certain points in the state machine (after a replayable action is taken). */ public class Scratchpad { public class Builder { var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too! private var global: Fetched<MetaGlobal>? private var keys: Fetched<Keys>? private var keyLabel: String var collectionLastFetched: [String: Timestamp] var engineConfiguration: EngineConfiguration? var clientRecordLastUpload: Timestamp = 0 var clientName: String var prefs: Prefs init(p: Scratchpad) { self.syncKeyBundle = p.syncKeyBundle self.prefs = p.prefs self.global = p.global self.keys = p.keys self.keyLabel = p.keyLabel self.collectionLastFetched = p.collectionLastFetched self.engineConfiguration = p.engineConfiguration self.clientRecordLastUpload = p.clientRecordLastUpload self.clientName = p.clientName } public func setKeys(keys: Fetched<Keys>?) -> Builder { self.keys = keys if let keys = keys { self.collectionLastFetched["crypto"] = keys.timestamp } return self } public func setGlobal(global: Fetched<MetaGlobal>?) -> Builder { self.global = global if let global = global { self.collectionLastFetched["meta"] = global.timestamp } return self } public func clearFetchTimestamps() -> Builder { self.collectionLastFetched = [:] return self } public func clearClientUploadTimestamp() -> Builder { self.clientRecordLastUpload = 0 return self } public func build() -> Scratchpad { return Scratchpad( b: self.syncKeyBundle, m: self.global, k: self.keys, keyLabel: self.keyLabel, fetches: self.collectionLastFetched, engines: self.engineConfiguration, clientUpload: self.clientRecordLastUpload, clientName: self.clientName, persistingTo: self.prefs ) } } public func evolve() -> Scratchpad.Builder { return Scratchpad.Builder(p: self) } // This is never persisted. let syncKeyBundle: KeyBundle // Cached records. // This cached meta/global is what we use to add or remove enabled engines. See also // engineConfiguration, below. // We also use it to detect when meta/global hasn't changed -- compare timestamps. // // Note that a Scratchpad held by a Ready state will have the current server meta/global // here. That means we don't need to track syncIDs separately (which is how desktop and // Android are implemented). // If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't // synced with this server before, and we'll do a fresh sync. let global: Fetched<MetaGlobal>? // We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs. // Instead, we store a label, which is seeded when you first create a Scratchpad. // This label is used to retrieve the real keys from your Keychain. // // Note that we also don't store the syncKeyBundle here. That's always created from kB, // provided by the Firefox Account. // // Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to // clean up without having your key. Secondly, we don't want to accidentally load keys // from the Keychain just because the Sync Key is the same -- e.g., after a node // reassignment. Randomly generating a label offers all of the benefits with none of the // problems, with only the cost of persisting that label alongside the rest of the state. let keys: Fetched<Keys>? let keyLabel: String // Collection timestamps. var collectionLastFetched: [String: Timestamp] // Enablement states. let engineConfiguration: EngineConfiguration? // When did we last upload our client record? let clientRecordLastUpload: Timestamp // What's our client name? let clientName: String let clientGUID: String = "TODOTODOTODO" // Where do we persist when told? let prefs: Prefs class func defaultClientName() -> String { return "Firefox" // TODO } init(b: KeyBundle, m: Fetched<MetaGlobal>?, k: Fetched<Keys>?, keyLabel: String, fetches: [String: Timestamp], engines: EngineConfiguration?, clientUpload: Timestamp, clientName: String, persistingTo prefs: Prefs ) { self.syncKeyBundle = b self.prefs = prefs self.keys = k self.keyLabel = keyLabel self.global = m self.engineConfiguration = engines self.collectionLastFetched = fetches self.clientRecordLastUpload = clientUpload self.clientName = clientName } // This should never be used in the end; we'll unpickle instead. // This should be a convenience initializer, but... Swift compiler bug? init(b: KeyBundle, persistingTo prefs: Prefs) { self.syncKeyBundle = b self.prefs = prefs self.keys = nil self.keyLabel = Bytes.generateGUID() self.global = nil self.engineConfiguration = nil self.collectionLastFetched = [String: Timestamp]() self.clientRecordLastUpload = 0 self.clientName = Scratchpad.defaultClientName() } // For convenience. func withGlobal(m: Fetched<MetaGlobal>?) -> Scratchpad { return self.evolve().setGlobal(m).build() } func freshStartWithGlobal(global: Fetched<MetaGlobal>) -> Scratchpad { // TODO: I *think* a new keyLabel is unnecessary. return self.evolve() .setGlobal(global) .setKeys(nil) .clearFetchTimestamps() .clearClientUploadTimestamp() .build() } func applyEngineChoices(old: MetaGlobal?) -> (Scratchpad, MetaGlobal?) { log.info("Applying engine choices from inbound meta/global.") log.info("Old meta/global syncID: \(old?.syncID)") log.info("New meta/global syncID: \(self.global?.value.syncID)") log.info("HACK: ignoring engine choices.") // TODO: detect when the sets of declined or enabled engines have changed, and update // our preferences and generate a new meta/global if necessary. return (self, nil) } private class func unpickleV1FromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad { let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve() // Do this first so that the meta/global and crypto/keys unpickling can overwrite the timestamps. if let lastFetched: [String: AnyObject] = prefs.dictionaryForKey(PrefLastFetched) { b.collectionLastFetched = optFilter(mapValues(lastFetched, { ($0 as? NSNumber)?.unsignedLongLongValue })) } if let mg = prefs.stringForKey(PrefGlobal) { if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) { if let global = MetaGlobal.fromPayload(mg) { b.setGlobal(Fetched(value: global, timestamp: mgTS)) } else { log.error("Malformed meta/global in prefs. Ignoring.") } } else { // This should never happen. log.error("Found global in prefs, but not globalTS!") } } if let keyLabel = prefs.stringForKey(PrefKeyLabel) { b.keyLabel = keyLabel if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) { if let keys = KeychainWrapper.stringForKey("keys." + keyLabel) { // We serialize as JSON. let keys = Keys(payload: KeysPayload(keys)) if keys.valid { log.debug("Read keys from Keychain with label \(keyLabel).") b.setKeys(Fetched(value: keys, timestamp: ckTS)) } else { log.error("Invalid keys extracted from Keychain. Discarding.") } } else { log.error("Found keysTS in prefs, but didn't find keys in Keychain!") } } } b.clientName = prefs.stringForKey(PrefClientName) ?? defaultClientName() b.clientRecordLastUpload = prefs.unsignedLongForKey(PrefClientLastUpload) ?? 0 // TODO: engineConfiguration return b.build() } public class func restoreFromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? { if let ver = prefs.intForKey(PrefVersion) { switch (ver) { case 1: return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle) default: return nil } } log.debug("No scratchpad found in prefs.") return nil } /** * Persist our current state to our origin prefs. * Note that calling this from multiple threads with either mutated or evolved * scratchpads will cause sadness — individual writes are thread-safe, but the * overall pseudo-transaction is not atomic. */ public func checkpoint() -> Scratchpad { return pickle(self.prefs) } func pickle(prefs: Prefs) -> Scratchpad { prefs.setInt(1, forKey: PrefVersion) if let global = global { prefs.setLong(global.timestamp, forKey: PrefGlobalTS) prefs.setString(global.value.toPayload().toString(), forKey: PrefGlobal) } else { prefs.removeObjectForKey(PrefGlobal) prefs.removeObjectForKey(PrefGlobalTS) } // We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs. prefs.setString(self.keyLabel, forKey: PrefKeyLabel) if let keys = self.keys { let payload = keys.value.asPayload().toString(pretty: false) let label = "keys." + self.keyLabel log.debug("Storing keys in Keychain with label \(label).") prefs.setString(self.keyLabel, forKey: PrefKeyLabel) prefs.setLong(keys.timestamp, forKey: PrefKeysTS) // TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here. KeychainWrapper.setString(payload, forKey: label) } else { log.debug("Removing keys from Keychain.") KeychainWrapper.removeObjectForKey(self.keyLabel) } // TODO: engineConfiguration prefs.setString(clientName, forKey: PrefClientName) prefs.setLong(clientRecordLastUpload, forKey: PrefClientLastUpload) // Thanks, Swift. let dict = mapValues(collectionLastFetched, { NSNumber(unsignedLongLong: $0) }) as NSDictionary prefs.setObject(dict, forKey: PrefLastFetched) return self } }
mpl-2.0
86e9c316785e8caaaabbbfb0b3834e44
36.327731
117
0.62667
4.865279
false
false
false
false
Kiandr/CrackingCodingInterview
Swift/Ch 10. Sorting and Searching/Ch 10. Sorting and Searching.playground/Pages/10.3 Search in Rotated Array.xcplaygroundpage/Contents.swift
1
1938
import Foundation /*: 10.3 Given a sorted array of n integers that has been rotated an unknown number of times, write code to find the element in the array. You may assume that the array was originally sorted in increasing order. */ extension RandomAccessCollection where Iterator.Element: Comparable, Indices.Iterator.Element == Index { func binarySearchShiftedArray(x: Iterator.Element) -> Index? { guard first! > last! else { return binarySearch(x: x) } guard let minElementIndex = successiveElements (where: { $0 > $1 })?.rightIndex else { return binarySearch(x: x) } let leftIndex = binarySearch(x: x, low: minElementIndex, high: index(before: endIndex)) return leftIndex ?? binarySearch(x: x, low: startIndex, high: index(before: minElementIndex)) } } extension RandomAccessCollection where Iterator.Element: Comparable { func binarySearch(x: Iterator.Element) -> Index? { return binarySearch(x: x, low: startIndex, high: index(before: endIndex)) } func binarySearch(x: Iterator.Element, low: Index, high: Index) -> Index? { guard low <= high else { return nil } let mid = index(low, offsetBy: distance(from: low, to: high) / 2) if self[mid] < x { return binarySearch(x: x, low: index(after: mid), high: high) } else if self[mid] > x { return binarySearch(x: x, low: low, high: index(before: mid)) } else { return mid } } } var a = [15,16,19,20,25,1,3,4,5,7,10,14] a.enumerated().forEach { i, e in for shift in 1..<a.endIndex { let shiftedArray = Array(a[a.endIndex-shift..<a.endIndex]) + Array(a[0..<a.endIndex-shift]) let expectedIndex = i + shift < a.endIndex ? i + shift : i + shift - a.endIndex let result = shiftedArray.binarySearchShiftedArray(x: e) assert(result == expectedIndex, "expected = \(expectedIndex) actual = \(String(describing: result)) element \(e)", file: "") } }
mit
5ba1d2df7b1fe4def1fd0a61a369e86a
34.888889
208
0.668215
3.726923
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/UserInfo/Controller/UserInfoController.swift
1
5766
// // UserInfoController.swift // OpenCode // // Created by 陈亮 on 16/5/18. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit import SwiftyJSON class UserInfoController: UIViewController, UITableViewDataSource,UITableViewDelegate { let USERINFO_CELL_ID = "userInfoCell" var userInfoDate:UserInfo? var tableView:UITableView? var headerView:UserInfoHeaderView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let userInfo = self.userInfoDate{ initView(userInfo) }else{ print("没有获取到数据") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func parseData(data:AnyObject) { self.userInfoDate = UserInfo(data: data) } func initView(userInfo:UserInfo){ self.headerView = UserInfoHeaderView() headerView?.setData(UIImage(data: NSData(contentsOfURL: NSURL(string: userInfo.avatarUrl)!)!)!, name: userInfo.name, followersNum: userInfo.followers, followingNum: userInfo.following) //列表 tableView = UITableView(frame: self.view.bounds, style: .Grouped) tableView?.dataSource = self tableView?.delegate = self tableView?.tableHeaderView = self.headerView self.view.addSubview(self.tableView!) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(self.USERINFO_CELL_ID) if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: self.USERINFO_CELL_ID) cell?.accessoryType = .DisclosureIndicator } switch indexPath.row { case 0: cell?.textLabel?.text = "事件" case 1: cell?.textLabel?.text = "组织" case 2: cell?.textLabel?.text = "项目" case 3 : cell?.textLabel?.text = "Gists" default: break } return cell! } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if(self.userInfoDate != nil){ let username = self.userInfoDate!.login if(indexPath.section == 0){ switch indexPath.row { case 0: print("事件") ProgressHUD.show() Github.getUserEvents(username, completionHandler: { (data:AnyObject?) in if let d = data{ let json = JSON(d) OperationQueueHelper.operateInMainQueue({ ProgressHUD.dismiss() let controller = UserEventsController() controller.eventData = json self.navigationController?.pushViewController(controller, animated: true) }) } }) case 1: print("组织") ProgressHUD.show() Github.getUserOrgs(username, completionHandler: { (data:AnyObject?) in if let d = data{ let json = JSON(d) OperationQueueHelper.operateInMainQueue({ ProgressHUD.dismiss() let controller = OrgsListController() controller.data = json.arrayValue self.navigationController?.pushViewController(controller, animated: true) }) } }) case 2: print("项目") ProgressHUD.show() Github.getUserRepos(username, completionHandler: { (data:AnyObject?) in if let d = data{ let json = JSON(d) OperationQueueHelper.operateInMainQueue({ ProgressHUD.dismiss() let controller = RepoListController() controller.repositoryDataList = json self.navigationController?.pushViewController(controller, animated: true) }) } }) case 3: print("gists") Github.getUserGists(username, completionHandler: { (data:AnyObject?) in if let d = data{ let json = JSON(d) print(json) } }) default: break } } } } /* // 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. } */ }
gpl-2.0
9a524cda92d04f29f39fa027eb5f21eb
35.883871
192
0.510582
6.017895
false
false
false
false
gegeburu3308119/ZCweb
ZCwebo/ZCwebo/Classes/Tools/Extensions/UIImageView+WebImage.swift
1
1179
// // UIImageView+WebImage.swift // 传智微博 // // Created by apple on 16/7/5. // Copyright © 2016年 itcast. All rights reserved. // import SDWebImage extension UIImageView { /// 隔离 SDWebImage 设置图像函数 /// /// - parameter urlString: urlString /// - parameter placeholderImage: 占位图像 /// - parameter isAvatar: 是否头像 func cz_setImage(urlString: String?, placeholderImage: UIImage?, isAvatar: Bool = false) { // 处理 URL guard let urlString = urlString, let url = NSURL.init(string: urlString) else { // 设置占位图像 image = placeholderImage return } // 可选项只是用在 Swift,OC 有的时候用 ! 同样可以传入 nil sd_setImage(with: url as URL!, placeholderImage: placeholderImage, options: [], progress: nil) { [weak self] (image, _, _, _) in // 完成回调 - 判断是否是头像 if isAvatar { self?.image = image?.cz_avatarImage(size: self?.bounds.size) } } } }
apache-2.0
0c627816bdab89eb20eb09a84b83eb90
25.5
136
0.532075
4.308943
false
false
false
false
JadenGeller/Parsley
Sources/Text.swift
1
3184
// // Text.swift // Parsley // // Created by Jaden Geller on 1/12/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import Spork extension ParserType where Token == Character { /** Runs the parser on the passed in `sequence`. - Parameter sequence: The sequence to be parsed. - Throws: `ParseError` if unable to parse. - Returns: The resulting parsed value. */ public func parse(string: String) throws -> Result { return try parse(ParseState(string.characters)) } } extension Parser where Result: SequenceType, Result.Generator.Element == Character { /** Converts a parser that results in a sequence of characters into a parser that results in a String. */ @warn_unused_result public func stringify() -> Parser<Token, String> { return map { String($0) } } } /** Construct a `Parser` that matches a given character. - Parameter character: The character to match against. */ @warn_unused_result public func character(character: Character) -> Parser<Character, Character> { return token(character).withError("character(\(character))") } /** Constructs a `Parser` that matches a given string of text. - Parameter text: The string of text to match against. */ @warn_unused_result public func string(text: String) -> Parser<Character, [Character]> { return sequence(text.characters.map(token)).withError("string(\(text)") } /** Constructs a `Parser` that consumes a single token and returns the token if it is within the string `text`. - Parameter text: The `String` that the input is tested against. */ @warn_unused_result public func within(text: String) -> Parser<Character, Character> { return one(of: text.characters).withError("within(\(text))") } /** A `Parser` that succeeds upon consuming a letter from the English alphabet. */ public let letter: Parser<Character, Character> = within("A"..."z").withError("letter") /** A `Parser` that succeeds upon consuming an Arabic numeral. */ public let digit: Parser<Character, Character> = within("0"..."9").withError("digit") /** Constructs a `Parser` that succeeds upon consuming a new line character. */ public let newLine: Parser<Character, Character> = token("\n").withError("newline") /** Constructs a `Parser` that succeeds upon consuming a tab character. */ public let tab: Parser<Character, Character> = token("\t").withError("tab") /** Constructs a `Parser` that skips zero or more whitespace characters. */ public let spaces: Parser<Character, ()> = many(space).discard().withError("spaces") /** Constructs a `Parser` that one whitespace character. */ public let space: Parser<Character, Character> = (token(" ") ?? newLine ?? tab).withError("space") /** Constructs a `Parser` that succeeds upon consuming an uppercase letter. */ public let uppercaseLetter: Parser<Character, Character> = within("A"..."Z").withError("uppercaseLetter") /** Constructs a `Parser` that succeeds upon consuming an lowercase letter. */ public let lowercaseLetter: Parser<Character, Character> = within("a"..."z").withError("lowercaseLetter")
mit
95b45df86e566f61aa1e43b4f4c26f27
30.205882
105
0.687716
4.149935
false
false
false
false
richard4339/DrawerController
DrawerController/AnimatedMenuButton.swift
4
5768
// Copyright (c) 2014 evolved.io (http://evolved.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import QuartzCore import UIKit public class AnimatedMenuButton : UIButton { let top: CAShapeLayer = CAShapeLayer() let middle: CAShapeLayer = CAShapeLayer() let bottom: CAShapeLayer = CAShapeLayer() let strokeColor: UIColor // MARK: - Constants let animationDuration: CFTimeInterval = 8.0 let shortStroke: CGPath = { let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, 2, 2) CGPathAddLineToPoint(path, nil, 30 - 2 * 2, 2) return path }() // MARK: - Initializers required public init?(coder aDecoder: NSCoder) { self.strokeColor = UIColor.grayColor() super.init(coder: aDecoder) } override convenience init(frame: CGRect) { self.init(frame: frame, strokeColor: UIColor.grayColor()) } init(frame: CGRect, strokeColor: UIColor) { self.strokeColor = strokeColor super.init(frame: frame) self.top.path = shortStroke; self.middle.path = shortStroke; self.bottom.path = shortStroke; for layer in [ self.top, self.middle, self.bottom ] { layer.fillColor = nil layer.strokeColor = self.strokeColor.CGColor layer.lineWidth = 4 layer.miterLimit = 2 layer.lineCap = kCALineCapRound layer.masksToBounds = true let strokingPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 4, .Round, .Miter, 4) layer.bounds = CGPathGetPathBoundingBox(strokingPath) layer.actions = [ "opacity": NSNull(), "transform": NSNull() ] self.layer.addSublayer(layer) } self.top.anchorPoint = CGPoint(x: 1, y: 0.5) self.top.position = CGPoint(x: 30 - 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) self.bottom.position = CGPoint(x: 30 - 1, y: 25) } // MARK: - Animations public func animateWithPercentVisible(percentVisible:CGFloat, drawerSide: DrawerSide) { if drawerSide == DrawerSide.Left { self.top.anchorPoint = CGPoint(x: 1, y: 0.5) self.top.position = CGPoint(x: 30 - 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) self.bottom.position = CGPoint(x: 30 - 1, y: 25) } else if drawerSide == DrawerSide.Right { self.top.anchorPoint = CGPoint(x: 0, y: 0.5) self.top.position = CGPoint(x: 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 0, y: 0.5) self.bottom.position = CGPoint(x: 1, y: 25) } let middleTransform = CABasicAnimation(keyPath: "opacity") middleTransform.duration = animationDuration let topTransform = CABasicAnimation(keyPath: "transform") topTransform.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85) topTransform.duration = animationDuration topTransform.fillMode = kCAFillModeBackwards let bottomTransform = topTransform.copy() as! CABasicAnimation middleTransform.toValue = 1 - percentVisible let translation = CATransform3DMakeTranslation(-4 * percentVisible, 0, 0) let sideInverter: CGFloat = drawerSide == DrawerSide.Left ? -1 : 1 topTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, 1.0 * sideInverter * ((CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) bottomTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, (-1.0 * sideInverter * (CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) topTransform.beginTime = CACurrentMediaTime() bottomTransform.beginTime = CACurrentMediaTime() self.top.addAnimation(topTransform, forKey: topTransform.keyPath) self.middle.addAnimation(middleTransform, forKey: middleTransform.keyPath) self.bottom.addAnimation(bottomTransform, forKey: bottomTransform.keyPath) self.top.setValue(topTransform.toValue, forKey: topTransform.keyPath!) self.middle.setValue(middleTransform.toValue, forKey: middleTransform.keyPath!) self.bottom.setValue(bottomTransform.toValue, forKey: bottomTransform.keyPath!) } }
mit
5d29ed225cf8443269c8103d7a9f57b9
40.496403
172
0.640083
4.467854
false
false
false
false
Neft-io/neft
packages/neft-scrollable/native/macos/ScrollableItem.swift
1
2900
import Cocoa extension Extension.Scrollable { class ScrollableItem: NativeItem { override class var name: String { return "Scrollable" } override class func register() { onCreate { return ScrollableItem() } onSet("contentItem") { (item: ScrollableItem, val: Item?) in item.contentItem = val } onSet("contentX") { (item: ScrollableItem, val: CGFloat) in item.contentX = val } onSet("contentY") { (item: ScrollableItem, val: CGFloat) in item.contentY = val } } class Delegate: NSViewController { weak var scrollable: ScrollableItem? func scrollViewDidScroll(_ scrollView: NSScrollView) { guard scrollable != nil else { return } let point = scrollView.documentVisibleRect.origin scrollable!.pushEvent(event: "contentXChange", args: [point.x]) scrollable!.pushEvent(event: "contentYChange", args: [point.y]) } } let delegate = Delegate() let scrollView = NSScrollView() var contentItem: Item? { didSet { if oldValue != nil { oldValue!.view.removeFromSuperview() } if contentItem != nil { contentItem!.view.removeFromSuperview() scrollView.addSubview(contentItem!.view, positioned: .above, relativeTo: nil) } } } var contentX: CGFloat = 0 { didSet { updateScroll() } } var contentY: CGFloat = 0 { didSet { updateScroll() } } override var width: CGFloat { didSet { super.width = width scrollView.frame.size.width = width scrollView.frame = scrollView.frame } } override var height: CGFloat { didSet { super.height = height scrollView.frame.size.height = height scrollView.frame = scrollView.frame } } init() { super.init(itemView: NSView()) view.addSubview(scrollView) //delegate.scrollable = self } func updateScroll() { scrollView.documentView?.scroll(NSPoint(x: contentX, y: contentY)) } override func onPointerPress(_ x: CGFloat, _ y: CGFloat) { super.onPointerPress(x, y) guard contentItem != nil else { return } // scrollView.contentSize = contentItem!.view.layer.bounds.size // scrollView.delegate = delegate } } }
apache-2.0
b1b20c7d6e1cb95c48438cceeb102e58
27.712871
97
0.494138
5.430712
false
false
false
false
rpowelll/GameBro
Sources/GameBro/CPU.swift
1
4093
/// An implementation of the Sharp LR35902 processor used by the Game Boy /// /// ## Register Layout /// /// FEDCBA98 76543210 /// +--------+--------+ /// | A | F | AF /// | B | C | BC /// | D | E | DE /// | H | L | HL /// +--------+--------+ /// | SP | Stack Pointer /// | PC | Program Counter /// +-----------------+ /// /// ## Flags /// /// 76543210 /// +----------+ /// | ZNHC---- | /// +----------+ /// /// + Z - Zero - Set when the result of a math operation is zero, or two values match for a CP operation /// + N - Subtract - Set if a subtraction was performed in the last math operation /// + H - Half-Carry - Set if a carry occurred from the lower nibble in the last math operation /// + C - Carry - Set if a carry occurred in the last math operation, or if the accumulator A is less than value for a CP operation public struct CPU { /// The stack pointer public var SP: UInt16 = 0 /// The program counter public var PC: UInt16 = 0x100 /// The A register public var A: UInt8 = 0 /// The flag register public var F: UInt8 = 0 /// The B register public var B: UInt8 = 0 /// The C register public var C: UInt8 = 0 /// The D register public var D: UInt8 = 0 /// The E register public var E: UInt8 = 0 /// The H register public var H: UInt8 = 0 /// The L register public var L: UInt8 = 0 /// The CPU's memory public var memory: Memory /// The number of elapsed cycles public var cycle: UInt64 = 0 /// Create a new CPU with the provided memory /// /// - parameter memory: the memory this CPU will use /// - returns: a CPU with the provided memory public init(memory: Memory) { self.memory = memory } } // Pseudo 16-bit registers public extension CPU { /// The AF register /// A 16-bit register made from the 8-bit A and F registers public var AF: UInt16 { get { return UInt16(A) << 8 | UInt16(F) } set { A = UInt8(newValue >> 8) F = UInt8(newValue & 0x00FF) } } /// The BC register /// A 16-bit register made from the 8-bit B and C registers public var BC: UInt16 { get { return UInt16(B) << 8 | UInt16(C) } set { B = UInt8(newValue >> 8) C = UInt8(newValue & 0x00FF) } } /// The DE register /// A 16-bit register made from the 8-bit D and E registers public var DE: UInt16 { get { return UInt16(D) << 8 | UInt16(E) } set { D = UInt8(newValue >> 8) E = UInt8(newValue & 0x00FF) } } /// The HL register /// A 16-bit register made from the 8-bit H and L registers public var HL: UInt16 { get { return UInt16(H) << 8 | UInt16(L) } set { H = UInt8(newValue >> 8) L = UInt8(newValue & 0x00FF) } } } // Flags public extension CPU { private func getFlag(_ flag: UInt8) -> Bool { return (flag & F) != 0 } private mutating func setFlag(_ flag: UInt8, _ value: Bool) { if value { F |= flag } else { F &= ~flag } } /// Zero flag public var ZFlag: Bool { get { return getFlag(0x80) } set { setFlag(0x80, newValue) } } /// Subtract flag public var NFlag: Bool { get { return getFlag(0x40) } set { setFlag(0x40, newValue) } } /// Half-carry flag public var HFlag: Bool { get { return getFlag(0x20) } set { setFlag(0x20, newValue) } } /// Carry flag public var CFlag: Bool { get { return getFlag(0x10) } set { setFlag(0x10, newValue) } } }
mit
f0af2ddd769501477114fcdb9068d930
21.738889
131
0.482775
3.78281
false
false
false
false
SimpleApp/evc-swift
EVC/EVC/ViewController.swift
1
2250
// // ViewController.swift // EVC // // Created by Benjamin Garrigues on 04/09/2017. import UIKit class ViewController: UIViewController { //MARK: - View properties @IBOutlet weak var label: UILabel! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! //MARK: - Data properties var engine: EVCEngine? = nil { didSet { engine?.sampleService.register(observer: self) } } //MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() //Because this sample uses a Storyboard to create its root view controller, //we need to grab the engine on the appdelegate from here. engine = (UIApplication.shared.delegate as? AppDelegate)?.engine updateViews() } //MARK: View rendering fileprivate func updateViews() { loadingIndicator.stopAnimating() if let value = engine?.sampleService.currentSampleData?.value { label.text = String(value) } else { label.text = "No data yet" } } //MARK: - Actions @IBAction func onTapCallSampleService(_ sender: Any) { loadingIndicator.startAnimating() engine?.sampleService.refreshData(onError: { [weak self](error) in self?.loadingIndicator.stopAnimating() if let error = error { let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default,handler: nil)) self?.present(alertController, animated: true, completion: nil) } }) } } //MARK: - SampleServiceObserver. //Whenever the data change, we rerender the whole view. //This single refresh loop is the easiest way to keep your screen updated in a consistant manner. //You should start thinking about refreshing parts of your screen only if performance is an issue. extension ViewController : SampleServiceObserver { func onSampleService(_ service: SampleService, didUpdateSampleDataTo newValue: SampleModel?) { self.updateViews() } }
mit
f6d99efc6743c8036c2d290a439ca9e6
30.690141
117
0.656889
4.923414
false
false
false
false
andreaperizzato/CoreStore
CoreStoreDemo/CoreStoreDemo/List and Object Observers Demo/ObjectObserverDemoViewController.swift
3
5570
// // ObjectObserverDemoViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/05/06. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore // MARK: - ObjectObserverDemoViewController class ObjectObserverDemoViewController: UIViewController, ObjectObserver { var palette: Palette? { get { return self.monitor?.object } set { guard self.monitor?.object != newValue else { return } if let palette = newValue { self.monitor = CoreStore.monitorObject(palette) } else { self.monitor = nil } } } // MARK: NSObject deinit { self.monitor?.removeObserver(self) } // MARK: UIViewController required init?(coder aDecoder: NSCoder) { if let palette = CoreStore.fetchOne(From(Palette), OrderBy(.Ascending("hue"))) { self.monitor = CoreStore.monitorObject(palette) } else { CoreStore.beginSynchronous { (transaction) -> Void in let palette = transaction.create(Into(Palette)) palette.setInitialValues() transaction.commit() } let palette = CoreStore.fetchOne(From(Palette), OrderBy(.Ascending("hue")))! self.monitor = CoreStore.monitorObject(palette) } super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.monitor?.addObserver(self) if let palette = self.monitor?.object { self.reloadPaletteInfo(palette, changedKeys: nil) } } // MARK: ObjectObserver func objectMonitor(monitor: ObjectMonitor<Palette>, didUpdateObject object: Palette, changedPersistentKeys: Set<KeyPath>) { self.reloadPaletteInfo(object, changedKeys: changedPersistentKeys) } func objectMonitor(monitor: ObjectMonitor<Palette>, didDeleteObject object: Palette) { self.navigationItem.rightBarButtonItem?.enabled = false self.colorNameLabel?.alpha = 0.3 self.colorView?.alpha = 0.3 self.hsbLabel?.text = "Deleted" self.hsbLabel?.textColor = UIColor.redColor() self.hueSlider?.enabled = false self.saturationSlider?.enabled = false self.brightnessSlider?.enabled = false } // MARK: Private var monitor: ObjectMonitor<Palette>? @IBOutlet weak var colorNameLabel: UILabel? @IBOutlet weak var colorView: UIView? @IBOutlet weak var hsbLabel: UILabel? @IBOutlet weak var dateLabel: UILabel? @IBOutlet weak var hueSlider: UISlider? @IBOutlet weak var saturationSlider: UISlider? @IBOutlet weak var brightnessSlider: UISlider? @IBAction dynamic func hueSliderValueDidChange(sender: AnyObject?) { let hue = self.hueSlider?.value ?? 0 CoreStore.beginAsynchronous { [weak self] (transaction) -> Void in if let palette = transaction.edit(self?.monitor?.object) { palette.hue = Int32(hue) transaction.commit() } } } @IBAction dynamic func saturationSliderValueDidChange(sender: AnyObject?) { let saturation = self.saturationSlider?.value ?? 0 CoreStore.beginAsynchronous { [weak self] (transaction) -> Void in if let palette = transaction.edit(self?.monitor?.object) { palette.saturation = saturation transaction.commit() } } } @IBAction dynamic func brightnessSliderValueDidChange(sender: AnyObject?) { let brightness = self.brightnessSlider?.value ?? 0 CoreStore.beginAsynchronous { [weak self] (transaction) -> Void in if let palette = transaction.edit(self?.monitor?.object) { palette.brightness = brightness transaction.commit() } } } @IBAction dynamic func deleteBarButtonTapped(sender: AnyObject?) { CoreStore.beginAsynchronous { [weak self] (transaction) -> Void in transaction.delete(self?.monitor?.object) transaction.commit() } } func reloadPaletteInfo(palette: Palette, changedKeys: Set<String>?) { self.colorNameLabel?.text = palette.colorName let color = palette.color self.colorNameLabel?.textColor = color self.colorView?.backgroundColor = color self.hsbLabel?.text = palette.colorText if changedKeys == nil || changedKeys?.contains("hue") == true { self.hueSlider?.value = Float(palette.hue) } if changedKeys == nil || changedKeys?.contains("saturation") == true { self.saturationSlider?.value = palette.saturation } if changedKeys == nil || changedKeys?.contains("brightness") == true { self.brightnessSlider?.value = palette.brightness } } }
mit
780a5f05a69b34c716660811b7acb7d4
28.010417
127
0.556014
5.525794
false
false
false
false
nathawes/swift
validation-test/Evolution/test_backward_deploy_conformance.swift
22
632
// RUN: %target-resilience-test --backward-deployment // REQUIRES: executable_test import StdlibUnittest import backward_deploy_conformance var BackwardDeployConformanceTest = TestSuite("BackwardDeployConformance") public class UsesNewStruct: CustomStringConvertible { public var field: NewStruct<Bool>? = nil public let description = "This is my description" } public class OtherClass {} @_optimize(none) func blackHole<T>(_: T) {} BackwardDeployConformanceTest.test("ConformanceCache") { if getVersion() == 1 { blackHole(UsesNewStruct()) } blackHole(OtherClass() as? CustomStringConvertible) } runAllTests()
apache-2.0
567babbe9a1acc9be6d80346d492b640
22.407407
74
0.764241
4.358621
false
true
false
false
davidhariri/done
Done/Todo.swift
1
992
// // Todo.swift // Done // // Created by David Hariri on 2017-03-08. // Copyright © 2017 David Hariri. All rights reserved. // import Foundation class Todo: DoneBase { var text: String var done: Bool = false var selected: Bool = false init(withText t: String) { self.text = t } // Change the done property explicitly rather // than using toggleDone() func markDone(withDone d: Bool) { done = d } // Used to mark the done property as the opposite // of what it is right now func toggleDone() { markDone(withDone: !done) markUpdated() } // Used for when a TodoList is in editing mode // and a user is editing multiple todos at once func toggleSelected() { selected = !selected } // This method should be used to update the // text content of the Todo item func updateText(withText t: String) { text = t markUpdated() } }
apache-2.0
d8dabba237fa1615e240036fe813d1f4
21.022222
55
0.59334
4.095041
false
false
false
false
practicalswift/swift
test/SILGen/pointer_conversion_nonaccessing.swift
30
2572
// RUN: %target-swift-emit-silgen -swift-version 4 %s | %FileCheck %s // rdar://33265254 // Check for the total absence of access markers here. // FIXME: probably we should have some markers that just disable even static checking var global = 0 // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing6testEq3ptrSbSV_tF func testEq(ptr: UnsafeRawPointer) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global == ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing7testNeq3ptrSbSV_tF func testNeq(ptr: UnsafeRawPointer) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global != ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing6testEq3ptrSbSv_tF func testEq(ptr: UnsafeMutableRawPointer) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global == ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing7testNeq3ptrSbSv_tF func testNeq(ptr: UnsafeMutableRawPointer) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global != ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing6testEq3ptrSbSPySiG_tF func testEq(ptr: UnsafePointer<Int>) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global == ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing7testNeq3ptrSbSPySiG_tF func testNeq(ptr: UnsafePointer<Int>) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global != ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing6testEq3ptrSbSpySiG_tF func testEq(ptr: UnsafeMutablePointer<Int>) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global == ptr } // CHECK-LABEL: sil hidden [ossa] @$s31pointer_conversion_nonaccessing7testNeq3ptrSbSpySiG_tF func testNeq(ptr: UnsafeMutablePointer<Int>) -> Bool { // CHECK: [[T0:%.*]] = global_addr @$s31pointer_conversion_nonaccessing6globalSiv // CHECK: address_to_pointer [[T0]] return &global != ptr }
apache-2.0
94adeda287d8396988d0906e60ecb1a5
39.1875
93
0.718896
3.227102
false
true
false
false
czechboy0/Buildasaur
BuildaGitServer/GitHub/GitHubRateLimit.swift
2
1482
// // GitHubRateLimit.swift // Buildasaur // // Created by Honza Dvorsky on 03/05/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation struct GitHubRateLimit { let resetTime: Double let limit: Int let remaining: Int let now: Double = NSDate().timeIntervalSince1970 func getReport() -> String { let resetInterval = 3600.0 //reset interval is 1 hour let startTime = self.resetTime - resetInterval let remainingTime = self.resetTime - self.now let consumed = self.limit - self.remaining let consumedTime = self.now - startTime let rateOfConsumption = Double(consumed) / consumedTime let rateOfConsumptionPretty = rateOfConsumption.clipTo(2) let maxRateOfConsumption = Double(self.limit) / resetInterval let maxRateOfConsumptionPretty = maxRateOfConsumption.clipTo(2) //how much faster we can be consuming requests before we hit the maximum rate of 5000/hour let usedRatePercent = (100.0 * rateOfConsumption / maxRateOfConsumption).clipTo(2) let report = "count: \(consumed)/\(self.limit), renews in \(Int(remainingTime)) seconds, rate: \(rateOfConsumptionPretty)/\(maxRateOfConsumptionPretty), using \(usedRatePercent)% of the allowed request rate." return report } } extension GitHubRateLimit: RateLimitType { var report: String { return self.getReport() } }
mit
3d77e626163978468984fc7964e22524
33.465116
216
0.677463
4.477341
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Buttons/BuyButton.swift
1
1812
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI @available(*, renamed: "BuyButton") public typealias ExchangeBuyButton = BuyButton /// BuyButton from the Figma Component Library. /// /// /// # Usage: /// /// `BuyButton(title: "Tap me") { print("button did tap") }` /// /// - Version: 1.0.1 /// /// # Figma /// /// [Buttons](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=3%3A367) public struct BuyButton: View { private let title: String private let action: () -> Void private let isLoading: Bool @Environment(\.isEnabled) private var isEnabled public init( title: String, isLoading: Bool = false, action: @escaping () -> Void ) { self.title = title self.isLoading = isLoading self.action = action } public var body: some View { Button(title) { action() } .buttonStyle( PillButtonStyle( isLoading: isLoading, isEnabled: isEnabled, size: .standard, colorCombination: .buyButtonColorCombination ) ) } } struct BuyButton_Previews: PreviewProvider { static var previews: some View { Group { BuyButton(title: "Enabled", action: {}) .previewLayout(.sizeThatFits) .previewDisplayName("Enabled") BuyButton(title: "Disabled", action: {}) .disabled(true) .previewLayout(.sizeThatFits) .previewDisplayName("Disabled") BuyButton(title: "Loading", isLoading: true, action: {}) .previewLayout(.sizeThatFits) .previewDisplayName("Loading") } .padding() } }
lgpl-3.0
e3d831ddc5f3e29658ab58bf49e7dde5
24.152778
101
0.561568
4.471605
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationMock/WalletAuthentication/MockWalletRepository.swift
1
3704
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine @testable import FeatureAuthenticationDomain import ToolKit import WalletPayloadKit final class MockWalletRepository: WalletRepositoryAPI { var expectedSessionToken: String? var expectedAuthenticatorType: WalletAuthenticatorType = .standard var expectedGuid: String? var expectedPayload: String? var expectedSharedKey: String? var expectedPassword: String? var expectedSyncPubKeys = false var expectedOfflineToken: Result<NabuOfflineToken, MissingCredentialsError>! var expectedChangePassword: Result<Void, PasswordRepositoryError>! var guid: AnyPublisher<String?, Never> { .just(expectedGuid) } var sharedKey: AnyPublisher<String?, Never> { .just(expectedSharedKey) } var sessionToken: AnyPublisher<String?, Never> { .just(expectedSessionToken) } var authenticatorType: AnyPublisher<WalletAuthenticatorType, Never> { .just(expectedAuthenticatorType) } var password: AnyPublisher<String?, Never> { .just(expectedPassword) } var hasPassword: AnyPublisher<Bool, Never> { .just(true) } var payload: AnyPublisher<String?, Never> { .just(expectedPayload) } var offlineTokenPublisher: AnyPublisher<Result<NabuOfflineToken, MissingCredentialsError>, Never> { Just(expectedOfflineToken).eraseToAnyPublisher() } var offlineToken: AnyPublisher<NabuOfflineToken, MissingCredentialsError> { expectedOfflineToken.publisher.eraseToAnyPublisher() } func set(guid: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedGuid = guid } } func set(sharedKey: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedSharedKey = sharedKey } } func set(sessionToken: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedSessionToken = sessionToken } } func cleanSessionToken() -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedSessionToken = nil } } func set(authenticatorType: WalletAuthenticatorType) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedAuthenticatorType = authenticatorType } } func set(password: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedPassword = password } } func changePassword(password: String) -> AnyPublisher<Void, PasswordRepositoryError> { expectedChangePassword .publisher .eraseToAnyPublisher() } func set(offlineToken: NabuOfflineToken) -> AnyPublisher<Void, CredentialWritingError> { perform { [weak self] in self?.expectedOfflineToken = .success(offlineToken) } } func set(syncPubKeys: Bool) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedSyncPubKeys = syncPubKeys } } func sync() -> AnyPublisher<Void, PasswordRepositoryError> { perform {} } func set(language: String) -> AnyPublisher<Void, Never> { .just(()) } func set(payload: String) -> AnyPublisher<Void, Never> { perform { [weak self] in self?.expectedPayload = payload } } private func perform<E: Error>(_ operation: @escaping () -> Void) -> AnyPublisher<Void, E> { Deferred { Future { $0(.success(operation())) } } .eraseToAnyPublisher() } }
lgpl-3.0
229e1a65b2d7cee7de3cd5ce8b735a14
27.484615
103
0.642722
4.778065
false
false
false
false
PekanMmd/Pokemon-XD-Code
Revolution Tool CL/objects/PBRStringTable.swift
1
10699
// // PBRStringTable.swift // XGCommandLineTools // // Created by StarsMmd on 05/03/2016. // Copyright © 2016 StarsMmd. All rights reserved. // import Foundation let kNumberOfStringsOffset = 0x06 let kStringTableIDOffset = 0x08 let kStringTableLanguageOffset = 0x0C let kEndOfHeader = 0x10 // high order 12 bits are compared with the string table's first 2 bytes // always seems to be 0 though let kMaxStringID = 0xFFFFF class XGStringTable: NSObject { static var mes_common = XGFiles.typeAndFsysName(.msg, region == .JP ? "common" : "mes_common") var file = XGFiles.nameAndFolder("", .Documents) { didSet { stringTable.file = file } } var startOffset = 0x0 // where in the file the string table is located. used for files like common.rel which have more than just the table var stringTable = XGMutableData() var stringOffsets = [Int : Int]() var stringIDs = [Int]() var tableID = 0 var language = XGStringTableLanguages.english var numberOfEntries : Int { get { return stringTable.get2BytesAtOffset(kNumberOfStringsOffset) } } var fileSize : Int { get { return self.stringTable.length } } var extraCharacters : Int { get { var currentChar = 0x00 var currentOffset = fileSize - 3 // the file always ends in 0x0000 to end its last string so it isn't included var length = 0 while currentChar == 0x00 { currentChar = stringTable.getByteAtOffset(currentOffset) if currentChar == 0x00 { length += 1 } currentOffset -= 1 } return length } } init(file: XGFiles, startOffset: Int, fileSize: Int) { super.init() self.file = file self.startOffset = startOffset self.stringTable = file.data! stringTable.deleteBytes(start: 0, count: startOffset) stringTable.deleteBytes(start: fileSize, count: stringTable.length - fileSize) setup() } init(data: XGMutableData) { super.init() self.file = data.file self.startOffset = 0 self.stringTable = data setup() } private func setup() { tableID = stringTable.get4BytesAtOffset(kStringTableIDOffset) let languageBinary = stringTable.getWordAtOffset(kStringTableLanguageOffset) language = XGStringTableLanguages.fromBinary(languageBinary) getOffsets() } func save() { if self.startOffset == 0 { stringTable.save() } else { let data = file.data! data.replaceBytesFromOffset(self.startOffset, withByteStream: stringTable.byteStream) data.save() } } @discardableResult func addString(_ string: XGString, increaseSize: Bool, save: Bool) -> Bool { if self.numberOfEntries == 0xFFFF { printg("String table \(stringTable.file.fileName) has the maximum number of entries!") return false } if !self.containsStringWithId(string.id) { if string.id == 0 { printg("Cannot add string with id 0") return false } if string.id > numberOfEntries + 1 { printg("Cannot add string with id \(string.id). Must add string ids in order.") printg("Next available id is \(numberOfEntries + 1)") return false } let bytesRequired = string.dataLength + 4 if self.extraCharacters > bytesRequired { self.stringTable.deleteBytes(start: stringTable.length - bytesRequired, count: bytesRequired) } else { if self.startOffset != 0 || !increaseSize { printg("Couldn't add string to \(stringTable.file.fileName) because it doesn't have enough space.") return false } } self.stringTable.insertRepeatedByte(byte: 0, count: bytesRequired, atOffset: (numberOfEntries * 4) + kEndOfHeader) self.stringTable.replaceBytesFromOffset( ((numberOfEntries + 1) * 4) + kEndOfHeader, withByteStream: string.byteStream) self.increaseOffsetsAfter(0, by: bytesRequired) self.stringOffsets[string.id] = ((numberOfEntries + 1) * 4) + kEndOfHeader self.stringIDs.append(string.id) self.stringTable.replace2BytesAtOffset(kNumberOfStringsOffset, withBytes: numberOfEntries + 1) self.updateOffsets() if save { self.save() } return true } else { return self.replaceString(string, save: save) } } func getOffsets() { var currentOffset = kEndOfHeader for id in 1 ... numberOfEntries { let offset = stringTable.getWordAtOffset(currentOffset).int self.stringOffsets[id] = offset self.stringIDs.append(id) currentOffset += 4 } } func updateOffsets() { var currentOffset = kEndOfHeader var sids = self.stringIDs sids.sort{$0 < $1} for sid in sids { stringTable.replaceWordAtOffset(currentOffset, withBytes: UInt32(stringOffsets[sid]!)) currentOffset += 4 } } func decreaseOffsetsAfter(_ offset: Int, by bytes: Int) { for sid in self.stringIDs { if let off = stringOffsets[sid] { if off > offset { stringOffsets[sid] = off - bytes } } } } func increaseOffsetsAfter(_ offset: Int, by bytes: Int) { for sid in self.stringIDs { if let off = stringOffsets[sid] { if off > offset { stringOffsets[sid] = off + bytes } } } } func offsetForStringID(_ stringID : Int) -> Int? { return self.stringOffsets[stringID] } func endOffsetForStringId(_ stringID : Int) -> Int { let startOff = offsetForStringID(stringID)! let text = stringWithID(stringID)! return startOff + text.dataLength } func getStringAtOffset(_ offset: Int) -> XGString { var currentOffset = offset var currChar = 0x0 let string = XGString(string: "", file: self.file, sid: 0) var complete = false while (currentOffset < self.stringTable.length - 1 && !complete) { currChar = stringTable.get2BytesAtOffset(currentOffset) currentOffset += 2 // These are special characters used by the game. Similar to escape sequences like \n or \t for newlines and tabs. if currChar == 0xFFFF { let sp = XGSpecialCharacters.id(stringTable.get2BytesAtOffset(currentOffset)) currentOffset += 2 if sp.id == 0xFFFF { complete = true } else { let extra = sp.extraBytes let stream = stringTable.getByteStreamFromOffset(currentOffset, length: extra) currentOffset += extra string.append(.special(sp, stream)) } } else { // This is a regular character so read normally. string.append(.unicode(currChar)) } } return string } func stringWithID(_ stringID: Int) -> XGString? { let offset = offsetForStringID(stringID) if offset != nil { if offset! + 2 >= self.stringTable.length { return nil } let string = getStringAtOffset(offset!) string.id = stringID return string } return nil } func stringSafelyWithID(_ stringID: Int) -> XGString { let string = stringWithID(stringID) return string ?? XGString(string: "-", file: nil, sid: 0) } func containsStringWithId(_ stringID: Int) -> Bool { return stringIDs.contains(stringID) } func allStrings() -> [XGString] { var strings = [XGString]() for sid in self.stringIDs { let string = self.stringSafelyWithID(sid) strings.append(string) } return strings } func purge() { let strings = self.allStrings() for str in strings { let empty = str.duplicateWithString("-") replaceString(empty) } self.save() printg("Purged String Table:",self.file.fileName) } func printAllStrings() { for string in self.allStrings() { printg(string.string,"\n") } } func writeJSON(to file: XGFiles) { guard let data = try? JSONRepresentation(), data.write(to: file) else { printg("Failed to write JSON to:", file.path) return } if XGSettings.current.verbose { printg("Successfully wrote JSON to:", file.path) } } func removeKanji() { for string in self.allStrings() where string.hasFurigana { string.removeKanji() replaceString(string, save: false) } } } enum XGStringTableLanguages: String, CaseIterable, Codable { case japanese case english case french case german case italian case spanish var binary: UInt32 { switch self { case .japanese: return 0x4A504A50 case .english: return 0x5553554B case .french: return 0x46524652 case .german: return 0x53505350 case .italian: return 0x49544954 case .spanish: return 0x47524752 } } static func fromBinary(_ binary: UInt32) -> XGStringTableLanguages { for language in allCases { if language.binary == binary { return language } } return .english } } struct XGStringTableMetaData: Codable { let file: XGFiles let tableID: Int let language: XGStringTableLanguages let strings: [String] } extension XGStringTable: Encodable { enum XGStringTableDecodingError: Error { case invalidData } enum CodingKeys: String, CodingKey { case file, tableID, language, strings } static func fromJSON(data: Data, removeKanji: Bool = false) throws -> XGStringTable { let decodedMetaData = try? JSONDecoder().decode(XGStringTableMetaData.self, from: data) guard let metaData = decodedMetaData else { throw XGStringTableDecodingError.invalidData } let numberOfStrings = metaData.strings.count let data = XGMutableData() data.file = metaData.file // Header data.appendBytes([0x4D, 0x45, 0x53, 0x47]) // MESG magic bytes data.appendBytes(numberOfStrings.charArray) data.appendBytes(metaData.tableID.charArray) data.appendBytes(metaData.language.binary.charArray) // Pointers let headerSize = 16 let pointerSize = 4 * numberOfStrings let endOfPointers = headerSize + pointerSize let pointerInitData = [UInt8](repeating: 0, count: pointerSize) data.appendBytes(pointerInitData) var currentStringOffset = endOfPointers var currentPointerOffset = headerSize for str in metaData.strings { data.replace4BytesAtOffset(currentPointerOffset, withBytes: currentStringOffset) let string = XGString(string: str, file: nil, sid: nil) if removeKanji { string.removeKanji() } let stringData = string.byteStream data.appendBytes(stringData) currentStringOffset += stringData.count currentPointerOffset += 4 } return XGStringTable(data: data) } static func fromJSONFile(file: XGFiles) throws -> XGStringTable { let url = URL(fileURLWithPath: file.path) let data = try Data(contentsOf: url) return try fromJSON(data: data) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(file, forKey: .file) try container.encode(tableID, forKey: .tableID) try container.encode(language, forKey: .language) try container.encode(allStrings().map { $0.string }, forKey: .strings) } }
gpl-2.0
047d80d452abce00dc2b2edf55c27393
22.105832
139
0.689662
3.500654
false
false
false
false
bcesur/FitPocket
FitPocket/FitPocket/IntroViewController.swift
1
3005
// // ViewController.swift // FitPocket // // Created by Berkay Cesur on 19/12/14. // Copyright (c) 2014 Berkay Cesur. All rights reserved. // import UIKit var user = UserProfile() let userDefaults = NSUserDefaults.standardUserDefaults() class IntroViewController: UIViewController, UITextFieldDelegate { var introDone : Bool = false // to check whether this view controller performed or not var gender: Int = 0 @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var ageTextField: UITextField! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! @IBOutlet weak var genderChanger: UISegmentedControl! @IBAction func genderChanged(sender: UISegmentedControl) { switch genderChanger.selectedSegmentIndex { case 0: println("0") user.setGender("male") gender = 0 break; case 1: println("1") user.setGender("female") gender = 1 break; default: println("defualt") user.setGender("male") gender = 0 break; } } @IBAction func editingFinished(sender: AnyObject) { user.setName(nameTextField.text) user.setAge(ageTextField.text.toInt()!) user.setWeight(Double(weightTextField.text.toInt()!)) user.setHeigh(Double(heightTextField.text.toInt()!)) userDefaults.setInteger(user.getAge(), forKey: "userAge") userDefaults.setInteger(gender, forKey: "userGender") userDefaults.setDouble(user.getWeight(), forKey: "userWeight") userDefaults.setDouble(user.getHeight(), forKey: "userHeight") introDone = false //NSUserDefaults.standardUserDefaults().setObject(introDone, forKey: "introDone") userDefaults.synchronize() } override func viewWillAppear(animated: Bool) { if userDefaults.objectForKey("userName") != nil{ performSegueWithIdentifier("idMainMenu", sender: nil) } super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() self.nameTextField.delegate = self self.ageTextField.delegate = self self.heightTextField.delegate = self self.weightTextField.delegate = self // Do any additional setup after loading the view, typically from a nib. } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let departmentVC = segue.destinationViewController as! MainMenuViewController } }
gpl-2.0
87d6ac185307c471170b1cf6adcec740
29.05
90
0.632612
5.110544
false
false
false
false
Ethenyl/JAMFKit
JamfKit/Tests/Models/Policy/PolicyNetworkLimitationsTests.swift
1
1651
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // import XCTest @testable import JamfKit class PolicyNetworkLimitationsTests: XCTestCase { // MARK: - Constants let subfolder = "Policy/" let defaultMinimumNetworkConnection = "No Minimum" let defaultAnyIpAddress = true // MARK: - Tests func testShouldInitializeFromJSON() { let payload = self.payload(for: "policy_network_limitations", subfolder: subfolder)! let actualValue = PolicyNetworkLimitations(json: payload) XCTAssertNotNil(actualValue) XCTAssertEqual(actualValue?.minimumNetworkConnection, defaultMinimumNetworkConnection) XCTAssertEqual(actualValue?.anyIpAddress, defaultAnyIpAddress) } func testShouldInitializeFromEmptyJSON() { let actualValue = PolicyNetworkLimitations(json: [String: Any]()) XCTAssertNotNil(actualValue) XCTAssertEqual(actualValue?.minimumNetworkConnection, "") XCTAssertEqual(actualValue?.anyIpAddress, false) } func testShouldEncodeToJSON() { let payload = self.payload(for: "policy_network_limitations", subfolder: subfolder)! let actualValue = PolicyNetworkLimitations(json: payload) let encodedObject = actualValue?.toJSON() XCTAssertNotNil(encodedObject) XCTAssertEqual(encodedObject?.count, 2) XCTAssertNotNil(encodedObject?[PolicyNetworkLimitations.MinimumNetworkConnectionKey]) XCTAssertNotNil(encodedObject?[PolicyNetworkLimitations.AnyIpAddressKey]) } }
mit
ba947c78dcc61217db3e6772e92fd41c
32.673469
102
0.730909
5.172414
false
true
false
false
kallahir/AlbumTrackr-iOS
AlbumTracker/ManageAccountViewController.swift
1
2589
// // ManageAccoutnViewController.swift // AlbumTracker // // Created by Itallo Rossi Lucas on 5/8/16. // Copyright © 2016 AlbumTrackr. All rights reserved. // import UIKit class ManageAccoutnViewController: UITableViewController { var notificationType = ["Settings.notification_album","Settings.notification_ep","Settings.notification_single","Settings.notification_other"] override func viewDidLoad() { super.viewDidLoad() self.tableView.bounces = false self.tableView.allowsSelection = false self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 1 { let cell = self.tableView.dequeueReusableCellWithIdentifier("NotificationCell") as! NotificationCell cell.notificationText.text = NSLocalizedString(self.notificationType[indexPath.row], comment: "Notification Type") cell.notificationDetail.text = NSLocalizedString(self.notificationType[indexPath.row]+"_details", comment: "Notification Type Details") cell.notificationSelection.setOn(true, animated: true) return cell } let cell = self.tableView.dequeueReusableCellWithIdentifier("UserCell") as! UserCell cell.userImage.image = UIImage(named: "profile_pic") cell.userName.text = NSLocalizedString("Settings.account_not_synced", comment: "Account Synchronization") cell.userName.tintColor = UIColor.redColor() return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } return self.notificationType.count } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 && indexPath.row == 0 { return 120 } return 55 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0{ return NSLocalizedString("Settings.personal_info", comment: "Personal Information") } return NSLocalizedString("Settings.notifications", comment: "Notifications") } }
agpl-3.0
ad276bcff2c586b46c8f3786578781ec
35.971429
147
0.665379
5.459916
false
false
false
false
yomajkel/RingGraph
RingGraph/RingGraph/RingGraphPainter.swift
1
4790
// // RingGraphPainter.swift // RingMeter // // Created by Michał Kreft on 30/03/15. // Copyright (c) 2015 Michał Kreft. All rights reserved. // import Foundation import UIKit internal class RignGraphPainter { let ringGraph: RingGraph let drawingRect: CGRect let geometry: Geometry let context: CGContext required init(ringGraph: RingGraph, drawingRect: CGRect, context: CGContext) { self.ringGraph = ringGraph self.drawingRect = drawingRect self.context = context geometry = Geometry(ringGraph: ringGraph, drawingSize: drawingRect.size) } func drawBackground() { for (index, ringMeter) in ringGraph.meters.enumerated() { context.saveGState() drawBackgroundRing(radius: geometry.radiusForIndex(index), meter: ringMeter) context.restoreGState() } } func drawForeground(animationState: RingGraphAnimationState) { for (index, ringMeter) in ringGraph.meters.enumerated() { let currentValue = CGFloat(animationState.meterValues[index]) let endAngle = geometry.angleForValue(currentValue) let radius = geometry.radiusForIndex(index) context.saveGState() func drawHalfForegroundRing() { let drawAngle = (endAngle > halfRingAngle ? halfRingAngle : endAngle) drawForegroundRing(radius: radius, startAngle: startAngle, endAngle: drawAngle, meter: ringMeter) } if (ringMeter.colors.count > 1) { context.beginTransparencyLayer(auxiliaryInfo: nil) drawHalfForegroundRing() drawGradient(fullRect: drawingRect, meterIndex: index) //TODO this method should take only gradient rect context.endTransparencyLayer() } else { drawHalfForegroundRing() } if (endAngle > halfRingAngle) { let sectionEndAngle = endAngle > shadowEndingAngle ? shadowEndingAngle : endAngle drawForegroundRing(radius: radius, startAngle: halfRingAngle, endAngle: sectionEndAngle, meter: ringMeter) } if (endAngle > shadowEndingAngle) { context.setShadow(offset: CGSize(width: 10, height: 0), blur: 5) drawForegroundRing(radius: radius, startAngle: shadowEndingAngle, endAngle: endAngle, meter: ringMeter) } context.restoreGState() } } } private extension RignGraphPainter { func drawBackgroundRing(radius: CGFloat, meter: RingMeter) { let color = meter.backgroundColor.cgColor context.setLineWidth(geometry.ringWidth) context.setLineCap(CGLineCap.round) context.setStrokeColor(color) context.addArc(center: geometry.centerPoint, radius: radius, startAngle: 0, endAngle: fullCircleRadians, clockwise: false) context.strokePath() } func drawForegroundRing(radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, meter: RingMeter) { let color = meter.colors.last!.cgColor context.setStrokeColor(color) context.setLineWidth(geometry.ringWidth) context.setLineCap(CGLineCap.round) context.addArc(center: geometry.centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false) context.strokePath() } func drawGradient(fullRect: CGRect, meterIndex: Int) { let colors = ringGraph.meters[meterIndex].colors context.setBlendMode(CGBlendMode.sourceIn) let num_locations :size_t = 2; let meterMultiplier = CGFloat(meterIndex + 1) let locations: [CGFloat] = [0.12 * meterMultiplier, 1 - 0.12 * meterMultiplier] let components: [CGFloat] = UIColor.gradientValuesFromColors(colors: colors) if let glossGradient = CGGradient(colorSpace: CGColorSpaceCreateDeviceRGB(), colorComponents: components, locations: locations, count: num_locations) { let topCenter = CGPoint(x: drawingRect.midX, y: 0.0) let midCenter = CGPoint(x: drawingRect.midX, y: drawingRect.maxY) context.clip(to: self.rightGradientClipRect(drawRect: fullRect)) context.drawLinearGradient(glossGradient, start: topCenter, end: midCenter, options: []) } } func rightGradientClipRect(drawRect: CGRect) -> CGRect { var clipRect = drawRect let halfWidth = drawRect.midX let halfRingWidth = geometry.ringWidth / 2.0 clipRect.origin.x = halfWidth - halfRingWidth clipRect.size.width = halfWidth + halfRingWidth return clipRect } }
mit
99a9ee31e3294bed4908d9428ee18f9c
39.235294
159
0.64411
4.797595
false
false
false
false
mendesbarreto/IOS
UICollectionInUITableViewCell/UICollectionInUITableViewCell/DaysUICollectionView.swift
1
3440
// // DaysUICollectionView.swift // UICollectionInUITableViewCell // // Created by Douglas Barreto on 2/23/16. // Copyright © 2016 CoderKingdom. All rights reserved. // import UIKit public class DaysUICollectionView: UICollectionView , UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{ public var week:Week? //public let signal:Signal<Day> = Signal<Day>() public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.registerCell() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) registerCell() } let SMEPGiPadViewControllerCellWidth:Int = 48; // public func collectionView(collectionView: UICollectionView, // layout collectionViewLayout: UICollectionViewLayout, // sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { // let kWhateverHeightYouWant:CGFloat = 100 // return CGSizeMake(collectionView.bounds.size.width, kWhateverHeightYouWant) // } // public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { // let numberOfCells = 7 // // // let edgeInsets:Int = (Int(self.frame.size.width) - (numberOfCells * SMEPGiPadViewControllerCellWidth)) / (numberOfCells + 1) // // // return UIEdgeInsetsMake(0, 40, 0, 40) // } public func registerCell() { self.delegate = self self.dataSource = self let nib = UINib(nibName: "DayCollectionViewCell", bundle:nil) self.registerNib(nib, forCellWithReuseIdentifier: "DayCollectionViewCell") self.backgroundColor = UIColor.whiteColor() } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 7 } public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let dayCell: DayCollectionViewCell = cell as! DayCollectionViewCell if let week = self.week { let weekDay = NSDate().weekday() let day:Day = week.days[indexPath.row] //print( day.description() ) dayCell.dayNumberLabel?.text = String(day.number) dayCell.weekDayLabel?.text = String(day.namePrefix) if day.date.isWeekDay(weekDay) { dayCell.selected = true self.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.None) } } } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print(week?.days[indexPath.row].date) } public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell:DayCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("DayCollectionViewCell", forIndexPath: indexPath) as! DayCollectionViewCell //cell.backgroundColor = UIColor.random() return cell } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let cellWidth:CGFloat = collectionView.bounds.size.width / 7; return CGSize(width: cellWidth, height: 64) } }
mit
b825fff1062cb41ded0cf66c037c8408
32.715686
173
0.768828
4.513123
false
false
false
false
EvgenyKarkan/Feeds4U
iFeed/Sources/UI/Components/FeedList/EVKFeedListViewController+Search.swift
1
3077
// // EVKFeedListViewController+Search.swift // iFeed // // Created by Julius Bahr on 20.04.18. // Copyright © 2018 Evgeny Karkan. All rights reserved. // import UIKit extension EVKFeedListViewController { @objc func searchPressed (_ sender: UIButton) { assert(!sender.isEqual(nil), "sender is nil") let waitingSpinner = UIActivityIndicatorView(style: .whiteLarge) waitingSpinner.frame = CGRect(x: 120, y: 200, width: 37, height: 37) waitingSpinner.startAnimating() view.addSubview(waitingSpinner) search.fillMatchingEngine { DispatchQueue.main.async { waitingSpinner.stopAnimating() waitingSpinner.removeFromSuperview() self.showEnterSearch() } } } func showEnterSearch() { let alertController = UIAlertController(title: "Search", message: "Search works best when you enter more than one word.", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in self.view.endEditing(true) } alertController.addAction(cancelAction) let nextAction = UIAlertAction(title: "Search", style: .default) { action -> Void in if let query = alertController.textFields?.first?.text, !query.isEmpty { self.search.search(for: query, resultsFound: { [weak self] (results) in DispatchQueue.main.async { guard let results = results, !results.isEmpty else { let noResultsFoundAlert = UIAlertController(title: "Search", message: "No results found", preferredStyle: .alert) let noResultsCancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) noResultsFoundAlert.addAction(noResultsCancelAction) self?.present(noResultsFoundAlert, animated: true, completion: nil) return } self?.showSearchResults(results: results, for: query) } }) } } alertController.addAction(nextAction) alertController.addTextField { textField -> Void in textField.placeholder = "Cute kittens" } let rootVConWindow = EVKBrain.brain.presenter.window.rootViewController rootVConWindow!.present(alertController, animated: true, completion: nil) } private func showSearchResults(results: [FeedItem], for query: String) { let feedItemsViewController = EVKFeedItemsViewController() feedItemsViewController.feedItems = results feedItemsViewController.searchTitle = "Search: \(query)" navigationController?.pushViewController(feedItemsViewController, animated: true) } }
mit
7cd02a9f8690c9fb0030d117cd150aa9
41.136986
141
0.5842
5.396491
false
false
false
false
plawanrath/DrawingApp_iOS_Swift
DrawingApp/DrawView.swift
1
1793
// // DrawView.swift // DrawingApp // // Created by Plawan Rath on 25/01/15. // Copyright (c) 2015 Plawan Rath. All rights reserved. // import UIKit class DrawView: UIView { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var lines = [Line]() //Important.. Was making array definition mistake... var lastPoint: CGPoint! var newPoint: CGPoint! var drawColor = UIColor.blackColor() override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { lastPoint = touches.anyObject()?.locationInView(self) //LastPoint is the point user last touched } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { newPoint = touches.anyObject()?.locationInView(self) //Where user moves the finger lines.append(Line(start: lastPoint, end: newPoint, color: drawColor)) lastPoint = newPoint self.setNeedsDisplay() } override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext() // CGContextBeginPath(context) CGContextSetLineCap(context, kCGLineCapRound) CGContextSetLineWidth(context, 5) for line in lines { CGContextBeginPath(context) CGContextMoveToPoint(context, line.startx, line.starty) CGContextAddLineToPoint(context, line.endx, line.endy) CGContextSetStrokeColorWithColor(context, line.color.CGColor) CGContextStrokePath(context) } // CGContextSetLineCap(context, kCGLineCapRound) //Make lines have a rounded end so looks smoother // CGContextSetRGBStrokeColor(context, 0, 0, 1, 1) // CGContextSetLineWidth(context, 5) // CGContextStrokePath(context) } }
mit
ea92f7826f9488bf3b954b8641cb2d26
33.480769
105
0.661461
4.755968
false
false
false
false
ilg/ElJayKit.swift
ElJayKit-Example/ElJayKit-ExampleTests/APITests.swift
1
5071
// // APITests.swift // ElJayKit-ExampleTests // // Created by Isaac Greenspan on 12/14/15. // Copyright © 2015 Isaac Greenspan. All rights reserved. // import XCTest import ElJayKit import Alamofire import VOKMockUrlProtocol private let APIExpectationTimeout: NSTimeInterval = 5000 class APITests: XCTestCase { static let manager: Manager = { VOKMockUrlProtocol.setTestBundle(NSBundle(forClass: APITests.self)) let mockConfig = Alamofire.Manager.sharedInstance.session.configuration var urlProtocolsToUse: [AnyClass] if let currentURLProtocols = mockConfig.protocolClasses { urlProtocolsToUse = currentURLProtocols } else { urlProtocolsToUse = [AnyClass]() } urlProtocolsToUse.insert(VOKMockUrlProtocol.self, atIndex: 0) mockConfig.protocolClasses = urlProtocolsToUse return Manager(configuration: mockConfig) }() func testLogin() { let expectation = expectationWithDescription("API Call Expectation") let api = API(server: .LiveJournal, username: "test_user", password: "password", manager: APITests.manager) api.login(callback: { result in defer { expectation.fulfill() } XCTAssert(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) guard let loginResult = result.value else { XCTFail() return } XCTAssertEqual(loginResult.fullName, "asLJ: LiveJournal Client for Mac OS X 10.5+") XCTAssertNil(loginResult.message) XCTAssertEqual(loginResult.useJournals, ["aslj_users", "lj_dev", "lj_nifty"]) XCTAssertEqual(loginResult.defaultPic.url.absoluteString, "http://l-userpic.livejournal.com/103439039/17800245") XCTAssertEqual(loginResult.userPics.first?.url.absoluteString, "http://l-userpic.livejournal.com/103439039/17800245") XCTAssertEqual(loginResult.userPics.first?.keywords, "asLJ") XCTAssertEqual(loginResult.userPics.last?.url.absoluteString, "http://l-userpic.livejournal.com/83760177/17800245") XCTAssertEqual(loginResult.userPics.last?.keywords, "asLJ (up to v0.6.3)") XCTAssertEqual(loginResult.friendGroups.last?.id, 5) XCTAssertEqual(loginResult.friendGroups.last?.isPublic, false) XCTAssertEqual(loginResult.friendGroups.last?.name, "Work") XCTAssertEqual(loginResult.friendGroups.last?.sortOrder, 50) XCTAssertEqual(loginResult.friendGroups.last?.bitMask, 0b100000) }) waitForExpectationsWithTimeout(APIExpectationTimeout, handler: { error in XCTAssertNil(error, "API call timed out") }) } func testGenerateSession() { let expectation = expectationWithDescription("API Call Expectation") let api = API(server: .LiveJournal, username: "test_user", password: "password", manager: APITests.manager) api.generateSession(callback: { result in XCTAssert(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) let session = result.value! XCTAssertEqual(session.ljSession, "v2:u17800245:s239:ayMTTTRXW9B:gc403c060ccb3222389b46dfa2bd083c80880ba0c//1") XCTAssertEqual(session.ljLoggedIn, "u17800245:s239") XCTAssertEqual(session.id, "s239") guard let sessionCookie = session.ljSessionCookie, let loggedInCookie = session.ljLoggedInCookie else { XCTFail() expectation.fulfill() return } XCTAssertEqual(sessionCookie.value, session.ljSession) XCTAssertEqual(sessionCookie.domain, ".livejournal.com") XCTAssertEqual(loggedInCookie.value, session.ljLoggedIn) XCTAssertEqual(loggedInCookie.domain, ".livejournal.com") expectation.fulfill() }) waitForExpectationsWithTimeout(APIExpectationTimeout, handler: { error in XCTAssertNil(error, "API call timed out") }) } func testExpireSession() { let expectation = expectationWithDescription("API Call Expectation") let api = API(server: .LiveJournal, username: "test_user", password: "password", manager: APITests.manager) api.expireSessions(callback: { result in XCTAssert(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) guard let value = result.value else { XCTFail() expectation.fulfill() return } XCTAssertEqual(value, NSNull()) expectation.fulfill() }) waitForExpectationsWithTimeout(APIExpectationTimeout, handler: { error in XCTAssertNil(error, "API call timed out") }) } }
mit
f0af60cf0b6b4a73d8d115553f3b6d61
41.966102
129
0.637081
4.865643
false
true
false
false
Polidea/RxBluetoothKit
ExampleApp/ExampleApp/Screens/CharacteristicNotify/CharacteristicNotifyView.swift
2
888
import UIKit class CharacteristicNotifyView: UIView { init() { super.init(frame: .zero) backgroundColor = .systemBackground setupLayout() } required init?(coder: NSCoder) { nil } // MARK: - Subviews let label: UILabel = { let label = UILabel() label.text = "Updated value: --" label.font = UIFont.systemFont(ofSize: 20.0) label.textColor = .green return label }() // MARK: - Private private func setupLayout() { label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: centerXAnchor), label.centerYAnchor.constraint(equalTo: centerYAnchor), label.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32) ]) } }
apache-2.0
e74065ebbf5100a7664d62397b1630ae
23.666667
87
0.618243
5.016949
false
false
false
false
msdgwzhy6/SwiftTask
Playgrounds/01-Sync.playground/Contents.swift
6
2020
//: Playground - noun: a place where people can play import Cocoa import XCPlayground // // NOTE: custom framework needs to be built first (and restart Xcode if needed) // // Importing Custom Frameworks Into a Playground // https://developer.apple.com/library/prerelease/ios/recipes/Playground_Help/Chapters/ImportingaFrameworkIntoaPlayground.html // import SwiftTask typealias Progress = Float typealias Value = String typealias Error = NSError typealias MyTask = Task<Progress, Value, Error> let myError = NSError(domain: "MyErrorDomain", code: 0, userInfo: nil) //-------------------------------------------------- // Example 1: Sync fulfilled -> success //-------------------------------------------------- let task = MyTask(value: "Hello") .success { value -> String in return "\(value) World" } .success { value -> String in return "\(value)!!!" } task.value //-------------------------------------------------- // Example 2: Sync rejected -> success -> failure //-------------------------------------------------- let task2a = MyTask(error: myError) .success { value -> String in return "Never reaches here..." } let task2b = task2a .failure { error, isCancelled -> String in return "ERROR: \(error!.domain)" // recovery from failure } task2a.value task2a.errorInfo task2b.value task2b.errorInfo //-------------------------------------------------- // Example 3: Sync fulfilled or rejected -> then //-------------------------------------------------- // fulfills or rejects immediately let task3a = MyTask { progress, fulfill, reject, configure in if arc4random_uniform(2) == 0 { fulfill("Hello") } else { reject(myError) } } let task3b = task3a .then { value, errorInfo -> String in if let errorInfo = errorInfo { return "ERROR: \(errorInfo.error!.domain)" } return "\(value!) World" } task3a.value task3a.errorInfo task3b.value task3b.errorInfo
mit
9ae9afa4d467d410abe5df28398ef366
24.56962
126
0.562376
4.372294
false
false
false
false
gzios/SystemLearn
SwiftBase/字符串.playground/Contents.swift
1
888
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let opration:String = "hello" for c in opration { print(c) } //两个字符串的拼接 let str1 = "我是谁" let str2 = "我是你大爷" let str3 = str1 + str2 //字符串和其他标识符的拼接 let name = "why" let age = 40 let height = 1.88 let info = "my name is \(name),my age is \(age),my height is \(height)" //字符串的格式化 let min = 2 let second = 8 let timeString = "0\(min):0\(second)" //拼接时间字符串 String(format:"%02d:%02d",arguments:[min,second]); //字符串截取 let urlString = "www.baidu.com" let header = (urlString as NSString).substring(to: 3); let middle = (urlString as NSString).substring(with: NSMakeRange(4, 5)); let footer = (urlString as NSString).substring(from: 10); let b = 10 var a = 5 a=b print(b)
apache-2.0
7f590ef51f5ed35cab9e1c2b9a7d7953
11.603175
72
0.653652
2.805654
false
false
false
false
amoriello/trust-line-ios
Trustline/Token.swift
1
17736
// // Token.swift // Trustline // // Created by matt on 10/10/2015. // Copyright © 2015 amoriello.hutti. All rights reserved. // import Foundation import CoreBluetooth import CryptoSwift import CoreData private let kHexChars = Array("0123456789abcdef".utf8) as [UInt8]; extension NSData { public func hexString() -> String { guard length > 0 else { return "" } let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: length) var output = [UInt8](count: length*2 + 1, repeatedValue: 0) var i: Int = 0 for b in buffer { let h = Int((b & 0xf0) >> 4) let l = Int(b & 0x0f) output[i++] = kHexChars[h] output[i++] = kHexChars[l] } return String.fromCString(UnsafePointer(output))! } } class Token { // MARK - Type definitions typealias CompletionHandler = (error: NSError?) -> (Void) typealias DataCompletionHandler = (data: [UInt8], error: NSError?) -> (Void) typealias RetrievePasswordHandler = (clearPassword: String, error: NSError?) -> (Void) typealias DecryptAccountHandler = (account: CDAccount?, error: NSError?) -> (Void) // MARK - Variable on init var centralManager: CBCentralManager var tokenPeriperal: CBPeripheral var tokenPeriperalProtocolImpl = TokenPeripheralProtocolImpl() var identifier: NSUUID var tokenCommander: TokenCommander! var keyMaterial: KeyMaterial! // MARK - member varibales var isConnected = false var connectHandler :CompletionHandler? var connectionStateHandler: BleManager.ManagerStateErrorHandler init(centralManager: CBCentralManager, peripheral: CBPeripheral, identifier: NSUUID, keyMaterial: KeyMaterial? = nil, connectionStateHandler: BleManager.ManagerStateErrorHandler) { self.centralManager = centralManager self.tokenPeriperal = peripheral self.tokenPeriperal.delegate = self.tokenPeriperalProtocolImpl self.connectionStateHandler = connectionStateHandler self.identifier = identifier if (keyMaterial != nil) { // Use the given one self.keyMaterial = keyMaterial } else { // This is a new token, create a new KeyMaterial dedicated to this token self.keyMaterial = KeyMaterial() } self.tokenCommander = TokenCommander(keyMaterial: self.keyMaterial, protocolImpl: tokenPeriperalProtocolImpl) } func setKeyMaterial(keyMaterial: KeyMaterial) { self.keyMaterial = keyMaterial // reset commander with new material self.tokenCommander = TokenCommander(keyMaterial: self.keyMaterial!, protocolImpl: tokenPeriperalProtocolImpl) } func connect(hanlder: CompletionHandler) { self.tokenPeriperalProtocolImpl.connectionHandler = self.connectHandlerHook self.connectHandler = hanlder; self.centralManager.connectPeripheral(tokenPeriperal, options: nil); } func pair(handler: CompletionHandler) { tokenCommander.PairWithDevice(handler) } func createPassword(strength: UInt8, handler: DataCompletionHandler) { tokenCommander.CreatePassword(strength, handler: handler) } func writePassword(password: [UInt8], additionalKeys: [UInt8]? = nil, handler: CompletionHandler) { tokenCommander.keystrokesPassword(password, additionalKeys: additionalKeys, handler: handler) } func resetNewKeys(keyMaterialFromQrCode keyMaterial: KeyMaterial, handler: CompletionHandler) { tokenCommander.resetNewKeys(keyMaterial, handler: handler) } func retrievePassword(password: [UInt8], handler: RetrievePasswordHandler) { tokenCommander.retrievePassword(password, handler: handler) } func decryptAccount(encryptedAccount: CDAccount, handler: DecryptAccountHandler) { // not implemented yet return handler(account: nil, error: createError("Error", description: "Not implemented yet")) } func connectHandlerHook(error: NSError?) { if let _ = error { isConnected = false; } else { isConnected = true; } // in case of connect, call user handler if let _ = connectHandler { connectHandler!(error: error) } connectionStateHandler(error) } } class TokenCommander { // MARK - Type definitions typealias ResponseHandler = (Response, error: NSError?) -> (Void) typealias CreatePasswordHandler = (cipheredPassword:[UInt8], error: NSError?) -> (Void) typealias RetrievePasswordHandler = (clearPassword: String, error: NSError?) -> (Void) typealias PairWithDeviceHandler = (NSError?) -> (Void) typealias CompletionHandler = (NSError?) -> (Void) typealias AuthCmdHandler = (nonce: [UInt8], error: NSError?) -> (Void) typealias LoginKeyHandler = (loginKey: [UInt8], error: NSError?) -> (Void) var passKey = [UInt8]() var keyMaterial :KeyMaterial var protocolImpl :TokenPeripheralProtocolImpl init(keyMaterial: KeyMaterial, protocolImpl: TokenPeripheralProtocolImpl) { self.keyMaterial = keyMaterial; self.protocolImpl = protocolImpl; } func PairWithDevice(handler: PairWithDeviceHandler) { let cmd = Command(cmdId: Command.Id.Pair, arg: [UInt8]())!; self.send(cmd) { (response, error) -> (Void) in if let _ = error { handler(error); return; } if response.isValid() { // Token is Paired let keySize = self.keyMaterial.keySize; let passKey = Array(response.bytes[2...1 + keySize]) let crKey = Array(response.bytes[2 + (1 * keySize)...1 + (2 * keySize)]) let comKey = Array(response.bytes[2 + (2 * keySize)...1 + (3 * keySize)]) let loginKey = Array(response.bytes[2 + (3 * keySize)...1 + (4 * keySize)]) self.keyMaterial.passKey = NSData(bytes: passKey, length: passKey.count) self.keyMaterial.crKey = NSData(bytes: crKey, length: crKey.count) self.keyMaterial.comKey = NSData(bytes: comKey, length: comKey.count) self.keyMaterial.loginKey = NSData(bytes: loginKey, length: loginKey.count) print("Pass Key: \(self.keyMaterial.passKey)"); print("Cr Key: \(self.keyMaterial.crKey)"); print("Req Key: \(self.keyMaterial.comKey)"); print("Login Key: \(self.keyMaterial.comKey)"); handler(nil); return; } handler(createError("Pairing Failed", description: "Invalid Response", status: response.status())) } } func CreatePassword(length: UInt8, handler: CreatePasswordHandler) { if length > 63 { let error = createError("Create Password Failed", description: "Invalid password size", status: Response.Status.InvalidArgument) handler(cipheredPassword: [UInt8](), error: error) return; } let arg:[UInt8] = [length]; let cmd = Command(cmdId: Command.Id.CreatePassword, arg: arg)! send(cmd) { (response, error) in if let _ = error { let cipherPassword = [UInt8]() handler(cipheredPassword: cipherPassword, error: error) return } let cipheredPassword = response.argData()! handler(cipheredPassword: cipheredPassword, error: error); } } func keystrokesPassword(password: [UInt8], additionalKeys: [UInt8]? = nil, handler: CompletionHandler) { var cmd :Command! if let addKeys = additionalKeys { var arg = password; arg.appendContentsOf(addKeys) cmd = Command(cmdId: .TypePassword, arg: arg)! } else { cmd = Command(cmdId: .TypePassword, arg: password)! } send(cmd) { (reponse, error) in handler(error) } } func retrievePassword(password: [UInt8], handler: RetrievePasswordHandler) { let cmd = Command(cmdId: .ReturnPassword, arg: password)! send(cmd) { (response, error) in if error != nil { handler(clearPassword: "", error: error) return } let argDataSize = response.argData()!.count if argDataSize != 80 { let error = createError("Invalid response", description: "Bad response length") handler(clearPassword: "", error: error) return } let iv = Array(response.argData()![0...self.keyMaterial.keySize - 1]) let cipheredPassword = Array(response.argData()![16...argDataSize - 1]) do { let clearData :[UInt8] = try AES(key: self.keyMaterial.comKey.arrayOfBytes(), iv: iv)!.decrypt(cipheredPassword) // remove trailing zeros let data = clearData.filter { $0 != 0 } let clearPassword = String(bytes: data, encoding: NSUTF8StringEncoding)! handler(clearPassword: clearPassword, error: nil) return } catch { let error = createError("Invalid response", description: "Bad cryptographic input") handler(clearPassword: "", error: error) } } } func retreiveLoginKey(handler: LoginKeyHandler) { let cmd = Command(cmdId: .ReturnLoginKey)! send(cmd) { (response, error) in if error != nil { handler(loginKey: [UInt8](), error: error) return } let argSize = response.argData()!.count let expectedArgSize = 2 * self.keyMaterial.keySize // IV + Encrypted Key. if argSize != expectedArgSize { let error = createError("Invalid response", description: "Bad response length") handler(loginKey: [UInt8](), error: error) return } let iv = Array(response.argData()![0...self.keyMaterial.keySize - 1]) let cipheredLoginKey = Array(response.argData()![16...argSize - 1]) do { let loginKey : [UInt8] = try AES(key: self.keyMaterial.comKey.arrayOfBytes(), iv: iv)!.decrypt(cipheredLoginKey) self.keyMaterial.loginKey = NSData(bytes: loginKey, length: self.keyMaterial.keySize) handler(loginKey: loginKey, error: nil) } catch { let error = createError("Invalid response", description: "Bad cryptographic input") handler(loginKey: [UInt8](), error: error) } } } func resetNewKeys(keyMaterial: KeyMaterial, handler: CompletionHandler) { let cmd = Command(cmdId: .ResetKeys, arg: keyMaterial.fullData())! send(cmd) { (response, error) in handler(error) } } func send(cmd: Command, handler: ResponseHandler) { if let needAuth = cmd.needAuth() { if (needAuth) { doSendCmdAuth(cmd, handler: handler); } else { doSend(cmd, handler: handler); } } } private func prepareAuthCmd(handler: AuthCmdHandler) { let cmd = Command(cmdId: Command.Id.CreateChallenge, arg: [UInt8]())!; self.doSend(cmd) { (response, error) in if let _ = error { handler(nonce: [UInt8](), error: error); return; } let nonce = Array(response.bytes[2...9]); print("Challenge: \(nonce)"); handler(nonce: nonce, error: error); } } private func doSendCmdAuth(cmd: Command, handler: ResponseHandler) { prepareAuthCmd { (nonce, error) in if let _ = error { handler(Response(), error: error); return; } cmd.setSecurityToken(nonce, key: self.keyMaterial.crKey.arrayOfBytes()); self.doSend(cmd, handler: handler); } } private func doSend(cmd: Command, handler: ResponseHandler) { let data = NSMutableData(bytes: cmd.bytes, length: cmd.bytes.count) protocolImpl.asyncWriteData(data, handler: handler); } } class TokenPeripheralProtocolImpl : NSObject, CBPeripheralDelegate { typealias ResponseHandler = (Response, error: NSError?) -> (Void); typealias ConnectionHandler = BleManager.ManagerStateErrorHandler private var handler: ResponseHandler? private class ReadCtx { var bytesRead = 0 var missingBytes = 0 var needAck = false; } private class WriteCtx { var bytesSent = 0; var isAckCond = NSCondition(); var isWaitingAck = false; var isAck = false; } private var connectionHandler :ConnectionHandler! private var tokenPeripheral:CBPeripheral! private var tokenReadCharacteristic:CBCharacteristic! private var tokenWriteCharacteristic:CBCharacteristic! private var dispatchQueue: dispatch_queue_t; private var currentResponse = Response() private var bleReady = false; let kMaxBurst = 15; private var rCtx: ReadCtx; private var wCtx: WriteCtx; override init() { rCtx = ReadCtx(); wCtx = WriteCtx(); dispatchQueue = dispatch_queue_create("BleQueue", nil); super.init(); } func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { if let _ = error { connectionHandler(error) return } // @todo Check if periperal is real token peripheral tokenPeripheral = peripheral; for service in peripheral.services! { print("Discovered service UUID: \(service.UUID)") peripheral.discoverCharacteristics(nil, forService: service) } } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { if error != nil { print("Error characteristics for service") return } for characteristic in service.characteristics! { switch characteristic.UUID { case g_tokenReadCharacteristicUUID: print("Found Read characteristic") tokenReadCharacteristic = characteristic tokenPeripheral.setNotifyValue(true, forCharacteristic: characteristic); case g_tokenWriteCharacteristicUUID: print("Found Write characteristic") tokenWriteCharacteristic = characteristic default: continue } } if (tokenReadCharacteristic != nil && tokenWriteCharacteristic != nil && !bleReady) { bleReady = true; connectionHandler(nil); } } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { if (peripheral == tokenPeripheral && characteristic == tokenReadCharacteristic) { if let value = characteristic.value { onReceivedData(value, error: error); } } } func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { if (peripheral == tokenPeripheral && characteristic == tokenWriteCharacteristic) { onWriteData(error) } } func asyncWriteData(data: NSData, handler: ResponseHandler) { // Init context self.handler = handler; currentResponse = Response(); rCtx = ReadCtx(); wCtx = WriteCtx(); dispatch_async(dispatchQueue, { [weak self] in self!.doWriteData(data); }); } private func onReceivedData(data: NSData, error: NSError?) { if let err = error { // Re-initialize context rCtx = ReadCtx(); wCtx = WriteCtx(); currentResponse = Response(); async { self.handler!(Response(), error: err); } return; } if data.length == 1 && wCtx.isWaitingAck { // Wait for ack wCtx.isAck = true; wCtx.isAckCond.signal(); return; } rCtx.bytesRead += data.length; currentResponse.appendBytes(data); if (rCtx.bytesRead == kMaxBurst) { let ack :UInt8 = (UInt8)(rCtx.bytesRead); rCtx.bytesRead = 0; let ackNSData = NSData(bytes: [ack], length: 1) writeDataToBle(ackNSData, type: .WithoutResponse); } if (currentResponse.isComplete()) { rCtx = ReadCtx(); wCtx = WriteCtx(); let responseCopy = currentResponse; currentResponse = Response(); if responseCopy.isValid() { async { self.handler!(responseCopy, error: nil) } } else { let error = createError("Command Error", description: "Todo: Description here code \(responseCopy.status().rawValue)") async { self.handler!(Response(), error: error) } } } } func onWriteData(error: NSError?) { if let err = error { print("Error while writing to the token: \(err.description)"); return; } print("data wrote!"); } private func waitAck() -> Bool { let maxCycles = 5; var cycles = 0; wCtx.isAckCond.lock(); wCtx.isWaitingAck = true; while !wCtx.isAck && cycles < maxCycles { wCtx.isAckCond.waitUntilDate(NSDate(timeIntervalSinceNow: NSTimeInterval(1))); ++cycles } wCtx.isAckCond.unlock(); wCtx.isWaitingAck = false; return wCtx.isAck; } private func doWriteData(data :NSData) { var size = data.length; var session_bytes_sent = 0; while size > 0 { let bytes_to_write = min(size, kMaxBurst - wCtx.bytesSent); let rangeToSend = NSRange(location: session_bytes_sent, length: bytes_to_write) let bytesToSend = data.subdataWithRange(rangeToSend) writeDataToBle(bytesToSend); size -= bytes_to_write; wCtx.bytesSent += bytes_to_write; session_bytes_sent += bytes_to_write; if (wCtx.bytesSent == kMaxBurst) { if waitAck() { wCtx.bytesSent = 0; wCtx.isAck = false; } else { print("No ack for write"); async { self.handler!(Response(), error: createError("Protocol", description: "Error during communication")) } break; } } } } func writeDataToBle(data: NSData, type: CBCharacteristicWriteType = .WithoutResponse) { tokenPeripheral.writeValue(data, forCharacteristic: tokenWriteCharacteristic, type: type); } private func async(handler: () -> (Void)) { dispatch_async(dispatch_get_main_queue(), handler) } }
mit
4bcdb32771907fb7bb9494e827738e6d
29.061017
183
0.650296
4.244854
false
false
false
false
nkirby/Humber
Humber/_src/View Controller/Single Stats/OverviewItemSingleStatViewController.swift
1
3926
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import Async import SnapKit import HMCore import HMGithub // ======================================================= class OverviewItemSingleStatViewController: UIViewController { internal var itemModel: GithubOverviewItemModel? private let countLabel = UILabel(frame: CGRect.zero) private let titleLabel = UILabel(frame: CGRect.zero) private let descriptionLabel = UILabel(frame: CGRect.zero) override func viewDidLoad() { super.viewDidLoad() self.setupSubviews() self.fetch() self.sync() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setupSubviews() { self.view.addSubview(self.countLabel) self.view.addSubview(self.titleLabel) self.view.addSubview(self.descriptionLabel) self.countLabel.translatesAutoresizingMaskIntoConstraints = false self.titleLabel.translatesAutoresizingMaskIntoConstraints = false self.descriptionLabel.translatesAutoresizingMaskIntoConstraints = false self.view.clipsToBounds = true self.descriptionLabel.numberOfLines = 0 self.descriptionLabel.snp_makeConstraints { make in make.width.equalTo(self.view).offset(-20.0) make.centerX.equalTo(0) make.bottom.equalTo(-20.0) } self.titleLabel.snp_makeConstraints { make in make.width.equalTo(self.view).offset(-20.0) make.centerX.equalTo(0) make.bottom.equalTo(self.descriptionLabel.snp_top).offset(-8.0) } self.countLabel.snp_makeConstraints { make in make.width.equalTo(self.view) make.centerX.equalTo(0) make.top.equalTo(20.0) } } private func fetch() { guard let model = self.itemModel else { return } let centerParagraphStyle = NSMutableParagraphStyle() centerParagraphStyle.alignment = NSTextAlignment.Center Async.main { self.titleLabel.attributedText = NSAttributedString(string: model.title, attributes: [ NSFontAttributeName: Theme.font(type: .Bold(11.0)), NSParagraphStyleAttributeName: centerParagraphStyle, NSForegroundColorAttributeName: Theme.color(type: .PrimaryTextColor) ]) self.descriptionLabel.attributedText = NSAttributedString(string: "\(model.action): \(model.repoOwner)/\(model.repoName)", attributes: [ NSFontAttributeName: Theme.font(type: .Regular(10.0)), NSParagraphStyleAttributeName: centerParagraphStyle, NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor) ]) self.countLabel.attributedText = NSAttributedString(string: "\(model.value)", attributes: [ NSFontAttributeName: Theme.font(type: .Bold(44.0)), NSParagraphStyleAttributeName: centerParagraphStyle, NSForegroundColorAttributeName: Theme.color(type: .TintColor) ]) } } internal func sync() { guard let model = self.itemModel else { return } ServiceController.component(GithubOverviewSyncProviding.self)?.syncOverviewItem(itemID: model.itemID).startWithNext { if let obj = ServiceController.component(GithubOverviewDataProviding.self)?.overviewItem(itemID: model.itemID) { self.itemModel = obj } self.fetch() } } }
mit
6959549c9fd3b11b69ab53e09109b373
35.018349
148
0.605196
5.576705
false
false
false
false
caoimghgin/HexKit
Pod/Classes/Tile.swift
1
5882
// // Tile.swift // https://github.com/caoimghgin/HexKit // // Copyright © 2015 Kevin Muldoon. // // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import UIKit public func ==(lhs: Tile, rhs: Tile) -> Bool {return lhs.hashValue == rhs.hashValue} public func <(lhs: Tile, rhs: Tile) -> Bool {return lhs.delta < rhs.delta} /// Tile that holds a hexagon public class Tile: Equatable, Hashable, Comparable, CustomStringConvertible { /** Shape of hexagon in tile. - FlatTopped: Hexagon top is flat - PointTopped: Hexagon top is point */ public enum Shape : Int { case FlatTopped case PointTopped } public var hex : Hex! public var center : Point! public var hashValue: Int {return "\(self.hex.r),\(self.hex.q)".hashValue} var offset : Coord! var cube : Cube! var size : Size! var radius : Double! var shape : Shape! var delta : Double! var units = [Unit]() var ø : Double {get {return (self.shape == Tile.Shape.PointTopped ? self.size.width : self.size.height)}} var Ø : Double {get {return (self.shape == Tile.Shape.PointTopped ? self.size.height : self.size.width)}} public var hexCorners : Array<Point> { get { var result = Array<Point>() for var i = 0; i <= 6; ++i { let center = Point.zeroPoint() let angle_deg = ( (self.shape == Tile.Shape.FlatTopped) ? 60 * Double(i) : 60 * Double(i) + 30 ) let angle_rad = M_PI / 180 * angle_deg let x = Double(center.x) + self.radius * cos(angle_rad); let y = Double(center.y) + self.radius * sin(angle_rad); result.append( Point(x: x + self.center.x, y: y + self.center.y) ) } return result } } var rect : Rect { get { let origin = Point(x: center.x - (size.width/2), y: center.y - (size.height/2)) return Rect(origin:origin, size: size) } } var keyValue : String { get { return Tile.keyFormat(q: self.hex.q, r: self.hex.r) } } public var description: String {return "Tile.\(self.hex) Key:(\(self.keyValue))"} init () {} init (cube : Cube, center: Point, size : Size, shape: Shape, radius: Double) { self.size = size self.center = center self.shape = shape self.radius = radius self.cube = cube self.offset = Coord.Convert(cube) self.hex = Hex.Convert(cube) } internal func removeUnit(unit:Unit) { units = units.filter() { $0 !== unit } } internal func addUnit(unit:Unit) { self.units.insert(unit, atIndex: self.units.count) } internal func sendUnitToBack(unit:Unit) { if units.contains(unit) { units = units.filter() { $0 !== unit } self.units.append(unit) } } internal func sendUnitToFront(unit:Unit) { if units.contains(unit) { units = units.filter() { $0 !== unit } self.units.insert(unit, atIndex: 0) } } internal func unitsVisible(flag : Bool) { var alpha : CGFloat = 0 if (flag == true) {alpha = 1} for unit in units { UIView .animateWithDuration(0.35, animations: { () -> Void in unit.alpha = alpha }) } } internal func alliance() -> Unit.Alliance { if (self.units.count == 0) { return Unit.Alliance.Uncontested } else { let unit = self.units.first return (unit?.alliance)! } } internal func hostile(alliance : Unit.Alliance) -> Bool { return false } internal func hostileNeighbors() -> Bool { if (self.alliance() == Unit.Alliance.Uncontested) { return false } else { for neighbor in self.neighbors() { if (neighbor.alliance() != Unit.Alliance.Uncontested && self.alliance() != neighbor.alliance()) { return true } } } return false } public func neighbors() -> [Tile] { return HexKit.sharedInstance.neighbors(self) } public func occupyingUnitsDetail() -> String { var info = "" for unit in self.units { info = info+"\r"+unit.description } return info } public func occupied() -> Bool { return (units.count > 0) ? true : false } class func keyFormat(q q:Int, r:Int) -> String { return String(format: "%03dx%03d", arguments: [q, r]) } }
mit
648a653205551f06a95dd0805ac3d349
31.307692
113
0.576118
4.04055
false
false
false
false
a2/RxSwift
RxTests/RxSwiftTests/Tests/VariableTest.swift
11
2763
// // VariableTest.swift // RxTests // // Created by Krunoslav Zaher on 5/2/15. // // import Foundation import XCTest import RxSwift class VariableTest : RxTest { func testVariable_initialValues() { let a = Variable(1) let b = Variable(2) let c = combineLatest(a, b, +) var latestValue: Int? let subscription = c .subscribeNext { next in latestValue = next } XCTAssertEqual(latestValue!, 3) a.value = 5 XCTAssertEqual(latestValue!, 7) b.value = 9 XCTAssertEqual(latestValue!, 14) subscription.dispose() a.value = 10 XCTAssertEqual(latestValue!, 14) } func testVariable_Completed() { var a = Variable(1) var b = Variable(2) let c = combineLatest(a, b, +) var latestValue: Int? var completed = false let subscription = c.subscribe(next: { next in latestValue = next }, completed: { completed = true }) XCTAssertEqual(latestValue!, 3) a.value = 5 XCTAssertEqual(latestValue!, 7) XCTAssertTrue(!completed) a = Variable(0) b = Variable(0) XCTAssertTrue(completed) } func testVariable_READMEExample() { // Two simple Rx variables // Every variable is actually a sequence future values in disguise. let a /*: Observable<Int>*/ = Variable(1) let b /*: Observable<Int>*/ = Variable(2) // Computed third variable (or sequence) let c /*: Observable<Int>*/ = combineLatest(a, b) { $0 + $1 } // Reading elements from c. // This is just a demo example. // Sequence elements are usually never enumerated like this. // Sequences are usually combined using map/filter/combineLatest ... // // This will immediatelly print: // Next value of c = 3 // because variables have initial values (starting element) var latestValueOfC : Int? = nil // let _ = doesn't retain. let d/*: Disposable*/ = c .subscribeNext { c in //print("Next value of c = \(c)") latestValueOfC = c } .scopedDispose XCTAssertEqual(latestValueOfC!, 3) // This will print: // Next value of c = 5 a.value = 3 XCTAssertEqual(latestValueOfC!, 5) // This will print: // Next value of c = 8 b.value = 5 XCTAssertEqual(latestValueOfC!, 8) } }
mit
f4e4b277cf5c0dc4777ad6153f585ecc
23.891892
76
0.51502
4.873016
false
true
false
false
gewill/Feeyue
Feeyue/AppDelegate.swift
1
4893
// // AppDelegate.swift // Feeyue // // Created by Will on 1/13/16. // Copyright © 2016 gewill.org. All rights reserved. // import UIKit import Fabric import Crashlytics import Kingfisher import RealmSwift import QMUIKit import TwitterKit #if DEBUG // import FLEX // import GDPerformanceView_Swift #endif @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window!.makeKeyAndVisible() // QMUIKit config QMUICMI() // QD自定义的全局样式渲染 QDCommonUI.renderGlobalAppearances() // 预加载 QQ 表情,避免第一次使用时卡顿 DispatchQueue.global().async { QDUIHelper.qmuiEmotions() } // // 临时清空数据库 // WeiboStore.deleteAllRealmData() // // 临时清空图片缓存 // KingfisherManager.shared.cache.clearMemoryCache() // KingfisherManager.shared.cache.clearDiskCache() delay(0.5) { #if DEBUG // FLEXManager.shared().isNetworkDebuggingEnabled = true //// FLEXManager.sharedManager().showExplorer() // // GDPerformanceMonitor.sharedInstance.startMonitoring() { (textLabel) in // textLabel?.backgroundColor = UIColor(hexString: "#14887D") // textLabel?.textColor = .white // textLabel?.layer.borderColor = UIColor(hexString: "#14887D").cgColor // } #endif // self.migrationToNewestRealmsChemaVersion() // Setup Crashlytics Fabric.with([Crashlytics.self]) TWTRTwitter.sharedInstance().start(withConsumerKey: TwitterConsumerKey, consumerSecret: TwitterConsumerSecect) // print simulator Document Path #if arch(i386) || arch(x86_64) let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) [0] print("Document Path: \(documentsPath))") #endif GWHUD.setMinimumDismissTimeInterval(2) // Disable autolayout constraint error messages in debug console output in Xcode UserDefaults.standard.setValue(false, forKey: "_UIConstraintBasedLayoutLogUnsatisfiable") } if AccountManager.shared.getWeiboToken() == "" { showIntroScene() } else { showMainScene() } // showTestScene() return true } //仅支持iOS9以上系统,iOS8及以下系统不会回调 func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { if TWTRTwitter.sharedInstance().application(app, open: url as URL, options: options) { return TWTRTwitter.sharedInstance().application(app, open: url, options: options) } return true } // 支持所有iOS系统 // 建议使用的系统openURL回调,且 新浪 平台仅支持以上回调。 func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return true } // 支持目前所有iOS系统 func application(_ application: UIApplication, handleOpen url: URL) -> Bool { return true } // MARK: - Change scene var isShowingMainScene: Bool = true func showIntroScene() { let vc = R.storyboard.account.introViewController() self.window?.rootViewController = vc isShowingMainScene = false } func showMainScene() { let tabBarControllerConfig = JLXMainTabBarControllerConfig() self.window?.rootViewController = tabBarControllerConfig.aTabBarController isShowingMainScene = true } func showTestScene() { let vc = TwitterUserViewController.create(userId: "27817880") self.window?.rootViewController = vc isShowingMainScene = false } // MARK: - Migration objects in Realm // func migrationToNewestRealmsChemaVersion() { // // Realm.Configuration.defaultConfiguration = Realm.Configuration( // schemaVersion: 1, // migrationBlock: { (migration, oldSchemaVersion) -> Void in // if (oldSchemaVersion < 1) { // migration.enumerate(WeiboAccount.className(), { (oldObject, newObject) -> Void in // }) // migration.enumerate(Comment.className(), { (oldObject, newObject) -> Void in // }) // } // print("Migration complete.") // }) // } }
mit
2978197edaa827765fb8376a0de0b070
28.949045
145
0.622501
4.716148
false
false
false
false
outfoxx/CryptoSecurity
Sources/OID.swift
1
2485
// // OID.swift // CryptoSecurity // // Copyright © 2019 Outfox, inc. // // // Distributed under the MIT License, See LICENSE for details. // import Foundation public struct OID { /// See: http://oid-info.com/get/{oid} public static let commonName = ASN1.oid(of: 2, 5, 4, 3) public static let serialNumber = ASN1.oid(of: 2, 5, 4, 5) public static let countryName = ASN1.oid(of: 2, 5, 4, 6) public static let localityName = ASN1.oid(of: 2, 5, 4, 7) public static let stateOrProvinceName = ASN1.oid(of: 2, 5, 4, 8) public static let organizationName = ASN1.oid(of: 2, 5, 4, 10) public static let organizationUnitName = ASN1.oid(of: 2, 5, 4, 11) public static let userId = ASN1.oid(of: 0, 9, 2342, 19200300, 100, 1, 1) public static let rsaEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 1) public static let sha1WithRSAEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 5) public static let sha256WithRSAEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 11) public static let sha384WithRSAEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 12) public static let sha512WithRSAEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 13) public static let sha224WithRSAEncryption = ASN1.oid(of: 1, 2, 840, 113549, 1, 1, 14) public static let extensionRequest = ASN1.oid(of: 1, 2, 840, 113549, 1, 9, 14) public static let extensionKeyUsage = ASN1.oid(of: 2, 5, 29, 15) public static func OIDFromRDNId(id: String) -> ASN1ObjectIdentifier { switch id { case "CN": return OID.commonName case "C": return OID.countryName case "O": return OID.organizationName case "OU": return OID.organizationUnitName case "UID": return OID.userId case "SN": return OID.serialNumber default: fatalError("Unsupported RDN ID") } } public static func RDNIdFromOID(oid: ASN1ObjectIdentifier) -> String { if oid.value == commonName.value { return "CN" } if oid.value == countryName.value { return "C" } if oid.value == localityName.value { return "L" } if oid.value == stateOrProvinceName.value { return "ST" } if oid.value == organizationName.value { return "O" } if oid.value == organizationUnitName.value { return "OU" } if oid.value == userId.value { return "UID" } if oid.value == serialNumber.value { return "SN" } fatalError("Unsupported RDN ID") } }
mit
6c559f072f88e8a9a28781419176d56d
26
87
0.638486
3.213454
false
false
false
false
tardieu/swift
benchmark/single-source/StringBuilder.swift
5
780
//===--- StringBuilder.swift ----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils @inline(never) func buildString() -> String { var sb = "a" for str in ["b","c","d","pizza"] { sb += str } return sb } @inline(never) public func run_StringBuilder(_ N: Int) { for _ in 1...5000*N { _ = buildString() } }
apache-2.0
cbcfdb18be73c4d46e4d9b08b4b76967
25
80
0.551282
4.23913
false
false
false
false
wolfhous/haochang_swift
haochang_swift/haochang_swift/其他-other/Common.swift
1
340
// // Common.swift // haochang_swift // // Created by 壹号商圈 on 16/12/29. // Copyright © 2016年 com.houshuai. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH : CGFloat = 44 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height
mit
2f7500207b40a4efddb8616547c0c0eb
20.933333
56
0.720365
3.257426
false
false
false
false
davejlin/treehouse
swift/swift2/interactive-story/InteractiveStory/ViewController.swift
1
3340
// // ViewController.swift // InteractiveStory // // Created by Lin David, US-205 on 9/23/16. // Copyright © 2016 Lin David. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var nameTextFieldToStartAdventureVerticalContraint: NSLayoutConstraint! deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } enum Error: ErrorType { case NoName } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyBoardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyBoardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "startAdventure" { do { if let name = nameTextField.text { if name == "" { throw Error.NoName } if let pageController = segue.destinationViewController as? PageController { pageController.page = Adventure.story(name) } } } catch Error.NoName { let alertController = UIAlertController(title: "Name Not Provided", message: "Provide a name to start your story!", preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(action) presentViewController(alertController, animated: true, completion: nil) } catch let error { fatalError("\(error)") } } } func keyBoardWillShow(notification: NSNotification) { if let userInfoDictionary = notification.userInfo, let keyboardFrameValue = userInfoDictionary[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyboardFrame = keyboardFrameValue.CGRectValue() UIView.animateWithDuration(0.8) { self.nameTextFieldToStartAdventureVerticalContraint.constant = keyboardFrame.size.height + 10 self.view.layoutIfNeeded() } } } func keyBoardWillHide(notification: NSNotification) { UIView.animateWithDuration(0.8) { self.nameTextFieldToStartAdventureVerticalContraint.constant = 25 self.view.layoutIfNeeded() } } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
unlicense
c1bd41b7014d1330b776903944e5df07
37.37931
171
0.637317
5.857895
false
false
false
false
eebean2/DevTools
DevTools/Classes/DevConsole.swift
1
11126
/* * Console * * Created by Erik Bean on 5/2/17 * Copyright © 2018 Erik Bean */ import UIKit import AVKit import GLKit import SpriteKit import SceneKit internal enum PrintMethod { case devOnly, xcodeOnly, both } internal typealias ConsoleCompletion = (DevConsole) -> Void // Public in future versions private typealias BasicCompletion = () -> Void internal class DevConsole { //MARK:- Basic Variables private let superview: UIView! private var console: UITextView! private var background: UIView! private var setupComplete = false //MARK:- Public Settings public let isReadOnly: Bool! public private(set) var isFullscreen = false public var backgroundColor: UIColor = .black public var textColor: UIColor = .green public var warningColor: UIColor = .yellow public var errorColor: UIColor = .red public var diagColor: UIColor = .cyan public var textFieldColor: UIColor = .white public var textFieldTextColor: UIColor = .white public var fullscreenEnabled = true //MARK:- Init /// -warning: Currently not setup, please use (on: ...) or (on: ..., readOnly: ...) @available(*, introduced: 2.0) required public init(_ view: UIView, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.isReadOnly = readOnly self.superview = view self.setup() { DevCore.logDiag("Console is not finished, please do not use") completion(self) } } convenience public init(_ controller: UIViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(controller.view, readOnly: readOnly, completion: completion) } public convenience init(_ controller: UITableViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(controller.view, readOnly: readOnly, completion: completion) } public convenience init(_ controller: UICollectionViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(controller.view, readOnly: readOnly, completion: completion) } public convenience init(_ controller: UIPageViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(controller.view, readOnly: readOnly, completion: completion) } public convenience init(_ controller: AVPlayerViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(controller.view, readOnly: readOnly, completion: completion) } public convenience init(_ view: GLKView, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { let v: UIView = view self.init(v, readOnly: readOnly, completion: completion) } public convenience init(_ view: SKView, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { let v: UIView = view self.init(v, readOnly: readOnly, completion: completion) } public convenience init(_ scene: SKScene, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { let v: UIView = scene.view! self.init(v, readOnly: readOnly, completion: completion) } public required init(on view: UIView, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.isReadOnly = readOnly self.superview = view self.isFullscreen = true self.setup() { DevCore.logDiag("Required Init Fisned") completion(self) } } public convenience init(on controller: UIViewController, readOnly: Bool = false, completion: @escaping ConsoleCompletion) { self.init(on: controller.view, readOnly: readOnly, completion: completion) } //MARK:- Setup (private) private func setup(completion: BasicCompletion) { setupBackground() { // setupConsole() { setupComplete = true completion() // } } } private func setupBackground(completion: BasicCompletion) { if isFullscreen { background = UIView(frame: superview.frame) background.backgroundColor = .clear superview.addSubview(background) var frame = CGRect() if superview.frame.minY < DevCore().statusBarHeight { if !DevCore().isStatusBarHidden { frame = CGRect(x: superview.frame.minX, y: DevCore().statusBarHeight + 8, width: superview.frame.width, height: superview.frame.height - (DevCore().statusBarHeight + 8)) } } else { frame = superview.frame } console = UITextView(frame: frame) console.backgroundColor = .clear console.isEditable = false console.attributedText = NSAttributedString(string: "Welcome to Console\n", attributes: [NSAttributedStringKey.foregroundColor: textColor]) background.addSubview(console) completion() } else { completion() } } private func setupConsole(completion: () -> Void) { if isReadOnly { console = UITextView(frame: superview.frame) console.backgroundColor = .clear completion() } else { completion() } } private func setupTextfield() { if isReadOnly { return } } //MARK:- Teardown (public) public func removeFromSuperview() { if !setupComplete { DevCore.logError("You must complete setup first") return } background.removeFromSuperview() } public func removeAndReset() { if !setupComplete { DevCore.logError("You must complete setup first") return } background.removeFromSuperview() reset() } private func reset() { console.removeFromSuperview() console = nil // Reset Console } //MARK:- Print public func print<Message>(_ message: Message, method: PrintMethod = .both) { if !setupComplete { DevCore.logConsoleError("You must complete setup first") return } switch method { case .both: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: "\(message)\n", attributes: [NSAttributedStringKey.foregroundColor: diagColor])) console.attributedText = i DevCore.log(message) case .xcodeOnly: DevCore.log(message) case .devOnly: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: "\(message)\n", attributes: [NSAttributedStringKey.foregroundColor: diagColor])) console.attributedText = i } } public func printDiag<Message>(_ diagnostic: Message, method: PrintMethod = .both) { if !setupComplete { DevCore.logConsoleError("You must complete setup first") return } switch method { case .both: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: DIAGNOSTIC :: \(diagnostic)\n)", attributes: [NSAttributedStringKey.foregroundColor: diagColor])) console.attributedText = i DevCore.logDiag(diagnostic) case .xcodeOnly: DevCore.logDiag(diagnostic) case .devOnly: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: DIAGNOSTIC :: \(diagnostic)\n)", attributes: [NSAttributedStringKey.foregroundColor: diagColor])) console.attributedText = i } } public func printWarning<Message>(_ warning: Message, method: PrintMethod = .both) { if !setupComplete { DevCore.logConsoleError("You must complete setup first") return } switch method { case .both: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: WARNING :: \(warning)\n)", attributes: [NSAttributedStringKey.foregroundColor: warningColor])) console.attributedText = i DevCore.logWarning(warning) case .xcodeOnly: DevCore.logWarning(warning) case .devOnly: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: WARNING :: \(warning)\n)", attributes: [NSAttributedStringKey.foregroundColor: warningColor])) console.attributedText = i } } public func printError<Message>(_ error: Message, method: PrintMethod = .both) { if !setupComplete { DevCore.logConsoleError("You must complete setup first") return } switch method { case .both: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: ERROR :: \(error)\n)", attributes: [NSAttributedStringKey.foregroundColor: errorColor])) console.attributedText = i DevCore.logError(error) case .xcodeOnly: DevCore.logError(error) case .devOnly: let i = NSMutableAttributedString(attributedString: console.attributedText) i.append(NSAttributedString(string: ":: ERROR :: \(error)\n)", attributes: [NSAttributedStringKey.foregroundColor: errorColor])) console.attributedText = i } } //MARK:- Public Functions public func clear() { if !setupComplete { DevCore.logError("You must complete setup first") return } // Clear Console } public func printDiagnostic() { if setupComplete { DevCore.log("\nConsole Diagnostic:\n") DevCore.logDiag("Console Background: \(backgroundColor)") DevCore.logDiag("Console Text Color: \(textColor.description)") DevCore.logDiag("Console Warning Color: \(warningColor.description)") DevCore.logDiag("Console Error Color: \(errorColor.description)") DevCore.logDiag("Console Diagnostic Color: \(diagColor.description)") DevCore.logDiag("FullScreen Enabled: \(fullscreenEnabled)") DevCore.logDiag("Is Fullscreen: \(isFullscreen)") DevCore.logDiag("Is Read Only: \(isReadOnly!)\n") DevCore.logDiag("Console Text:\n") if console.text.isEmpty { DevCore.logDiag("Console has no text") } else { DevCore.logDiag(console.text!) } } else { DevCore.log("Console has not been setup yet") } } }
mit
81f028fc09af200e7b2cef7cf0fcd984
35.960133
189
0.62436
5.110243
false
false
false
false
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/utils/UtilEmitter.swift
1
5802
// // UtilEmitter.swift // deepstreamSwiftTest // // Created by Redlock on 4/6/17. // Copyright © 2017 JiblaTech. All rights reserved. // import Foundation enum EventEnum: String { case AllEvents case ConnectionStateChanged } protocol Listener: class { func call(args: Any...) } /** * The event emitter which is ported from the JavaScript module. self class is thread-safe. * @see [https://github.com/component/emitter](https://github.com/component/emitter) */ class UtilEmitter { private var callbacks: [String: [AnyObject] ] = [:] //NSHashTable<AnyObject> init() { } func printAllListeners(){ print("[Printing Listeners]") for (eventKey, listeners) in callbacks { print("==========================================================") print("Event: \(eventKey) \n") for m in listeners { let m = Mirror(reflecting: m) print(m.subjectType) print(m.displayStyle) } } } private func sameAs(fn: AnyObject, inside: AnyObject) -> Bool { if fn === inside { return true } if let indoor = inside as? OnceListener { if indoor.fn === fn { return true } } return false // return fn === inside || inside is OnceListener && fn == inside.fn } /** * @param enu eventName as an Enum * * * @param fn The listener to invoke * * * @return a reference to self object. */ @discardableResult func on(event: EventEnum, fn: AnyObject) -> UtilEmitter { self.on(event: event.rawValue , fn: fn) return self } func off(event: EventEnum, fn: AnyObject) { self.off(event: event.rawValue , fn: fn) } /** * Listens on the event. * @param event event name. * * * @param fn The listener to invoke * * * @return a reference to self object. */ @discardableResult func on(event: String, fn: AnyObject) -> UtilEmitter { var callbacks = self.callbacks[event] if (callbacks == nil) { self.callbacks[event] = [AnyObject]() } self.callbacks[event]?.append(fn) return self } /** * Adds a one time listener for the event. * @param event an event name. * * * @param fn The listener to invoke * * * @return a reference to self object. */ func once(event: String, fn: AnyObject) -> UtilEmitter { self.on(event: event, fn: OnceListener(event: event, fn: fn, emitter: self)) return self } /** * Removes all registered listeners. * @return a reference to self object. */ func off() -> UtilEmitter { self.callbacks.removeAll() return self } /** * Removes all listeners of the specified event. * @param event an event name. * * * @return a reference to self object. */ func off(event: String) -> UtilEmitter { self.callbacks.removeValue(forKey: event) return self } /** * Removes the listener. * @param event an event name. * * * @param fn The listener to invoke * * * @return a reference to self object. */ @discardableResult func off(event: String, fn: AnyObject) -> UtilEmitter { guard let listeners = self.callbacks[event] else { print("no such event") return self } // listeners.index.remove(fn) return self } /** * Returns a list of listeners for the specified event. * @param event an event name. * * * @return a reference to self object. */ func listeners(event: EventEnum) -> [AnyObject] { return self.listeners(event: event.rawValue) } func listeners(event: String) -> [AnyObject] { guard let callbacks = self.callbacks[event] else { return [] } return callbacks } /** * Check if this emitter has any listeners * @return all listeners */ var events : [String] { return Array(self.callbacks.keys) } /** * Check if self emitter has listeners for the specified event. * @param event an event name. * * * @return true if a listener exists for that eventname */ func hasListeners(event: String) -> Bool { return self.callbacks[event] != nil } /** * Check if self emitter has any listeners * @return all listeners */ /** * Check if self emitter has any listeners * @return true if any listeners exist */ func hasListeners() -> Bool { return self.callbacks.isEmpty } class OnceListener: Listener { let event: String let fn: AnyObject let emitter:UtilEmitter init(event: String, fn: AnyObject, emitter:UtilEmitter) { self.event = event self.fn = fn self.emitter = emitter } func call(args: Any...) { emitter.off(event: self.event, fn: self.fn) guard let caller = self.fn as? Listener else { print("Error: Callback function is incorrect type.") return } caller.call(args: args) } } }
mit
0d3012a8105ae4bd1f1d35cfe3cd2444
22.019841
91
0.510774
4.682002
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/MBProgressHUD/MBProgressHUD+CS.swift
1
1370
// // Created by Rene Dohan on 1/31/21. // import MBProgressHUD extension MBProgressHUD { class func showProgress(view: UIView, title: String, foregroundColor: UIColor, backgroundColor: UIColor, canCancel: Bool, cancelTitle: String?, onCancel: Func?, graceTime: TimeInterval?, minShowTime: TimeInterval?) -> MBProgressHUD { MBProgressHUD.hide(for: view, animated: true) let hud = MBProgressHUD(view: view) view.add(view: hud).matchParent() hud.removeFromSuperViewOnHide = true graceTime?.then { hud.graceTime = $0 } minShowTime?.then { hud.minShowTime = $0 } hud.animationType = .zoom hud.contentColor = foregroundColor hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = .clear hud.backgroundView.style = .solidColor hud.backgroundView.backgroundColor = backgroundColor if canCancel { hud.detailsLabel.text = title.isSet ? "\n" + title + "\n" : "\n" hud.button.text(cancelTitle ?? .cs_dialog_cancel).onClick { onCancel?() hud.hide(animated: true) } } else { hud.detailsLabel.text = "\n" + title.asString } hud.show(animated: true) return hud } }
mit
e3557de2023cb3cbf6cac2c38879314d
37.083333
100
0.583942
4.644068
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/GroupDetails/Sections/ServicesSectionController.swift
1
2664
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel final class ServicesSectionController: GroupDetailsSectionController { private weak var delegate: GroupDetailsSectionControllerDelegate? private let serviceUsers: [UserType] private let conversation: GroupDetailsConversationType init(serviceUsers: [UserType], conversation: GroupDetailsConversationType, delegate: GroupDetailsSectionControllerDelegate) { self.serviceUsers = serviceUsers self.conversation = conversation self.delegate = delegate } override func prepareForUse(in collectionView: UICollectionView?) { super.prepareForUse(in: collectionView) collectionView?.register(UserCell.self, forCellWithReuseIdentifier: UserCell.zm_reuseIdentifier) } override var sectionTitle: String { return "participants.section.services".localized(uppercased: true, args: serviceUsers.count) } override var sectionAccessibilityIdentifier: String { return "label.groupdetails.services" } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return serviceUsers.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let user = serviceUsers[indexPath.row] let cell = collectionView.dequeueReusableCell(ofType: UserCell.self, for: indexPath) cell.configure(with: user, selfUser: ZMUser.selfUser(), conversation: conversation) cell.showSeparator = (serviceUsers.count - 1) != indexPath.row cell.accessoryIconView.isHidden = false cell.accessibilityIdentifier = "participants.section.services.cell" return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.presentDetails(for: serviceUsers[indexPath.row]) } }
gpl-3.0
dd014d65895d55a394c66e2f87ccca18
38.176471
130
0.745871
5.182879
false
false
false
false
gspd-mobi/rage-ios
Tests/RageCodableSpec.swift
1
10122
import Foundation import Quick import Nimble import Rage class Person: Codable { let firstName: String? let lastName: String? let birthDay: Date? init(firstName: String? = nil, lastName: String? = nil, birthDay: Date? = nil) { self.firstName = firstName self.lastName = lastName self.birthDay = birthDay } enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastName = "last_name" case birthDay = "birth_day" } } extension Person: Equatable { static func == (lhs: Person, rhs: Person) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.birthDay == rhs.birthDay } } class RageCodableSpec: QuickSpec { override func spec() { describe("data parsing") { it("parse json object data to codable") { let jsonObjectString = """ { "first_name": "Barbara", "last_name": "Sanders" } """ let jsonObjectData = jsonObjectString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let person = Person(firstName: "Barbara", lastName: "Sanders") let parsedPerson: Person? = jsonObjectData.parseJson(decoder: jsonDecoder) expect(parsedPerson).to(equal(person)) } it("parse invalid json data to codable") { let jsonObjectString = """ { first_name: "Fabrizio" "last_name": "Verdaasdonk" } """ let jsonObjectData = jsonObjectString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let parsedPerson: Person? = jsonObjectData.parseJson(decoder: jsonDecoder) expect(parsedPerson).to(beNil()) } it("parse invalid json array data to codable") { let jsonArrayString = """ [ { first_name: "Laurenz" "last_name": "Wenzel" }, { "first_name": "Hudson"; last_name: "Roy" } ] """ let jsonArrayData = jsonArrayString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let parsedPersons: [Person]? = jsonArrayData.parseJsonArray(decoder: jsonDecoder) expect(parsedPersons).to(beNil()) } it("parse json array data to codable") { let jsonArrayString = """ [ { "first_name": "Noah", "last_name": "Ginnish" }, { "first_name": "Megan", "last_name": "Claire" } ] """ let jsonArrayData = jsonArrayString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let persons = [ Person(firstName: "Noah", lastName: "Ginnish"), Person(firstName: "Megan", lastName: "Claire") ] let parsedPersons: [Person] = jsonArrayData.parseJsonArray(decoder: jsonDecoder)! expect(parsedPersons).to(equal(persons)) } it("person json object data with date") { let jsonObjectString = """ { "first_name": "Eva", "last_name": "Lorenzo", "birth_day": "18.08.2017" } """ let jsonObjectData = jsonObjectString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let formatter = DateFormatter() formatter.dateFormat = "dd.MM.YYYY" jsonDecoder.dateDecodingStrategy = .formatted(formatter) let date = formatter.date(from: "18.08.2017")! let person = Person(firstName: "Eva", lastName: "Lorenzo", birthDay: date) let parsedPerson: Person = jsonObjectData.parseJson(decoder: jsonDecoder)! expect(parsedPerson).to(equal(person)) } it("parse person json object with invalid data") { let jsonObjectString = """ { "first_name": "Tuba", "last_name": "van Hagen", "birth_day": "18.082017" } """ let jsonObjectData = jsonObjectString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let formatter = DateFormatter() formatter.dateFormat = "dd.MM.YYYY" jsonDecoder.dateDecodingStrategy = .formatted(formatter) let parsedPerson: Person? = jsonObjectData.parseJson(decoder: jsonDecoder) expect(parsedPerson).to(beNil()) } it("parse json array with invalid date") { let jsonArrayString = """ [ { "first_name": "Caetano", "last_name": "Dias", "birth_day": "1808.2017" }, { "first_name": "Michael", "last_name": "Singh", "birth_day": "19082017" } ] """ let jsonArrayData = jsonArrayString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let formatter = DateFormatter() formatter.dateFormat = "dd.MM.YYYY" let parsedPersons: [Person]? = jsonArrayData.parseJson(decoder: jsonDecoder) expect(parsedPersons).to(beNil()) } it("person json array with date") { let jsonArrayString = """ [ { "first_name": "Marc", "last_name": "Austin", "birth_day": "18.08.2017" }, { "first_name": "Amparo", "last_name": "Parra", "birth_day": "19.08.2017" } ] """ let jsonArrayData = jsonArrayString.data(using: .utf8)! let jsonDecoder = JSONDecoder() let formatter = DateFormatter() formatter.dateFormat = "dd.MM.YYYY" jsonDecoder.dateDecodingStrategy = .formatted(formatter) let firstDate = formatter.date(from: "18.08.2017") let secondDate = formatter.date(from: "19.08.2017") let persons = [ Person(firstName: "Marc", lastName: "Austin", birthDay: firstDate), Person(firstName: "Amparo", lastName: "Parra", birthDay: secondDate) ] let parsedPersons: [Person] = jsonArrayData.parseJsonArray(decoder: jsonDecoder)! expect(parsedPersons).to(equal(persons)) } } describe("body rage request") { it("codable at BodyRageRequest body json") { let person = Person(firstName: "Jennifer", lastName: "Jenkins") let personString = try! person.toJSONString() let request = BodyRageRequest(httpMethod: .post, baseUrl: "http://example.com") .bodyJson(person) let body = request.rawRequest().httpBody! let bodyString = String(data: body, encoding: .utf8)! expect(bodyString).to(equal(personString)) } it("codable array at BodyRageRequest body json") { let persons = [ Person(firstName: "Kimberly", lastName: "Stephens"), Person(firstName: "Matilda", lastName: "Hunta") ] let personsString = try! persons.toJSONString() let request = BodyRageRequest(httpMethod: .post, baseUrl: "http://example.com") .bodyJson(persons) let body = request.rawRequest().httpBody! let bodyString = String(data: body, encoding: .utf8)! expect(bodyString).to(equal(personsString)) } } describe("rage request stubs") { it("rage request codable stub") { let person = Person(firstName: "Kate", lastName: "Robinson") let personString = try! person.toJSONString() let request = RageRequest(httpMethod: .get, baseUrl: "http://example.com") _ = request.stub(person, mode: .immediate) let result = request.execute().value?.data let resultString = String(data: result!, encoding: .utf8)! expect(resultString).to(equal(personString)) } it("rage request codable array stub") { let persons = [ Person(firstName: "Debra", lastName: "Gilbert"), Person(firstName: "John", lastName: "Harris") ] let personsString = try! persons.toJSONString() let request = RageRequest(httpMethod: .get, baseUrl: "http://example.com") _ = request.stub(persons, mode: .immediate) let result = request.execute().value?.data let resultString = String(data: result!, encoding: .utf8)! expect(resultString).to(equal(personsString)) } } } }
mit
ec99c1ffb7c4d9e157f1340868076176
36.628253
97
0.468682
5.153768
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCSkillEditTableViewCell.swift
2
1526
// // NCSkillEditTableViewCell.swift // Neocom // // Created by Artem Shimanski on 06.03.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit class NCSkillEditTableViewCell: NCTableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var levelSegmentedControl: UISegmentedControl! var actionHandler: NCActionHandler<UISegmentedControl>? override func prepareForReuse() { super.prepareForReuse() actionHandler = nil } } extension Prototype { enum NCSkillEditTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCSkillEditTableViewCell") } } class NCSkillEditRow: NCFetchedResultsObjectNode<NSDictionary>, TreeNodeRoutable { var level: Int = 0 let typeID: Int var route: Route? var accessoryButtonRoute: Route? required init(object: NSDictionary) { typeID = (object["typeID"] as! NSNumber).intValue accessoryButtonRoute = Router.Database.TypeInfo(typeID) super.init(object: object) cellIdentifier = Prototype.NCSkillEditTableViewCell.default.reuseIdentifier } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCSkillEditTableViewCell else {return} cell.titleLabel.text = object["typeName"] as? String cell.levelSegmentedControl.selectedSegmentIndex = level let segmentedControl = cell.levelSegmentedControl! cell.actionHandler = NCActionHandler(cell.levelSegmentedControl, for: .valueChanged) { [weak self] _ in self?.level = segmentedControl.selectedSegmentIndex } } }
lgpl-2.1
95b34e56357308841ea683cc83c14e1e
26.727273
105
0.769836
4.002625
false
false
false
false
csnu17/My-Swift-learning
GooglyPuff/GooglyPuff/PhotoCollectionViewController.swift
1
7800
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Photos private let reuseIdentifier = "photoCell" private let backgroundImageOpacity: CGFloat = 0.1 #if DEBUG var signal: DispatchSourceSignal? private let setupSignalHandlerFor = { (_ object: AnyObject) -> Void in let queue = DispatchQueue.main signal = DispatchSource.makeSignalSource(signal: Int32(SIGSTOP), queue: queue) signal?.setEventHandler { print("Hi, I am: \(object.description!)") } signal?.resume() } #endif class PhotoCollectionViewController: UICollectionViewController { // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() #if DEBUG _ = setupSignalHandlerFor(self) #endif // Background image setup let backgroundImageView = UIImageView(image: UIImage(named:"background")) backgroundImageView.alpha = backgroundImageOpacity backgroundImageView.contentMode = .center collectionView?.backgroundView = backgroundImageView NotificationCenter.default.addObserver( self, selector: #selector(contentChangedNotification(_:)), name: NSNotification.Name(rawValue: photoManagerContentUpdatedNotification), object: nil) NotificationCenter.default.addObserver( self, selector: #selector(contentChangedNotification(_:)), name: NSNotification.Name(rawValue: photoManagerContentAddedNotification), object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showOrHideNavPrompt() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } // MARK: - IBAction Methods @IBAction func addPhotoAssets(_ sender: Any) { let alert = UIAlertController(title: "Get Photos From:", message: nil, preferredStyle: .actionSheet) // Cancel button let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cancelAction) // Photo library button let libraryAction = UIAlertAction(title: "Photo Library", style: .default) { _ in let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AlbumsStoryboard") as? UINavigationController if let viewController = viewController, let albumsTableViewController = viewController.topViewController as? AlbumsTableViewController { albumsTableViewController.assetPickerDelegate = self self.present(viewController, animated: true) } } alert.addAction(libraryAction) // Internet button let internetAction = UIAlertAction(title: "Le Internet", style: .default) { _ in self.downloadImageAssets() } alert.addAction(internetAction) // Present alert present(alert, animated: true) } } // MARK: - Private Methods private extension PhotoCollectionViewController { func showOrHideNavPrompt() { let delayInSeconds = 1.0 DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { let count = PhotoManager.sharedManager.photos.count if count > 0 { self.navigationItem.prompt = nil } else { self.navigationItem.prompt = "Add photos with faces to Googlyify them!" } } } func downloadImageAssets() { PhotoManager.sharedManager.downloadPhotosWithCompletion() { error in // This completion block currently executes at the wrong time let message = error?.localizedDescription ?? "The images have finished downloading" let alert = UIAlertController(title: "Download Complete", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) self.present(alert, animated: true) } } } // MARK: - Notification handlers extension PhotoCollectionViewController { @objc func contentChangedNotification(_ notification: Notification!) { collectionView?.reloadData() showOrHideNavPrompt() } } // MARK: - UICollectionViewDataSource extension PhotoCollectionViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return PhotoManager.sharedManager.photos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCollectionViewCell // Configure the cell let photoAssets = PhotoManager.sharedManager.photos let photo = photoAssets[indexPath.row] switch photo.statusThumbnail { case .goodToGo: cell.thumbnailImage = photo.thumbnail case .downloading: cell.thumbnailImage = UIImage(named: "photoDownloading") case .failed: cell.thumbnailImage = UIImage(named: "photoDownloadError") } return cell } } // MARK: - UICollectionViewDelegate extension PhotoCollectionViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let photos = PhotoManager.sharedManager.photos let photo = photos[indexPath.row] switch photo.statusImage { case .goodToGo: let viewController = storyboard?.instantiateViewController(withIdentifier: "PhotoDetailStoryboard") as? PhotoDetailViewController if let viewController = viewController { viewController.image = photo.image navigationController?.pushViewController(viewController, animated: true) } case .downloading: let alert = UIAlertController(title: "Downloading", message: "The image is currently downloading", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) case .failed: let alert = UIAlertController(title: "Image Failed", message: "The image failed to be created", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) } } } // MARK: - AssetPickerDelegate extension PhotoCollectionViewController: AssetPickerDelegate { func assetPickerDidCancel() { // Dismiss asset picker dismiss(animated: true) } func assetPickerDidFinishPickingAssets(_ selectedAssets: [PHAsset]) { // Add assets for asset in selectedAssets { let photo = AssetPhoto(asset: asset) PhotoManager.sharedManager.addPhoto(photo) } // Dismiss asset picker dismiss(animated: true) } }
mit
b7b732cacf5728672a1f62622b8586ea
34.616438
135
0.70859
5.134957
false
false
false
false
cuappdev/podcast-ios
old/Podcast/SearchSectionHeaderView.swift
1
2316
// // SearchSectionHeaderTableViewCell.swift // Podcast // // Created by Jack Thompson on 4/6/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit import SnapKit protocol SearchTableViewHeaderDelegate: class { func searchTableViewHeaderDidPressViewAllButton(view: SearchSectionHeaderView) } class SearchSectionHeaderView: UIView { let edgePadding: CGFloat = 18 var mainLabel: UILabel! var viewAllButton: UIButton! var type: SearchType! weak var delegate: SearchTableViewHeaderDelegate? var mainLabelHeight: CGFloat = 21 var viewAllButtonHeight: CGFloat = 18 var bottomInset: CGFloat = 12.5 init(frame: CGRect, type: SearchType) { super.init(frame: frame) mainLabel = UILabel(frame: .zero) mainLabel.font = ._14SemiboldFont() mainLabel.textColor = .charcoalGrey viewAllButton = UIButton(frame: .zero) viewAllButton.addTarget(self, action: #selector(didPressViewAllButton), for: .touchUpInside) let attributedTitle = NSAttributedString(string: "See all", attributes: [NSAttributedStringKey.foregroundColor: UIColor.slateGrey, NSAttributedStringKey.font: UIFont._12RegularFont()]) viewAllButton.setAttributedTitle(attributedTitle, for: .normal) addSubview(mainLabel) addSubview(viewAllButton) mainLabel.snp.makeConstraints { (make) in make.leading.equalToSuperview().offset(edgePadding) make.height.equalTo(mainLabelHeight) make.bottom.equalToSuperview().inset(bottomInset) } viewAllButton.snp.makeConstraints { (make) in make.trailing.equalToSuperview().inset(edgePadding) make.height.equalTo(viewAllButtonHeight) make.bottom.equalTo(mainLabel) } } func configure(type: SearchType) { self.type = type mainLabel.text = type.toString() } func hideViewAllButton() { viewAllButton.isHidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func didPressViewAllButton() { delegate?.searchTableViewHeaderDidPressViewAllButton(view: self) } }
mit
b0807e3a7d3b6490480130cd2807536b
31.152778
192
0.671706
4.936034
false
false
false
false
xwu/swift
test/expr/closure/anonymous.swift
4
1201
// RUN: %target-typecheck-verify-swift func takeIntToInt(_ f: (Int) -> Int) { } func takeIntIntToInt(_ f: (Int, Int) -> Int) { } // Simple closures with anonymous arguments func simple() { takeIntToInt({return $0 + 1}) takeIntIntToInt({return $0 + $1 + 1}) } func takesIntArray(_: [Int]) { } func takesVariadicInt(_: (Int...) -> ()) { } func takesVariadicIntInt(_: (Int, Int...) -> ()) { } func takesVariadicGeneric<T>(_ f: (T...) -> ()) { } func variadic() { // These work takesVariadicInt({let _ = $0}) takesVariadicInt({let _: [Int] = $0}) let _: (Int...) -> () = {let _: [Int] = $0} takesVariadicInt({takesIntArray($0)}) let _: (Int...) -> () = {takesIntArray($0)} takesVariadicGeneric({takesIntArray($0)}) // FIXME: Problem here is related to multi-statement closure body not being type-checked together with // enclosing context. We could have inferred `$0` to be `[Int]` if `let` was a part of constraint system. takesVariadicGeneric({let _: [Int] = $0}) // expected-error@-1 {{unable to infer type of a closure parameter '$0' in the current context}} takesVariadicIntInt({_ = $0; takesIntArray($1)}) takesVariadicIntInt({_ = $0; let _: [Int] = $1}) }
apache-2.0
598a8637b651d0ecd0009ad67c374716
29.794872
107
0.621149
3.532353
false
false
false
false
BryanHoke/swift-corelibs-foundation
Foundation/NSXMLParser.swift
2
37526
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation public enum NSXMLParserExternalEntityResolvingPolicy : UInt { case ResolveExternalEntitiesNever // default case ResolveExternalEntitiesNoNetwork case ResolveExternalEntitiesSameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL: case ResolveExternalEntitiesAlways } extension _CFXMLInterface { var parser: NSXMLParser { return unsafeBitCast(self, NSXMLParser.self) } } extension NSXMLParser { internal var interface: _CFXMLInterface { return unsafeBitCast(self, _CFXMLInterface.self) } } private func UTF8STRING(bytes: UnsafePointer<UInt8>) -> String? { let len = strlen(UnsafePointer<Int8>(bytes)) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: bytes, count: Int(len))) return str } internal func _NSXMLParserCurrentParser() -> _CFXMLInterface { if let parser = NSXMLParser.currentParser() { return parser.interface } else { return nil } } internal func _NSXMLParserExternalEntityWithURL(interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput { let parser = interface.parser let policy = parser.externalEntityResolvingPolicy var a: NSURL? if let allowedEntityURLs = parser.allowedExternalEntityURLs { if let url = NSURL(string: String(urlStr)) { a = url if let scheme = url.scheme { if scheme == "file" { a = NSURL(fileURLWithPath: url.path!) } } } if let url = a { let allowed = allowedEntityURLs.contains(url) if allowed || policy != .ResolveExternalEntitiesSameOriginOnly { if allowed { return originalLoaderFunction(urlStr, identifier, context) } } } } switch policy { case .ResolveExternalEntitiesSameOriginOnly: if let url = parser._url { if a == nil { a = NSURL(string: String(urlStr)) } if let aUrl = a { var matches: Bool if let aHost = aUrl.host { if let host = url.host { matches = host == aHost } else { matches = false } } else { matches = false } if matches { if let aPort = aUrl.port { if let port = url.port { matches = port == aPort } else { matches = false } } else { matches = false } } if matches { if let aScheme = aUrl.scheme { if let scheme = url.scheme { matches = scheme == aScheme } else { matches = false } } else { matches = false } } if !matches { return nil } } } break case .ResolveExternalEntitiesAlways: break case .ResolveExternalEntitiesNever: return nil case .ResolveExternalEntitiesNoNetwork: return _CFXMLInterfaceNoNetExternalEntityLoader(urlStr, identifier, context) } return originalLoaderFunction(urlStr, identifier, context) } internal func _NSXMLParserGetContext(ctx: _CFXMLInterface) -> _CFXMLInterfaceParserContext { return ctx.parser._parserContext } internal func _NSXMLParserInternalSubset(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2InternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _NSXMLParserIsStandalone(ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceIsStandalone(ctx.parser._parserContext) } internal func _NSXMLParserHasInternalSubset(ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasInternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserHasExternalSubset(ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasExternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserGetEntity(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>) -> _CFXMLInterfaceEntity { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) var entity = _CFXMLInterfaceGetPredefinedEntity(name) if entity == nil { entity = _CFXMLInterfaceSAX2GetEntity(context, name) } if entity == nil { if let delegate = parser.delegate { let entityName = UTF8STRING(name)! // if the systemID was valid, we would already have the correct entity (since we're loading external dtds) so this callback is a bit of a misnomer let result = delegate.parser(parser, resolveExternalEntityName: entityName, systemID: nil) if _CFXMLInterfaceHasDocument(context) != 0 { if let data = result { // unfortunately we can't add the entity to the doc to avoid further lookup since the delegate can change under us _NSXMLParserCharacters(ctx, ch: UnsafePointer<UInt8>(data.bytes), len: Int32(data.length)) } } } } return entity } internal func _NSXMLParserNotationDecl(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let notationName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) delegate.parser(parser, foundNotationDeclarationWithName: notationName, publicID: publicIDString, systemID: systemIDString) } } internal func _NSXMLParserAttributeDecl(ctx: _CFXMLInterface, elem: UnsafePointer<UInt8>, fullname: UnsafePointer<UInt8>, type: Int32, def: Int32, defaultValue: UnsafePointer<UInt8>, tree: _CFXMLInterfaceEnumeration) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let elementString = UTF8STRING(elem)! let nameString = UTF8STRING(fullname)! let typeString = "" // FIXME! let defaultValueString = UTF8STRING(defaultValue) delegate.parser(parser, foundAttributeDeclarationWithName: nameString, forElement: elementString, type: typeString, defaultValue: defaultValueString) } // in a regular sax implementation tree is added to an attribute, which takes ownership of it; in our case we need to make sure to release it _CFXMLInterfaceFreeEnumeration(tree) } internal func _NSXMLParserElementDecl(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, type: Int32, content: _CFXMLInterfaceElementContent) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let nameString = UTF8STRING(name)! let modelString = "" // FIXME! delegate.parser(parser, foundElementDeclarationWithName: nameString, model: modelString) } } internal func _NSXMLParserUnparsedEntityDecl(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>, notationName: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) // Add entities to the libxml2 doc so they'll resolve properly _CFXMLInterfaceSAX2UnparsedEntityDecl(context, name, publicId, systemId, notationName) if let delegate = parser.delegate { let declName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) let notationNameString = UTF8STRING(notationName) delegate.parser(parser, foundUnparsedEntityDeclarationWithName: declName, publicID: publicIDString, systemID: systemIDString, notationName: notationNameString) } } internal func _NSXMLParserStartDocument(ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidStartDocument(parser) } } internal func _NSXMLParserEndDocument(ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidEndDocument(parser) } } internal func _colonSeparatedStringFromPrefixAndSuffix(prefix: UnsafePointer<UInt8>, _ prefixlen: UInt, _ suffix: UnsafePointer<UInt8>, _ suffixLen: UInt) -> String { let prefixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: prefix, count: Int(prefixlen))) let suffixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: suffix, count: Int(suffixLen))) return "\(prefixString!):\(suffixString!)" } internal func _NSXMLParserStartElementNs(ctx: _CFXMLInterface, localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>, URI: UnsafePointer<UInt8>, nb_namespaces: Int32, namespaces: UnsafeMutablePointer<UnsafePointer<UInt8>>, nb_attributes: Int32, nb_defaulted: Int32, attributes: UnsafeMutablePointer<UnsafePointer<UInt8>>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let reportNamespaces = parser.shouldReportNamespacePrefixes let prefixLen = prefix == nil ? strlen(UnsafePointer<Int8>(prefix)) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let qualifiedNameString = prefixLen != 0 ? _colonSeparatedStringFromPrefixAndSuffix(prefix, prefixLen, localname, strlen(UnsafePointer<Int8>(localname))) : localnameString let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nil var nsDict = [String:String]() var attrDict = [String:String]() if nb_attributes + nb_namespaces > 0 { for var idx = 0; idx < Int(nb_namespaces) * 2; idx += 2 { var namespaceNameString: String? var asAttrNamespaceNameString: String? if namespaces[idx] != nil { if reportNamespaces { namespaceNameString = UTF8STRING(namespaces[idx]) } asAttrNamespaceNameString = _colonSeparatedStringFromPrefixAndSuffix("xmlns", 5, namespaces[idx], strlen(UnsafePointer<Int8>(namespaces[idx]))) } else { namespaceNameString = "" asAttrNamespaceNameString = "xmlns" } let namespaceValueString = namespaces[idx + 1] == nil ? UTF8STRING(namespaces[idx + 1]) : "" if (reportNamespaces) { if let k = namespaceNameString { if let v = namespaceValueString { nsDict[k] = v } } } if !reportQNameURI { if let k = asAttrNamespaceNameString { if let v = namespaceValueString { attrDict[k] = v } } } } } if reportNamespaces { parser._pushNamespaces(nsDict) } for var idx = 0; idx < Int(nb_attributes) * 5; idx += 5 { if attributes[idx] == nil { continue } var attributeQName: String let attrLocalName = attributes[idx] let attrPrefix = attributes[idx + 1] let attrPrefixLen = attrPrefix == nil ? strlen(UnsafePointer<Int8>(attrPrefix)) : 0 if attrPrefixLen != 0 { attributeQName = _colonSeparatedStringFromPrefixAndSuffix(attrPrefix, attrPrefixLen, attrLocalName, strlen((UnsafePointer<Int8>(attrLocalName)))) } else { attributeQName = UTF8STRING(attrLocalName)! } // idx+2 = URI, which we throw away // idx+3 = value, i+4 = endvalue // By using XML_PARSE_NOENT the attribute value string will already have entities resolved var attributeValue = "" if attributes[idx + 3] != nil && attributes[idx + 4] != nil { let numBytesWithoutTerminator = attributes[idx + 4] - attributes[idx + 3] let numBytesWithTerminator = numBytesWithoutTerminator + 1 if numBytesWithoutTerminator != 0 { var chars = [Int8](count: numBytesWithTerminator, repeatedValue: 0) attributeValue = chars.withUnsafeMutableBufferPointer({ (inout buffer: UnsafeMutableBufferPointer<Int8>) -> String in strncpy(buffer.baseAddress, UnsafePointer<Int8>(attributes[idx + 3]), numBytesWithoutTerminator) //not strlcpy because attributes[i+3] is not Nul terminated return UTF8STRING(UnsafePointer<UInt8>(buffer.baseAddress))! }) } attrDict[attributeQName] = attributeValue } } if let delegate = parser.delegate { if reportQNameURI { delegate.parser(parser, didStartElement: localnameString!, namespaceURI: (namespaceURIString != nil ? namespaceURIString : ""), qualifiedName: (qualifiedNameString != nil ? qualifiedNameString : ""), attributes: attrDict) } else { delegate.parser(parser, didStartElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil, attributes: attrDict) } } } internal func _NSXMLParserEndElementNs(ctx: _CFXMLInterface , localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>, URI: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let prefixLen = prefix == nil ? strlen(UnsafePointer<Int8>(prefix)) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let nilStr: String? = nil let qualifiedNameString = (prefixLen != 0) ? _colonSeparatedStringFromPrefixAndSuffix(prefix, prefixLen, localname, strlen(UnsafePointer<Int8>(localname))) : nilStr let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nilStr if let delegate = parser.delegate { if (reportQNameURI) { // When reporting namespace info, the delegate parameters are not passed in nil delegate.parser(parser, didEndElement: localnameString!, namespaceURI: namespaceURIString == nil ? "" : namespaceURIString, qualifiedName: qualifiedNameString == nil ? "" : qualifiedNameString) } else { delegate.parser(parser, didEndElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil) } } // Pop the last namespaces that were pushed (safe since XML is balanced) parser._popNamespaces() } internal func _NSXMLParserCharacters(ctx: _CFXMLInterface, ch: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser let context = parser._parserContext if _CFXMLInterfaceInRecursiveState(context) != 0 { _CFXMLInterfaceResetRecursiveState(context) } else { if let delegate = parser.delegate { let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: ch, count: Int(len))) delegate.parser(parser, foundCharacters: str!) } } } internal func _NSXMLParserProcessingInstruction(ctx: _CFXMLInterface, target: UnsafePointer<UInt8>, data: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let targetString = UTF8STRING(target)! let dataString = UTF8STRING(data) delegate.parser(parser, foundProcessingInstructionWithTarget: targetString, data: dataString) } } internal func _NSXMLParserCdataBlock(ctx: _CFXMLInterface, value: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parser(parser, foundCDATA: NSData(bytes: UnsafePointer<Void>(value), length: Int(len))) } } internal func _NSXMLParserComment(ctx: _CFXMLInterface, value: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let comment = UTF8STRING(value)! delegate.parser(parser, foundComment: comment) } } internal func _NSXMLParserExternalSubset(ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2ExternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _structuredErrorFunc(interface: _CFXMLInterface, error: _CFXMLInterfaceError) { let err = _CFErrorCreateFromXMLInterface(error)._nsObject let parser = interface.parser parser._parserError = err if let delegate = parser.delegate { delegate.parser(parser, parseErrorOccurred: err) } } public class NSXMLParser : NSObject { private var _handler: _CFXMLInterfaceSAXHandler internal var _stream: NSInputStream? internal var _data: NSData? internal var _chunkSize = Int(4096 * 32) // a suitably large number for a decent chunk size internal var _haveDetectedEncoding = false internal var _bomChunk: NSData? private var _parserContext: _CFXMLInterfaceParserContext internal var _delegateAborted = false internal var _url: NSURL? internal var _namespaces = [[String:String]]() // initializes the parser with the specified URL. public convenience init?(contentsOfURL url: NSURL) { if url.fileURL { if let stream = NSInputStream(URL: url) { self.init(stream: stream) _url = url } } else { if let data = NSData(contentsOfURL: url) { self.init(data: data) self._url = url } } return nil } // create the parser from data public init(data: NSData) { _CFSetupXMLInterface() _data = data.copy() as? NSData _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } deinit { _CFXMLInterfaceDestroySAXHandler(_handler) _CFXMLInterfaceDestroyContext(_parserContext) } //create a parser that incrementally pulls data from the specified stream and parses it. public init(stream: NSInputStream) { _CFSetupXMLInterface() _stream = stream _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } public weak var delegate: NSXMLParserDelegate? public var shouldProcessNamespaces: Bool = false public var shouldReportNamespacePrefixes: Bool = false //defaults to NSXMLNodeLoadExternalEntitiesNever public var externalEntityResolvingPolicy: NSXMLParserExternalEntityResolvingPolicy = .ResolveExternalEntitiesNever public var allowedExternalEntityURLs: Set<NSURL>? internal static func currentParser() -> NSXMLParser? { if let current = NSThread.currentThread().threadDictionary["__CurrentNSXMLParser"] { return current as? NSXMLParser } else { return nil } } internal static func setCurrentParser(parser: NSXMLParser?) { if let p = parser { NSThread.currentThread().threadDictionary["__CurrentNSXMLParser"] = p } else { NSThread.currentThread().threadDictionary.removeValueForKey("__CurrentNSXMLParser") } } internal func _handleParseResult(parseResult: Int32) -> Bool { return true /* var result = true if parseResult != 0 { if parseResult != -1 { // TODO: determine if this result is a fatal error from libxml via the CF implementations } } return result */ } internal func parseData(data: NSData) -> Bool { _CFXMLInterfaceSetStructuredErrorFunc(interface, _structuredErrorFunc) var result = true /* The vast majority of this method just deals with ensuring we do a single parse on the first 4 received bytes before continuing on to the actual incremental section */ if _haveDetectedEncoding { var totalLength = data.length if let chunk = _bomChunk { totalLength += chunk.length } if (totalLength < 4) { if let chunk = _bomChunk { let newData = NSMutableData() newData.appendData(chunk) newData.appendData(data) _bomChunk = newData } else { _bomChunk = data } } else { var allExistingData: NSData if let chunk = _bomChunk { let newData = NSMutableData() newData.appendData(chunk) newData.appendData(data) allExistingData = newData } else { allExistingData = data } var handler: _CFXMLInterfaceSAXHandler = nil if delegate != nil { handler = _handler } _parserContext = _CFXMLInterfaceCreatePushParserCtxt(handler, interface, UnsafePointer<Int8>(allExistingData.bytes), 4, nil) var options = _kCFXMLInterfaceRecover | _kCFXMLInterfaceNoEnt // substitute entities, recover on errors if shouldResolveExternalEntities { options |= _kCFXMLInterfaceDTDLoad } if handler == nil { options |= (_kCFXMLInterfaceNoError | _kCFXMLInterfaceNoWarning) } _CFXMLInterfaceCtxtUseOptions(_parserContext, options) _haveDetectedEncoding = true _bomChunk = nil if (totalLength > 4) { let remainingData = NSData(bytesNoCopy: UnsafeMutablePointer<Void>(allExistingData.bytes.advancedBy(4)), length: totalLength - 4, freeWhenDone: false) parseData(remainingData) } } } else { let parseResult = _CFXMLInterfaceParseChunk(_parserContext, UnsafePointer<Int8>(data.bytes), Int32(data.length), 0) result = _handleParseResult(parseResult) } _CFXMLInterfaceSetStructuredErrorFunc(interface, nil) return result } internal func parseFromStream() -> Bool { var result = true NSXMLParser.setCurrentParser(self) if let stream = _stream { stream.open() let buffer = malloc(_chunkSize) var len = stream.read(UnsafeMutablePointer<UInt8>(buffer), maxLength: _chunkSize) if len != -1 { while len > 0 { let data = NSData(bytesNoCopy: buffer, length: len, freeWhenDone: false) result = parseData(data) len = stream.read(UnsafeMutablePointer<UInt8>(buffer), maxLength: _chunkSize) } } else { result = false } free(buffer) stream.close() } else if let data = _data { let buffer = malloc(_chunkSize) var range = NSMakeRange(0, min(_chunkSize, data.length)) while result { data.getBytes(buffer, range: range) let chunk = NSData(bytesNoCopy: buffer, length: range.length, freeWhenDone: false) result = parseData(chunk) if range.location + range.length >= data.length { break } range = NSMakeRange(range.location + range.length, min(_chunkSize, data.length - (range.location + range.length))) } free(buffer) } else { result = false } NSXMLParser.setCurrentParser(nil) return result } // called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error. public func parse() -> Bool { return parseFromStream() } // called by the delegate to stop the parse. The delegate will get an error message sent to it. public func abortParsing() { if _parserContext != nil { _CFXMLInterfaceStopParser(_parserContext) _delegateAborted = true } } internal var _parserError: NSError? /*@NSCopying*/ public var parserError: NSError? { return _parserError } // can be called after a parse is over to determine parser state. //Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'. //The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier public var shouldResolveExternalEntities: Bool = false // Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred. public var publicID: String? { return nil } public var systemID: String? { return nil } public var lineNumber: Int { return Int(_CFXMLInterfaceSAX2GetLineNumber(_parserContext)) } public var columnNumber: Int { return Int(_CFXMLInterfaceSAX2GetColumnNumber(_parserContext)) } internal func _pushNamespaces(ns: [String:String]) { _namespaces.append(ns) if let del = self.delegate { ns.forEach { del.parser(self, didStartMappingPrefix: $0.0, toURI: $0.1) } } } internal func _popNamespaces() { let ns = _namespaces.removeLast() if let del = self.delegate { ns.forEach { del.parser(self, didEndMappingPrefix: $0.0) } } } } /* For the discussion of event methods, assume the following XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type='text/css' href='cvslog.css'?> <!DOCTYPE cvslog SYSTEM "cvslog.dtd"> <cvslog xmlns="http://xml.apple.com/cvslog"> <radar:radar xmlns:radar="http://xml.apple.com/radar"> <radar:bugID>2920186</radar:bugID> <radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title> </radar:radar> </cvslog> */ // The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category. public protocol NSXMLParserDelegate : class { // Document handling methods func parserDidStartDocument(parser: NSXMLParser) // sent when the parser begins parsing of the document. func parserDidEndDocument(parser: NSXMLParser) // sent when the parser has completed parsing. If this is encountered, the parse was successful. // DTD handling methods for various declarations. func parser(parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) func parser(parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) func parser(parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) func parser(parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) // sent when the parser finds an element start tag. // In the case of the cvslog tag, the following is what the delegate receives: // elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog // In the case of the radar tag, the following is what's passed in: // elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar // If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName. func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) // sent when an end tag is encountered. The various parameters are supplied as above. func parser(parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) // sent when the parser first sees a namespace attribute. // In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace) // In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar" func parser(parser: NSXMLParser, didEndMappingPrefix prefix: String) // sent when the namespace prefix in question goes out of scope. func parser(parser: NSXMLParser, foundCharacters string: String) // This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters: func parser(parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) // The parser reports ignorable whitespace in the same way as characters it's found. func parser(parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) // The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'" func parser(parser: NSXMLParser, foundComment comment: String) // A comment (Text in a <!-- --> block) is reported to the delegate as a single string func parser(parser: NSXMLParser, foundCDATA CDATABlock: NSData) // this reports a CDATA block to the delegate as an NSData. func parser(parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? // this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data. func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) // ...and this reports a fatal error to the delegate. The parser will stop parsing. func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) } extension NSXMLParserDelegate { func parserDidStartDocument(parser: NSXMLParser) { } func parserDidEndDocument(parser: NSXMLParser) { } func parser(parser: NSXMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(parser: NSXMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { } func parser(parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { } func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { } func parser(parser: NSXMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { } func parser(parser: NSXMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } func parser(parser: NSXMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { } func parser(parser: NSXMLParser, didEndMappingPrefix prefix: String) { } func parser(parser: NSXMLParser, foundCharacters string: String) { } func parser(parser: NSXMLParser, foundIgnorableWhitespace whitespaceString: String) { } func parser(parser: NSXMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { } func parser(parser: NSXMLParser, foundComment comment: String) { } func parser(parser: NSXMLParser, foundCDATA CDATABlock: NSData) { } func parser(parser: NSXMLParser, resolveExternalEntityName name: String, systemID: String?) -> NSData? { return nil } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { } func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) { } } // If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing. public let NSXMLParserErrorDomain: String = "NSXMLParserErrorDomain" // for use with NSError. // Error reporting public enum NSXMLParserError : Int { case InternalError case OutOfMemoryError case DocumentStartError case EmptyDocumentError case PrematureDocumentEndError case InvalidHexCharacterRefError case InvalidDecimalCharacterRefError case InvalidCharacterRefError case InvalidCharacterError case CharacterRefAtEOFError case CharacterRefInPrologError case CharacterRefInEpilogError case CharacterRefInDTDError case EntityRefAtEOFError case EntityRefInPrologError case EntityRefInEpilogError case EntityRefInDTDError case ParsedEntityRefAtEOFError case ParsedEntityRefInPrologError case ParsedEntityRefInEpilogError case ParsedEntityRefInInternalSubsetError case EntityReferenceWithoutNameError case EntityReferenceMissingSemiError case ParsedEntityRefNoNameError case ParsedEntityRefMissingSemiError case UndeclaredEntityError case UnparsedEntityError case EntityIsExternalError case EntityIsParameterError case UnknownEncodingError case EncodingNotSupportedError case StringNotStartedError case StringNotClosedError case NamespaceDeclarationError case EntityNotStartedError case EntityNotFinishedError case LessThanSymbolInAttributeError case AttributeNotStartedError case AttributeNotFinishedError case AttributeHasNoValueError case AttributeRedefinedError case LiteralNotStartedError case LiteralNotFinishedError case CommentNotFinishedError case ProcessingInstructionNotStartedError case ProcessingInstructionNotFinishedError case NotationNotStartedError case NotationNotFinishedError case AttributeListNotStartedError case AttributeListNotFinishedError case MixedContentDeclNotStartedError case MixedContentDeclNotFinishedError case ElementContentDeclNotStartedError case ElementContentDeclNotFinishedError case XMLDeclNotStartedError case XMLDeclNotFinishedError case ConditionalSectionNotStartedError case ConditionalSectionNotFinishedError case ExternalSubsetNotFinishedError case DOCTYPEDeclNotFinishedError case MisplacedCDATAEndStringError case CDATANotFinishedError case MisplacedXMLDeclarationError case SpaceRequiredError case SeparatorRequiredError case NMTOKENRequiredError case NAMERequiredError case PCDATARequiredError case URIRequiredError case PublicIdentifierRequiredError case LTRequiredError case GTRequiredError case LTSlashRequiredError case EqualExpectedError case TagNameMismatchError case UnfinishedTagError case StandaloneValueError case InvalidEncodingNameError case CommentContainsDoubleHyphenError case InvalidEncodingError case ExternalStandaloneEntityError case InvalidConditionalSectionError case EntityValueRequiredError case NotWellBalancedError case ExtraContentError case InvalidCharacterInEntityError case ParsedEntityRefInInternalError case EntityRefLoopError case EntityBoundaryError case InvalidURIError case URIFragmentError case NoDTDError case DelegateAbortedParseError }
apache-2.0
43eefc23b0ec76337cd9889ac0e2ee83
42.736597
339
0.667191
5.113928
false
false
false
false
saiwu-bigkoo/iOS-ViewPagerIndicator
IndicatorDemo/IndicatorDemo/BottomViewController.swift
3
2979
// // BottomViewController.swift // IndicatorDemo // // Created by Sai on 15/5/4. // Copyright (c) 2015年 Sai. All rights reserved. // import UIKit import ViewPagerIndicator class BottomViewController: UIViewController ,ViewPagerIndicatorDelegate,UIScrollViewDelegate{ @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var viewPagerIndicator: ViewPagerIndicator! var scrollViewHeight: CGFloat! override func viewDidLoad() { super.viewDidLoad() viewPagerIndicator.titles = ["Apple","Banana","Cherry","Durin"] //监听ViewPagerIndicator选中项变化 viewPagerIndicator.delegate = self scrollViewHeight = self.view.bounds.height - viewPagerIndicator.bounds.height - 20 //样式 scrollView.pagingEnabled = true scrollView.bounces = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.delegate = self //内容大小 scrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(viewPagerIndicator.count ), height: scrollViewHeight) //根据顶部的数量加入子Item for(var i = 0; i < viewPagerIndicator.count; i++ ){ let title = viewPagerIndicator.titles[i] as! String let textView = UILabel(frame: CGRectMake(self.view.bounds.width * CGFloat(i), 0, self.view.bounds.width, scrollViewHeight)) textView.text = title textView.textAlignment = NSTextAlignment.Center scrollView.addSubview(textView) } viewPagerIndicator.setTitleColorForState(UIColor.whiteColor(), state: UIControlState.Selected) // viewPagerIndicator.setTitleColorForState(UIColor.blackColor(), state: UIControlState.Normal) // viewPagerIndicator.tintColor = UIColor.brownColor() // viewPagerIndicator.showBottomLine = false // viewPagerIndicator.autoAdjustSelectionIndicatorWidth = true // viewPagerIndicator.titleFont = UIFont.systemFontOfSize(20) viewPagerIndicator.indicatorDirection = .Top viewPagerIndicator.indicatorHeight = viewPagerIndicator.bounds.height } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //点击顶部选中后回调 func indicatorChange(indicatorIndex: Int){ scrollView.scrollRectToVisible(CGRectMake(self.view.bounds.width * CGFloat(indicatorIndex), 0, self.view.bounds.width, scrollViewHeight), animated: true) } //滑动scrollview回调 func scrollViewDidEndDecelerating(scrollView: UIScrollView) { var xOffset: CGFloat = scrollView.contentOffset.x var x: Float = Float(xOffset) var width:Float = Float(self.view.bounds.width) let index = Int((x + (width * 0.5)) / width) viewPagerIndicator.setSelectedIndex(index)//改变顶部选中 } }
apache-2.0
93071da06d5213d5d9757c6eee7b18af
42.848485
161
0.690633
4.886824
false
false
false
false
oskarpearson/rileylink_ios
MinimedKit/Messages/ReadCurrentGlucosePageMessageBody.swift
1
816
// // ReadCurrentGlucosePageMessageBody.swift // RileyLink // // Created by Timothy Mecklem on 10/19/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class ReadCurrentGlucosePageMessageBody: CarelinkLongMessageBody { public let pageNum: UInt32 public let glucose: Int public let isig: Int public required init?(rxData: Data) { guard rxData.count == type(of: self).length else { return nil } self.pageNum = rxData.subdata(in: 1..<5).withUnsafeBytes({ (bytes: UnsafePointer<UInt32>) -> UInt32 in return UInt32(bigEndian: bytes.pointee) }) self.glucose = Int(rxData[6] as UInt8) self.isig = Int(rxData[8] as UInt8) super.init(rxData: rxData) } }
mit
9dcc6adb2b8d96b35028b439240cf276
26.166667
110
0.630675
3.956311
false
false
false
false
elysiumd/ios-wallet
BreadWalletTests/BRReplicatedKVStoreTests.swift
1
14213
// // BRReplicatedKVStoreTests.swift // BreadWallet // // Created by Samuel Sutch on 8/10/16. // Copyright © 2016 Aaron Voisine. All rights reserved. // import XCTest @testable import breadwallet class BRReplicatedKVStoreTestAdapter: BRRemoteKVStoreAdaptor { let testCase: XCTestCase var db = [String: (UInt64, Date, [UInt8], Bool)]() init(testCase: XCTestCase) { self.testCase = testCase db["hello"] = (1, Date(), [0, 1], false) db["removed"] = (2, Date(), [0, 2], true) for i in 1...20 { db["testkey-\(i)"] = (1, Date(), [0, UInt8(i + 2)], false) } } func keys(_ completionFunc: ([(String, UInt64, Date, BRRemoteKVStoreError?)], BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] KEYS") DispatchQueue.main.async { let res = self.db.map { (t) -> (String, UInt64, Date, BRRemoteKVStoreError?) in return (t.0, t.1.0, t.1.1, t.1.3 ? BRRemoteKVStoreError.tombstone : nil) } completionFunc(res, nil) } } func ver(_ key: String, completionFunc: (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] VER \(key)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), .notFound) } completionFunc(obj.0, obj.1, obj.3 ? .tombstone : nil) } } func get(_ key: String, version: UInt64, completionFunc: (UInt64, Date, [UInt8], BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] GET \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), [], .notFound) } if version != obj.0 { return completionFunc(0, Date(), [], .conflict) } completionFunc(obj.0, obj.1, obj.2, obj.3 ? .tombstone : nil) } } func put(_ key: String, value: [UInt8], version: UInt64, completionFunc: (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] PUT \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { if version != 0 { return completionFunc(1, Date(), .notFound) } let newObj = (UInt64(1), Date(), value, false) self.db[key] = newObj return completionFunc(1, newObj.1, nil) } if version != obj.0 { return completionFunc(0, Date(), .conflict) } let newObj = (obj.0 + 1, Date(), value, false) self.db[key] = newObj completionFunc(newObj.0, newObj.1, nil) } } func del(_ key: String, version: UInt64, completionFunc: (UInt64, Date, BRRemoteKVStoreError?) -> ()) { print("[TestRemoteKVStore] DEL \(key) \(version)") DispatchQueue.main.async { guard let obj = self.db[key] else { return completionFunc(0, Date(), .notFound) } if version != obj.0 { return completionFunc(0, Date(), .conflict) } let newObj = (obj.0 + 1, Date(), obj.2, true) self.db[key] = newObj completionFunc(newObj.0, newObj.1, nil) } } } class BRReplicatedKVStoreTest: XCTestCase { var store: BRReplicatedKVStore! var key = BRKey(privateKey: "S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy")! var adapter: BRReplicatedKVStoreTestAdapter! override func setUp() { super.setUp() adapter = BRReplicatedKVStoreTestAdapter(testCase: self) store = try! BRReplicatedKVStore(encryptionKey: key, remoteAdaptor: adapter) store.encryptedReplication = false } override func tearDown() { super.tearDown() try! store.rmdb() store = nil } func XCTAssertDatabasesAreSynced() { // this only works for keys that are not marked deleted var remoteKV = [String: [UInt8]]() for (k, v) in adapter.db { if !v.3 { remoteKV[k] = v.2 } } let allLocalKeys = try! store.localKeys() var localKV = [String: [UInt8]]() for i in allLocalKeys { if !i.4 { localKV[i.0] = try! store.get(i.0).3 } } for (k, v) in remoteKV { XCTAssertEqual(v, localKV[k] ?? []) } for (k, v) in localKV { XCTAssertEqual(v, remoteKV[k] ?? []) } } // MARK: - local db tests func testSetLocalDoesntThrow() { let (v1, t1) = try! store.set("hello", value: [0, 0, 0], localVer: 0) XCTAssertEqual(1, v1) XCTAssertNotNil(t1) } func testSetLocalIncrementsVersion() { try! store.set("hello", value: [0, 1], localVer: 0) XCTAssertEqual(try! store.localVersion("hello").0, 1) } func testSetThenGet() { let (v1, t1) = try! store.set("hello", value: [0, 1], localVer: 0) let (v, t, d, val) = try! store.get("hello") XCTAssertEqual(val, [0, 1]) XCTAssertEqual(v1, v) XCTAssertEqualWithAccuracy(t1.timeIntervalSince1970, t.timeIntervalSince1970, accuracy: 0.001) XCTAssertEqual(d, false) } func testSetThenSetIncrementsVersion() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (v2, _) = try! store.set("hello", value: [0, 2], localVer: v1) XCTAssertEqual(v2, v1 + 1) } func testSetThenDel() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (v2, _) = try! store.del("hello", localVer: v1) XCTAssertEqual(v2, v1 + 1) } func testSetThenDelThenGet() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) try! store.del("hello", localVer: v1) let (v2, _, d, _) = try! store.get("hello") XCTAssert(d) XCTAssertEqual(v2, v1 + 1) } func testSetWithIncorrectFirstVersionFails() { XCTAssertThrowsError(try store.set("hello", value: [0, 1], localVer: 1)) } func testSetWithStaleVersionFails() { try! store.set("hello", value: [0, 1], localVer: 0) XCTAssertThrowsError(try store.set("hello", value: [0, 1], localVer: 0)) } func testGetNonExistentKeyFails() { XCTAssertThrowsError(try store.get("hello")) } func testGetNonExistentKeyVersionFails() { XCTAssertThrowsError(try store.get("hello", version: 1)) } func testGetAllKeys() { let (v1, t1) = try! store.set("hello", value: [0, 1], localVer: 0) let lst = try! store.localKeys() XCTAssertEqual(1, lst.count) XCTAssertEqual("hello", lst[0].0) XCTAssertEqual(v1, lst[0].1) XCTAssertEqualWithAccuracy(t1.timeIntervalSince1970, lst[0].2.timeIntervalSince1970, accuracy: 0.001) XCTAssertEqual(0, lst[0].3) XCTAssertEqual(false, lst[0].4) } func testSetRemoteVersion() { let (v1, _) = try! store.set("hello", value: [0, 1], localVer: 0) let (newV, _) = try! store.setRemoteVersion("hello", localVer: v1, remoteVer: 1) XCTAssertEqual(newV, v1 + 1) let rmv = try! store.remoteVersion("hello") XCTAssertEqual(rmv, 1) } // MARK: - syncing tests func testBasicSyncGetAllObjects() { let exp = expectation(withDescription: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) let allKeys = try! store.localKeys() XCTAssertEqual(adapter.db.count - 1, allKeys.count) // minus 1: there is a deleted key that needent be synced XCTAssertDatabasesAreSynced() } func testSyncTenTimes() { let exp = expectation(withDescription: "sync") var n = 10 var handler: (e: ErrorProtocol?) -> () = { e in return } handler = { (e: ErrorProtocol?) in XCTAssertNil(e) if n > 0 { self.store.syncAllKeys(handler) n -= 1 } else { exp.fulfill() } } handler(e: nil) waitForExpectations(withTimeout: 2, handler: nil) XCTAssertDatabasesAreSynced() } func testSyncAddsLocalKeysToRemote() { store.syncImmediately = false try! store.set("derp", value: [0, 1], localVer: 0) let exp = expectation(withDescription: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertEqual(adapter.db["derp"]!.2, [0, 1]) XCTAssertDatabasesAreSynced() } func testSyncSavesRemoteVersion() { let exp = expectation(withDescription: "sync") store.syncAllKeys { err in XCTAssertNil(err) exp.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) let rv = try! store.remoteVersion("hello") XCTAssertEqual(adapter.db["hello"]!.0, 1) // it should not have done any mutations XCTAssertEqual(adapter.db["hello"]!.0, rv) // only saved the remote version XCTAssertDatabasesAreSynced() } func testSyncPreventsAnotherConcurrentSync() { let exp1 = expectation(withDescription: "sync") let exp2 = expectation(withDescription: "sync2") store.syncAllKeys { e in exp1.fulfill() } store.syncAllKeys { (e) in XCTAssertEqual(e, BRReplicatedKVStoreError.alreadyReplicating) exp2.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) } func testLocalDeleteReplicates() { let exp1 = expectation(withDescription: "sync1") store.syncImmediately = false try! store.set("goodbye_cruel_world", value: [0, 1], localVer: 0) store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() try! store.del("goodbye_cruel_world", localVer: try! store.localVersion("goodbye_cruel_world").0) let exp2 = expectation(withDescription: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() XCTAssertEqual(adapter.db["goodbye_cruel_world"]!.3, true) } func testLocalUpdateReplicates() { let exp1 = expectation(withDescription: "sync1") store.syncImmediately = false try! store.set("goodbye_cruel_world", value: [0, 1], localVer: 0) store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() try! store.set("goodbye_cruel_world", value: [1, 0, 0, 1], localVer: try! store.localVersion("goodbye_cruel_world").0) let exp2 = expectation(withDescription: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testRemoteDeleteReplicates() { let exp1 = expectation(withDescription: "sync1") store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() adapter.db["hello"]?.0 += 1 adapter.db["hello"]?.1 = Date() adapter.db["hello"]?.3 = true let exp2 = expectation(withDescription: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() let (_, _, h, _) = try! store.get("hello") XCTAssertEqual(h, true) let exp3 = expectation(withDescription: "sync3") store.syncAllKeys { (e) in XCTAssertNil(e) exp3.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testRemoteUpdateReplicates() { let exp1 = expectation(withDescription: "sync1") store.syncAllKeys { (e) in XCTAssertNil(e) exp1.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() adapter.db["hello"]?.0 += 1 adapter.db["hello"]?.1 = Date() adapter.db["hello"]?.2 = [0, 1, 1, 1, 1, 1, 11 , 1, 1, 1, 1, 1, 0x8c] let exp2 = expectation(withDescription: "sync2") store.syncAllKeys { (e) in XCTAssertNil(e) exp2.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() let (_, _, _, b) = try! store.get("hello") XCTAssertEqual(b, [0, 1, 1, 1, 1, 1, 11 , 1, 1, 1, 1, 1, 0x8c]) let exp3 = expectation(withDescription: "sync3") store.syncAllKeys { (e) in XCTAssertNil(e) exp3.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertDatabasesAreSynced() } func testEnableEncryptedReplication() { adapter.db.removeAll() store.encryptedReplication = true try! store.set("derp", value: [0, 1], localVer: 0) let exp = expectation(withDescription: "sync") store.syncAllKeys { (err) in XCTAssertNil(err) exp.fulfill() } waitForExpectations(withTimeout: 1, handler: nil) XCTAssertNotEqual(adapter.db["derp"]!.2, [0, 1]) } }
mit
afb1dfcb8cc9bcc8cdfcfd832fe29edc
34.979747
123
0.562623
3.970942
false
true
false
false
cezarywojcik/Operations
Sources/Core/Shared/OperationCondition.swift
1
3465
// // OperationCondition.swift // YapDB // // Created by Daniel Thorpe on 25/06/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** The result of an OperationCondition. Either the condition is satisfied, indicated by `.Satisfied` or it has failed. In the failure case, an `ErrorType` must be associated with the result. */ public enum ConditionResult { /// Indicates that the condition is satisfied case satisfied /// Indicates that the condition failed with an associated error. case failed(Error) } internal extension ConditionResult { var error: Error? { switch self { case .failed(let error): return error default: return .none } } } public typealias OperationConditionResult = ConditionResult /** Types which conform to `OperationCondition` can be added to `Operation` subclasses before they are added to an `OperationQueue`. If the condition returns an `NSOperation` dependency, the dependency relationship will be set and it is added to the queue automatically. Evaluation of the condition only occurs once the dependency has executed. It is possible to support asynchronous evaluation of the condition, as the results, an `OperationConditionResult` is returned in a completion block. */ public protocol OperationCondition { /** The name of the condition. - parameter name: a String */ var name: String { get } /** A flag to indicate whether this condition is mutually exclusive. Meaning that only one condition can be evaluated at a time. Other `Operation` instances which have this condition will wait in a `.Pending` state - i.e. not get executed. - parameter isMutuallyExclusive: a Bool */ var isMutuallyExclusive: Bool { get } /** Some conditions may have the ability to satisfy the condition if another operation is executed first. Use this method to return an operation that (for example) asks for permission to perform the operation. - parameter operation: The `Operation` to which the condition has been added. - returns: An `NSOperation`, if a dependency should be automatically added. - note: Only a single operation may be returned. */ func dependencyForOperation(_ operation: AdvancedOperation) -> Operation? /** Evaluate the condition, to see if it has been satisfied. - parameter operation: the `Operation` which this condition is attached to. - parameter completion: a closure which receives an `OperationConditionResult`. */ func evaluateForOperation(_ operation: AdvancedOperation, completion: (OperationConditionResult) -> Void) } internal func evaluateOperationConditions(_ conditions: [OperationCondition], operation: AdvancedOperation, completion: @escaping ([Error]) -> Void) { let group = DispatchGroup() var results = [OperationConditionResult?](repeating: .none, count: conditions.count) for (index, condition) in conditions.enumerated() { group.enter() condition.evaluateForOperation(operation) { result in results[index] = result group.leave() } } group.notify(queue: Queue.default.queue) { var failures: [Error] = results.compactMap { $0?.error } if operation.isCancelled { failures.append(OperationError.conditionFailed) } completion(failures) } }
mit
0d373f71836ae260324764da2309cbfc
29.130435
150
0.702453
4.859748
false
false
false
false
huangboju/Moots
Examples/NumberFormatter/NSNumberFormatter/UIBarButtonItem+Bage.swift
1
9085
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // import UIKit extension UIBarButtonItem { private struct AssociatedKeys { static var badgeKey = "badgeKey" static var badgeValueKey = "badgeValueKey" static var badgeBGColorKey = "badgeBGColorKey" static var badgeTextColorKey = "badgeTextColorKey" static var badgeFontKey = "badgeFontKey" static var badgePaddingKey = "badgePaddingKey" static var badgeMinSizeKey = "badgeMinSizeKey" static var badgeOriginXKey = "badgeOriginXKey" static var badgeOriginYKey = "badgeOriginYKey" static var shouldHideBadgeAtZeroKey = "shouldHideBadgeAtZeroKey" static var shouldAnimateBadgeKey = "shouldAnimateBadgeKey" } func badgeInit() { var superview: UIView? var defaultOriginX: CGFloat = 0 if let customView = self.customView { superview = customView defaultOriginX = superview!.frame.width - badge!.frame.width / 2 } else if responds(to: #selector(getter: UITouch.view)) { if let view = value(forKey: "_view") { superview = (view as? UIView) defaultOriginX = superview!.frame.width - badge!.frame.width } } superview?.addSubview(badge!) badgeOriginX = defaultOriginX + 3 } func refreshBadge() { badge?.textColor = badgeTextColor badge?.backgroundColor = badgeBGColor badge?.font = badgeFont if badgeValue == nil || badgeValue == "" || (badgeValue == "0" && shouldHideBadgeAtZero) { badge?.isHidden = true } else { badge?.isHidden = false updateBadgeValue(animated: true) } } var badgeExpectedSize: CGSize { let frameLabel = duplicateLabel(labelToCopy: badge!) frameLabel.sizeToFit() return frameLabel.frame.size } func updateBadgeFrame() { let expectedLabelSize = badgeExpectedSize var minHeight = expectedLabelSize.height minHeight = max(minHeight, badgeMinSize) var minWidth = expectedLabelSize.width let padding = badgePadding minWidth = max(minWidth, minHeight) badge?.layer.masksToBounds = true badge?.layer.cornerRadius = (minHeight + padding) / 2 badge?.frame = CGRect(x: badgeOriginX, y: badgeOriginY, width: minWidth + padding, height: minHeight + padding) } func updateBadgeValue(animated: Bool) { if animated && shouldAnimateBadge && badge?.text != badgeValue { let animation = CABasicAnimation(keyPath: "transform.scale") animation.fromValue = NSNumber(value: 1.5) animation.toValue = NSNumber(value: 1) animation.duration = 0.2 animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 1.3, 1, 1) badge?.layer.add(animation, forKey: "bounceAnimation") } badge?.text = badgeValue if animated && shouldAnimateBadge { UIView.animate(withDuration: 0.2, animations: { self.updateBadgeFrame() }) } else { updateBadgeFrame() } } func removeBadge() { UIView.animate(withDuration: 0.2, animations: { self.badge?.transform = CGAffineTransform(scaleX: 0, y: 0) }) { (flag) in self.badge?.removeFromSuperview() self.badge = nil } } func duplicateLabel(labelToCopy: UILabel) -> UILabel { let duplicateLabel = UILabel(frame: labelToCopy.frame) duplicateLabel.text = labelToCopy.text duplicateLabel.font = labelToCopy.font return duplicateLabel } var badge: UILabel? { get { var label = objc_getAssociatedObject(self, &AssociatedKeys.badgeKey) as? UILabel if label == nil { label = UILabel(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) self.badge = label! badgeInit() customView?.addSubview(label!) label?.textAlignment = .center } return label! } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var badgeValue: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.badgeValueKey) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeValueKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) updateBadgeValue(animated: true) refreshBadge() } } var badgeBGColor: UIColor { get { let color = objc_getAssociatedObject(self, &AssociatedKeys.badgeBGColorKey) as? UIColor return color ?? UIColor.red } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeBGColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) updateBadgeValue(animated: true) refreshBadge() } } var badgeTextColor: UIColor { get { let color = objc_getAssociatedObject(self, &AssociatedKeys.badgeTextColorKey) as? UIColor return color ?? UIColor.white } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeTextColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) updateBadgeValue(animated: true) refreshBadge() if badge != nil { refreshBadge() } } } /// Defatul UIFont.smallSystemFontSize var badgeFont: UIFont { get { let font = objc_getAssociatedObject(self, &AssociatedKeys.badgeFontKey) as? UIFont return font ?? UIFont.systemFont(ofSize: UIFont.smallSystemFontSize) } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeFontKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { refreshBadge() } } } /// Defatult 1.5 var badgePadding: CGFloat { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.badgePaddingKey) as? CGFloat return number ?? 1.5 } set { objc_setAssociatedObject(self, &AssociatedKeys.badgePaddingKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { updateBadgeFrame() } } } /// Defatult 8 var badgeMinSize: CGFloat { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.badgeMinSizeKey) as? CGFloat return number ?? 8 } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeMinSizeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { updateBadgeFrame() } } } /// Defatul 0 var badgeOriginX: CGFloat { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.badgeOriginXKey) as? CGFloat return number ?? 0 } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeOriginXKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { updateBadgeFrame() } } } /// Defatul -4 var badgeOriginY: CGFloat { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.badgeOriginYKey) as? CGFloat return number ?? -4 } set { objc_setAssociatedObject(self, &AssociatedKeys.badgeOriginYKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { updateBadgeFrame() } } } var shouldHideBadgeAtZero: Bool { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.shouldHideBadgeAtZeroKey) as? NSNumber return number?.boolValue ?? true } set { let number = NSNumber(value: newValue) objc_setAssociatedObject(self, &AssociatedKeys.shouldHideBadgeAtZeroKey, number, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { updateBadgeFrame() } } } var shouldAnimateBadge: Bool { get { let number = objc_getAssociatedObject(self, &AssociatedKeys.shouldAnimateBadgeKey) as? NSNumber return number?.boolValue ?? true } set { let number = NSNumber(value: newValue) objc_setAssociatedObject(self, &AssociatedKeys.shouldAnimateBadgeKey, number, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if badge != nil { refreshBadge() } } } }
mit
302bca593f383dd1f7dfa3c54a49a902
32.389706
128
0.578507
5.020453
false
false
false
false
idlebear/useful_things
Munkres.swift
1
11109
/***************************************************************************** ****************************************************************************** Copyright 2017 -- Barry Gilhuly 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. ****************************************************************************** ******************************************************************************/ // // - Make the stored data type a generic, but that is going to require // some negotiation with the swift gods.... // public func calculateMunkres( withData data: [[Double]] ) -> [(Int,Int)] { return Munkres(withData: data).resolve() } fileprivate class Munkres { var dataArray: [[Double]] = [[]] let rows: Int let cols: Int var zeros: [[ZeroState]] var coveredRows: [Int] var coveredCols: [Int] let rotated: Bool var startingPathRow: Int = 0 var startingPathCol: Int = 0 enum InternalState { case ensmallen, stars, covers, prime, augment, minimize, done } enum ZeroState { case none, starred, prime } init( withData data: [[Double]] ) { let dataRows = data.count let dataCols = data[0].count if dataCols >= dataRows { dataArray = data cols = dataCols rows = dataRows rotated = false } else { rotated = true cols = dataRows rows = dataCols for col in 0..<cols { dataArray.append([]) for row in 0..<rows { dataArray[col].append(data[row][col]) } } } zeros = Array<Array<ZeroState>>(repeating: Array<ZeroState>(repeating: .none, count: cols), count: rows) coveredCols = Array<Int>(repeating: 0, count: cols) coveredRows = Array<Int>(repeating: 0, count: rows) } /** Step 1: Ensmallen! Minimize each row by subtracting the value of the smallest item in that row from each element in the row (resulting in at least one zero value) */ func ensmallenEachRow() -> InternalState { // Step 1 for row in 0..<rows { var smallest = dataArray[row][0] for col in 1..<cols { if dataArray[row][col] < smallest { smallest = dataArray[row][col] } } for col in 0..<cols { dataArray[row][col] -= smallest } } return .stars } /** Step 2: Stars For each uncovered row/column, mark the first zero found, cover that row and continue */ func starTheZeros() -> InternalState { // Step 2 for row in 0..<rows { for col in 0..<cols { if dataArray[row][col] == 0 && coveredRows[row] == 0 && coveredCols[col] == 0 { zeros[row][col] = .starred coveredCols[col] = 1 coveredRows[row] = 1 } } } clearCovers() return .covers } // MARK: Step 3 support functions //-------------------------------------------------------- func clearCovers() -> Void { for col in 0..<cols { coveredCols[col] = 0 } for row in 0..<rows { coveredRows[row] = 0 } } /** Step 3: Apply covers Cover each column containing a starred zero. If there are the same number of columns covered as there are rows, the starred zeros represent the complete set of assignments. Go to .done. Otherwise, continue to step 4, prime. */ func applyCovers() -> InternalState { for row in 0..<rows { for col in 0..<cols { if zeros[row][col] == .starred { coveredCols[col] = 1 } } } var coveredCount = 0 for covered in coveredCols { if covered == 1 { coveredCount += 1 } } if coveredCount == rows { return .done } return .prime } // MARK: Step 4 support functions //-------------------------------------------------------- func findNextUncoveredZero() -> (Int,Int)? { for row in 0..<rows { for col in 0..<cols { if dataArray[row][col] == 0 && coveredCols[col] == 0 && coveredRows[row] == 0 { return (row,col) } } } return nil } func find( zeroState state: ZeroState, inRow row: Int ) -> Int? { for col in 0..<cols { if zeros[row][col] == state { return col } } return nil } /** Step 4: Prime Find the first non-covered zero and prime it. If there is no non-starred zero in this row, go to step 5, augmentation. Otherwise, cover this row and uncover the column containing the starred zero. Continue until there are no uncovered zeros left, then go to step 6, minimize. */ func primeZeros() -> InternalState { while true { guard let(row, col) = findNextUncoveredZero() else { return .minimize } zeros[row][col] = .prime if let col = find( zeroState: .starred, inRow: row) { coveredCols[col] = 0 coveredRows[row] = 1 } else { startingPathRow = row startingPathCol = col break } } return .augment } // MARK: Step 5 support functions //-------------------------------------------------------- func find( zeroState state: ZeroState, inCol col: Int ) -> Int? { for row in 0..<rows { if zeros[row][col] == state { return row } } return nil } func augment( zeroPath path: [(Int,Int)] ) -> Void { for (row,col) in path { if zeros[row][col] == .starred { zeros[row][col] = .none } else { zeros[row][col] = .starred } } } func erasePrimes() -> Void { for row in 0..<rows { for col in 0..<cols { if zeros[row][col] == .prime { zeros[row][col] = .none } } } } /** Step 5: Augmentation Construct a series of alternating primed and starred zeros as follows: Let Z0 represent the uncovered primed zero found in step 4. Let Z1 represent the starred zero in the same column as Z0 (if it exists) Let Z2 represent the primed zero in the row of Z1 (always exists) Continue until the series terminates at a primed zero that has no starred zero in its column. Unstar each starred zero (Z1) of the series, star each primed zero (Z0) of the series, erase all primes and uncover all rows and columns. Return to step 3, covers. */ func augmentation() -> InternalState { // Step 5 var path:[(Int,Int)] = [(startingPathRow, startingPathCol)] while true { let col = path.last!.1 if let row = find(zeroState: .starred, inCol: col) { path.append((row,col)) if let col = find(zeroState: .prime, inRow: row) { path.append((row,col)) } } else { break } } augment(zeroPath: path) clearCovers() erasePrimes() return .covers } // MARK: Step 6 support functions //-------------------------------------------------------- func findSmallestUncovered() -> Double { var minimum = Double.infinity for row in 0..<rows { for col in 0..<cols { if coveredCols[col] == 0 && coveredRows[row] == 0 { if dataArray[row][col] < minimum { minimum = dataArray[row][col] } } } } return minimum } /** Step 6: Minimize Add the smallest uncovered value to each covered row, and subtrace it from every element in every uncovered column. Return to step 4, prime. */ func minimize() -> InternalState { let minimumValue = findSmallestUncovered() for row in 0..<rows { for col in 0..<cols { if coveredRows[row] == 1 { dataArray[row][col] += minimumValue } if coveredCols[col] == 0 { dataArray[row][col] -= minimumValue } } } return .prime } func resolve() -> [(Int, Int)] { var nextState = InternalState.ensmallen munkresCycle: while true { switch nextState { case .ensmallen: nextState = ensmallenEachRow() case .stars: nextState = starTheZeros() case .covers: nextState = applyCovers() case .prime: nextState = primeZeros() case .augment: nextState = augmentation() case .minimize: nextState = minimize() case .done: break munkresCycle } } var result: [(Int,Int)] = [] findZeros: for row in 0..<rows { for col in 0..<cols { if zeros[row][col] == .starred { result.append(rotated ? (col,row) : (row, col)) continue findZeros } } } return result } }
mit
e785a9818330f34b0357b9eb038db99e
28.862903
112
0.483302
4.798704
false
false
false
false
naoto0822/swift-ec-client
SwiftECClient/APIRequest.swift
1
2504
// // APIRequest.swift // SwiftECClient // // Created by naoto yamaguchi on 2014/06/10. // Copyright (c) 2014 naoto yamaguchi. All rights reserved. // import UIKit protocol APIRequestDelegate: NSObjectProtocol { func didRequest(data: NSData, responseHeaders: NSDictionary, error: NSError?) } class APIRequest: NSObject, NSURLSessionDelegate, NSURLSessionDataDelegate { var delegate: APIRequestDelegate? var responseData: NSMutableData = NSMutableData() var responseHeaders: NSDictionary = NSDictionary() init(delegate: APIRequestDelegate) { super.init() self.delegate = delegate self.responseData = NSMutableData() } // APPID class is .gitignore func request() { let appID:String = APPID.appID() let urlString:String = "http://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?appid=\(appID)&category_id=1034&hits=20" let url: NSURL = NSURL.URLWithString(urlString) let session: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue()) let dataTask: NSURLSessionDataTask = session.dataTaskWithURL(url) dataTask.resume() } func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) { let statusCode:Int = (response as NSHTTPURLResponse).statusCode if (statusCode >= 400) { let dict: Dictionary = [NSLocalizedDescriptionKey: "statusCode error"] let error: NSError = NSError.errorWithDomain("swift.sample.app", code: statusCode, userInfo: dict) URLSession(session, task: dataTask, didCompleteWithError: error) return } self.responseHeaders = (response as NSHTTPURLResponse).allHeaderFields completionHandler(.Allow) } func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) { self.responseData.appendData(data) } func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) { self.delegate?.didRequest(self.responseData, responseHeaders: self.responseHeaders, error: error) } }
mit
73d201db36fe4e8ccdb94cf0dd607dbf
39.387097
188
0.669728
5.552106
false
false
false
false
cfraz89/RxSwift
Tests/RxSwiftTests/BagTest.swift
8
7755
// // BagTest.swift // Tests // // Created by Krunoslav Zaher on 8/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // // testable import doesn't work well in Linux #if !os(Linux) import XCTest @testable import RxSwift final class BagTest : RxTest { override var accumulateStatistics: Bool { return false } } extension BagTest { typealias DoSomething = () -> Void typealias KeyType = Bag<DoSomething>.KeyType func numberOfActionsAfter<T>(_ nInsertions: Int, deletionsFromStart: Int, createNew: () -> T, bagAction: (RxMutableBox<Bag<T>>) -> ()) { let bag = RxMutableBox(Bag<T>()) var keys = [KeyType]() for _ in 0 ..< nInsertions { keys.append(bag.value.insert(createNew())) } for i in 0 ..< deletionsFromStart { let key = keys[i] XCTAssertTrue(bag.value.removeKey(key) != nil) } bagAction(bag) } func testBag_deletionsFromStart() { for i in 0 ..< 50 { for j in 0 ... i { var numberForEachActions = 0 var numberObservers = 0 var numberDisposables = 0 numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> DoSomething in { () -> () in numberForEachActions += 1 } }, bagAction: { (bag: RxMutableBox<Bag<DoSomething>>) in bag.value.forEach { $0() }; XCTAssertTrue(bag.value.count == i - j) } ) numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> (Event<Int>) -> () in { _ in numberObservers += 1 } }, bagAction: { (bag: RxMutableBox<Bag<(Event<Int>) -> ()>>) in dispatch(bag.value, .next(1)); XCTAssertTrue(bag.value.count == i - j) } ) numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> Disposable in Disposables.create { numberDisposables += 1 } }, bagAction: { (bag: RxMutableBox<Bag<Disposable>>) in disposeAll(in: bag.value); XCTAssertTrue(bag.value.count == i - j) } ) XCTAssertTrue(numberForEachActions == i - j) XCTAssertTrue(numberObservers == i - j) XCTAssertTrue(numberDisposables == i - j) } } } func numberOfActionsAfter<T>(_ nInsertions: Int, deletionsFromEnd: Int, createNew: () -> T, bagAction: (RxMutableBox<Bag<T>>) -> ()) { let bag = RxMutableBox(Bag<T>()) var keys = [KeyType]() for _ in 0 ..< nInsertions { keys.append(bag.value.insert(createNew())) } for i in 0 ..< deletionsFromEnd { let key = keys[keys.count - 1 - i] XCTAssertTrue(bag.value.removeKey(key) != nil) } bagAction(bag) } func testBag_deletionsFromEnd() { for i in 0 ..< 30 { for j in 0 ... i { var numberForEachActions = 0 var numberObservers = 0 var numberDisposables = 0 numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> DoSomething in { () -> () in numberForEachActions += 1 } }, bagAction: { (bag: RxMutableBox<Bag<DoSomething>>) in bag.value.forEach { $0() }; XCTAssertTrue(bag.value.count == i - j) } ) numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> (Event<Int>) -> () in { _ in numberObservers += 1 } }, bagAction: { (bag: RxMutableBox<Bag<(Event<Int>) -> ()>>) in dispatch(bag.value, .next(1)); XCTAssertTrue(bag.value.count == i - j) } ) numberOfActionsAfter(i, deletionsFromStart: j, createNew: { () -> Disposable in Disposables.create { numberDisposables += 1 } }, bagAction: { (bag: RxMutableBox<Bag<Disposable>>) in disposeAll(in: bag.value); XCTAssertTrue(bag.value.count == i - j) } ) XCTAssertTrue(numberForEachActions == i - j) XCTAssertTrue(numberObservers == i - j) XCTAssertTrue(numberDisposables == i - j) } } } func testBag_immutableForeach() { for breakAt in 0 ..< 50 { var increment1 = 0 var increment2 = 0 var increment3 = 0 let bag1 = RxMutableBox(Bag<DoSomething>()) let bag2 = RxMutableBox(Bag<(Event<Int>) -> ()>()) let bag3 = RxMutableBox(Bag<Disposable>()) for _ in 0 ..< 50 { _ = bag1.value.insert({ if increment1 == breakAt { bag1.value.removeAll() } increment1 += 1 }) _ = bag2.value.insert({ _ in if increment2 == breakAt { bag2.value.removeAll() } increment2 += 1 }) _ = bag3.value.insert(Disposables.create { _ in if increment3 == breakAt { bag3.value.removeAll() } increment3 += 1 }) } for _ in 0 ..< 2 { bag1.value.forEach { c in c() } dispatch(bag2.value, .next(1)) disposeAll(in: bag3.value) } XCTAssertEqual(increment1, 50) } } func testBag_removeAll() { var numberForEachActions = 0 var numberObservers = 0 var numberDisposables = 0 numberOfActionsAfter(100, deletionsFromStart: 0, createNew: { () -> DoSomething in { () -> () in numberForEachActions += 1 } }, bagAction: { (bag: RxMutableBox<Bag<DoSomething>>) in bag.value.removeAll(); bag.value.forEach { $0() } } ) numberOfActionsAfter(100, deletionsFromStart: 0, createNew: { () -> (Event<Int>) -> () in { _ in numberObservers += 1 } }, bagAction: { (bag: RxMutableBox<Bag<(Event<Int>) -> ()>>) in bag.value.removeAll(); dispatch(bag.value, .next(1)); } ) numberOfActionsAfter(100, deletionsFromStart: 0, createNew: { () -> Disposable in Disposables.create { numberDisposables += 1 } }, bagAction: { (bag: RxMutableBox<Bag<Disposable>>) in bag.value.removeAll(); disposeAll(in: bag.value); } ) XCTAssertTrue(numberForEachActions == 0) XCTAssertTrue(numberObservers == 0) XCTAssertTrue(numberDisposables == 0) } func testBag_complexityTestFromFront() { var bag = Bag<Disposable>() let limit = 10000 var increment = 0 var keys: [Bag<Disposable>.KeyType] = [] for _ in 0..<limit { keys.append(bag.insert(Disposables.create { increment += 1 })) } for i in 0..<limit { _ = bag.removeKey(keys[i]) } } func testBag_complexityTestFromEnd() { var bag = Bag<Disposable>() let limit = 10000 var increment = 0 var keys: [Bag<Disposable>.KeyType] = [] for _ in 0..<limit { keys.append(bag.insert(Disposables.create { increment += 1 })) } for i in 0..<limit { _ = bag.removeKey(keys[limit - 1 - i]) } } } #endif
mit
83b1e9258560b245eb2f6508a3b9a506
33.7713
153
0.495744
4.574631
false
true
false
false
thoughtbot/DeltaTodoExample
Source/Controllers/TodoTableViewController.swift
1
2876
import UIKit class TodoTableViewController: UITableViewController { @IBOutlet weak var filterSegmentedControl: UISegmentedControl! var viewModel = TodosViewModel(todos: []) { didSet { tableView.reloadData() } } override func viewDidLoad() { filterSegmentedControl.addTarget(self, action: "filterValueChanged", forControlEvents: .ValueChanged) store.activeFilter.producer.startWithNext { filter in self.filterSegmentedControl.selectedSegmentIndex = filter.rawValue } store.activeTodos.startWithNext { todos in self.viewModel = TodosViewModel(todos: todos) } } } // MARK: Actions extension TodoTableViewController { @IBAction func addTapped(sender: UIBarButtonItem) { let alertController = UIAlertController(title: "Create", message: "Create a new todo item", preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler() { textField in textField.placeholder = "Name" } alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { _ in }) alertController.addAction(UIAlertAction(title: "Create", style: .Default) { _ in guard let name = alertController.textFields?.first?.text else { return } store.dispatch(CreateTodoAction(name: name)) }) presentViewController(alertController, animated: false, completion: nil) } func filterValueChanged() { guard let newFilter = TodoFilter(rawValue: filterSegmentedControl.selectedSegmentIndex) else { return } store.dispatch(SetFilterAction(filter: newFilter)) } } // MARK: UITableViewController extension TodoTableViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.todos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("todoCell", forIndexPath: indexPath) as! TodoTableViewCell let todo = viewModel.todoForIndexPath(indexPath) cell.configure(todo) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let todo = viewModel.todoForIndexPath(indexPath) store.dispatch(ToggleCompletedAction(todo: todo)) tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let todo = viewModel.todoForIndexPath(indexPath) store.dispatch(DeleteTodoAction(todo: todo)) } } }
mit
3add9051415a036193aa49a53f0d6026
35.405063
157
0.70306
5.457306
false
false
false
false
jopamer/swift
test/Serialization/typealias.swift
1
1312
// RUN: %empty-directory(%t) // RUN: %target-build-swift -module-name alias -emit-module -o %t %S/Inputs/alias.swift // RUN: %target-build-swift -I %t %s -module-name typealias -emit-module-path %t/typealias.swiftmodule -o %t/typealias.o // RUN: llvm-bcanalyzer %t/alias.swiftmodule | %FileCheck %s // RUN: %target-build-swift -I %t %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck -check-prefix=OUTPUT %s // REQUIRES: executable_test // CHECK-NOT: UnknownCode import alias var i : MyInt64 i = 42 var j : AnotherInt64 = i print("\(j)\n", terminator: "") // OUTPUT: 42 var both : TwoInts both = (i, j) var named : ThreeNamedInts named.b = 64 print("\(named.b)\n", terminator: "") // OUTPUT: 64 var none : None none = () func doNothing() {} var nullFn : NullFunction = doNothing func negate(x: MyInt64) -> AnotherInt64 { return -x } var monadic : IntFunction = negate print("\(monadic(i))\n", terminator: "") // OUTPUT: -42 func subtract(_ t : (x: MyInt64, y: MyInt64)) -> MyInt64 { return t.x - t.y } var dyadic : TwoIntFunction = subtract print("\(dyadic((named.b, i))) \(dyadic(both))\n", terminator: "") // OUTPUT: 22 0 // Used for tests that only need to be type-checked. func check(_: BaseAlias) { } let x: GG<Int> = 0 let x2: GInt = 1 public typealias TestUnbound = UnboundAlias
apache-2.0
4a067a51c66dfcbe69ae7e7526253319
21.62069
120
0.660823
2.883516
false
true
false
false
shuuchen/Swift-Down-Video
source/ContainerViewController.swift
1
18787
// // ContainerViewController.swift // table_template // // Created by Shuchen Du on 2015/10/07. // Copyright (c) 2015年 Shuchen Du. All rights reserved. // import UIKit import CoreData class ContainerViewController: UIViewController { @IBOutlet weak var containerVisualView: UIVisualEffectView! @IBOutlet weak var label: UILabel! @IBOutlet weak var indicator: UIActivityIndicatorView! @IBOutlet weak var videoCollectionView: UICollectionView! @IBOutlet weak var underLabel: UILabel! var videoMaps: NSMutableArray! var videoJson: UNIJsonNode! var videoTitle: String! var videoFormat: String! var videoSize: String! var videoDuration: String! var originalUrl: String! var _originalUrl: String! let defaultResume = "default resume".dataUsingEncoding(NSUTF8StringEncoding)! var videoID: String! var videoImgUrlStr: String! var cellBackgroundColor: UIColor! var hilightedCellBackgroundColor = UIColor( red: 255/255.0, green: 52/255.0, blue: 179/255.0, alpha: 1) var url: NSURL! var manager: NSFileManager! var urlOfDocumentFolder: NSURL! var urlOfVideoFolder: NSURL! var urlOfImgFolder: NSURL! var session: NSURLSession! var configuration: NSURLSessionConfiguration! var appDelegate: AppDelegate! var managedContext: NSManagedObjectContext! var entityVideoData: String! // recover unfinished download func recoverDownload() { let error: NSError? var videoArr: [VideoData] // fetch existing videos from core data let fetchRequest = NSFetchRequest(entityName: entityVideoData) videoArr = (try! managedContext.executeFetchRequest(fetchRequest)) as! [VideoData] // error happens if let theErr = error { } else { if videoArr.count > 0 { for v in videoArr { if v.resumeData != self.defaultResume { let task = session.downloadTaskWithResumeData(v.resumeData) task.resume() } } } } } override func viewDidLoad() { super.viewDidLoad() //recoverDownload() } // session operation override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // invalidate session if no tasks exist session.finishTasksAndInvalidate() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // kick off session let configurationIdentifier = NSDate().description configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configurationIdentifier) configuration.timeoutIntervalForRequest = 15.0 session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) underLabel.hidden = true } // init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // file manager manager = NSFileManager() // url of Document folder var error: NSError? urlOfDocumentFolder = try! manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) if let theErr = error { print("cannot get the url of Document folder: \(theErr.description))") } // url of video folder urlOfVideoFolder = urlOfDocumentFolder.URLByAppendingPathComponent("videos", isDirectory: true) if !manager.fileExistsAtPath(urlOfVideoFolder.path!) { do { // create video folder try manager.createDirectoryAtURL(urlOfVideoFolder, withIntermediateDirectories: true, attributes: nil) } catch let error1 as NSError { error = error1 } if let theErr = error { print("cannot create video folder: \(theErr.description)") } } // url of image folder urlOfImgFolder = urlOfDocumentFolder.URLByAppendingPathComponent("imgs", isDirectory: true) if !manager.fileExistsAtPath(urlOfImgFolder.path!) { do { // create image folder try manager.createDirectoryAtURL(urlOfImgFolder, withIntermediateDirectories: true, attributes: nil) } catch let error1 as NSError { error = error1 } if let theErr = error { print("cannot create image folder: \(theErr.description)") } } // init core data appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate managedContext = appDelegate.managedObjectContext entityVideoData = NSStringFromClass(VideoData.classForCoder()) } // video json download func downloadVideoJSON() { let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue, { dispatch_sync(queue, { self.videoJson = FetchVideo.fetch(self.videoID) if self.videoJson == nil { print("json nil 1") return } self.videoTitle = self.videoJson.object["title"] as? String self.videoImgUrlStr = self.videoJson.object["img"] as! String if let map = self.videoJson.object["map"] as? NSArray { self.videoMaps = map.mutableCopy() as! NSMutableArray } else { return } // remove "0B" items from videoMaps for v in self.videoMaps { let size = v.objectAtIndex(4) as! String if size == "0B" { self.videoMaps.removeObject(v) } } }) dispatch_sync(dispatch_get_main_queue(), { self.indicator.stopAnimating() self.indicator.hidden = true if self.videoJson == nil { print("json nil 2") return } self.updateLabelText() self.videoCollectionView.reloadData() }) }) } // display alert dialog on the top view controller func displayAlertWithTitle(title: String, message: String) { let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) var topVC = UIApplication.sharedApplication().keyWindow?.rootViewController while let preVC = topVC?.presentedViewController { topVC = preVC } topVC!.presentViewController(controller, animated: true, completion: nil) } // update the label above collection view func updateLabelText() { if label.hidden { label.hidden = false } if videoMaps == nil || videoMaps.count == 0 { label.text = "No videos available" } else { label.text = "\(videoMaps.count) video files available" underLabel.hidden = false } } } // collection view extension extension ContainerViewController: UICollectionViewDelegate, UICollectionViewDataSource { // cells in collection view func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.videoMaps == nil { return 0 } else { return self.videoMaps.count } } func getVideoFormat(row: Int) -> String { let videoType = self.videoMaps.objectAtIndex(row).objectAtIndex(0) as? String let type = videoType?.componentsSeparatedByString("/") return type![1] } func getVideoSize(row: Int) -> String { let size = self.videoMaps.objectAtIndex(row).objectAtIndex(4) as! String return size } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let videoCell = self.videoCollectionView.dequeueReusableCellWithReuseIdentifier("videoCell", forIndexPath: indexPath) as! MyVideoCell if self.videoMaps != nil { // video type and size videoCell.videoTypeLabelView.text = getVideoFormat(indexPath.row) videoCell.videoSizeLabelView.text = self.videoMaps.objectAtIndex(indexPath.row).objectAtIndex(4) as? String } return videoCell } // (un)highlight background color update func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { let highlightedCell = collectionView.cellForItemAtIndexPath(indexPath) self.cellBackgroundColor = highlightedCell?.backgroundColor highlightedCell?.backgroundColor = self.hilightedCellBackgroundColor } func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { let highlightedCell = collectionView.cellForItemAtIndexPath(indexPath) highlightedCell?.backgroundColor = self.cellBackgroundColor } // download selected func alreadyDownloaded() -> Bool { let error: NSError? var videoArr: [VideoData] // fetch existing videos from core data let fetchRequest = NSFetchRequest(entityName: entityVideoData) videoArr = (try! managedContext.executeFetchRequest(fetchRequest)) as! [VideoData] // error happens if let theErr = error { print("cannot fetch video info from core data: \(theErr.description)") return true } else { if videoArr.count > 0 { for v in videoArr { if v.title == self.videoTitle && v.format == self.videoFormat && v.size == self.videoSize { // dupilication found return true } } } return false } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // video url and format let videoUrl = self.videoMaps.objectAtIndex(indexPath.row).objectAtIndex(2) as! String self.videoFormat = getVideoFormat(indexPath.row) self.videoSize = getVideoSize(indexPath.row) // check duplication in core data if alreadyDownloaded() { displayAlertWithTitle("OK", message: "the video is already downloaded") return } // download video and image self.downloadVideoFile(videoUrl) self.downloadImgFile(self.videoImgUrlStr) } } // download extension extension ContainerViewController: NSURLSessionDelegate, NSURLSessionDownloadDelegate, NSURLSessionTaskDelegate { // download video and image func downloadVideoFile(videoURL: String) { url = NSURL(string: videoURL) let task = session.downloadTaskWithURL(url!) task.resume() } func downloadImgFile(imgURL: String) { url = NSURL(string: imgURL) let task = session.downloadTaskWithURL(url!) task.resume() } func removeCancelledData() { } func cancelCompHandler(dataTasks: [AnyObject]!, upTasks: [AnyObject]!, downTasks: [AnyObject]!) { for v in downTasks { let task = v as! NSURLSessionDownloadTask let url = task.originalRequest!.URL?.absoluteString if url == self._originalUrl { task.cancel() // remove the corresponding item in core data & files removeCancelledData() } } } func cancelUnfinishedTask(notif: NSNotification) { let url = notif.userInfo!["originalUrl" ] as! String self._originalUrl = url //session.getTasksWithCompletionHandler(cancelCompHandler) } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){ let d = Double(totalBytesWritten) let e = Double(totalBytesExpectedToWrite) // ~1.0 in double let p = d / e // video download task if downloadTask.taskIdentifier % 2 == 1 { // insert to core data if !alreadyDownloaded() { self.originalUrl = downloadTask.originalRequest!.URL?.absoluteString saveToCoreData() } // send notification of current condition let notif = NSNotification(name: "videoDownloadPercentNotif", object: self, userInfo: ["percent": p, "title": videoTitle, "format": videoFormat, "size": videoSize ]) NSNotificationCenter.defaultCenter().postNotification(notif) // observe cancel notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "cancelUnfinishedTask:", name: "cancelUnfinishedTask", object: nil) } } // error check when completed func insertResumeDataToCoreData(resumeData: NSData) { let error: NSError? var videoArr: [VideoData] // fetch existing videos from core data let fetchRequest = NSFetchRequest(entityName: entityVideoData) videoArr = (try! managedContext.executeFetchRequest(fetchRequest)) as! [VideoData] // error happens if let _ = error { } else { if videoArr.count > 0 { for v in videoArr { if v.title == self.videoTitle && v.format == self.videoFormat && v.size == self.videoSize { // insert v.resumeData = resumeData do { try managedContext!.save() } catch _ { print("cannot save resume data to core data") } break } } } } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { print("Finished ", terminator: "") if error == nil { print("without an error") } else { // save the resume data to core data if let _ = error?.userInfo { } } } // save to file system and core data when succeeded func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { var destUrl: NSURL! let taskID = downloadTask.taskIdentifier let comp = self.videoTitle + "_" + self.videoSize + "." + self.videoFormat var messageOK = "" var messageFail = "" // form the url of downloaded files if taskID % 2 == 1 { // video task destUrl = urlOfVideoFolder.URLByAppendingPathComponent(comp) messageOK = "successfully download video " + self.videoTitle messageFail = "cannot download video " + self.videoTitle } else if taskID % 2 == 0 { // image task destUrl = urlOfImgFolder.URLByAppendingPathComponent(comp) messageOK = "successfully download thumbnail " + self.videoTitle messageFail = "cannot download thumbnail " + self.videoTitle } // move to file system var error: NSError? do { try manager.moveItemAtURL(location, toURL: destUrl) // alert success message displayAlertWithTitle("OK", message: messageOK) } catch let error1 as NSError { error = error1 if let _ = error { //println("cannot move downloaded file with task \(taskID): \(error?.description)") displayAlertWithTitle("OK", message: messageFail) } } } } // core data extension extension ContainerViewController { // save video title, duration and format to core data func saveToCoreData() { // error var error: NSError? // insert video object to context let video = NSEntityDescription.insertNewObjectForEntityForName(entityVideoData, inManagedObjectContext: managedContext!) as! VideoData // send values to video object video.title = self.videoTitle video.format = self.videoFormat video.size = self.videoSize video.duration = self.videoDuration video.resumeData = self.defaultResume video.originalUrl = self.originalUrl do { try managedContext!.save() print("Successfully saved in core data") } catch let error1 as NSError { error = error1 if let theErr = error { print("Failed to save the new video. Error = \(theErr.description)") } } } }
mit
7f3274075e8208275742e8e46884fa37
32.725314
177
0.556561
5.819393
false
false
false
false
gouyz/GYZBaking
baking/Classes/Home/Controller/GYZShopSerchGoodsVC.swift
1
5375
// // GYZShopSerchGoodsVC.swift // baking // 店内商品搜索 // Created by gouyz on 2017/5/27. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD private let searchShopGoodsCell = "searchShopGoodsCell" class GYZShopSerchGoodsVC: GYZBaseVC,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource { /// 商品名称 var goodsName: String = "" ///商家ID var shopId: String = "" var goodsModels: [GoodInfoModel] = [GoodInfoModel]() ///回传商品信息 var blockGoodsInfo: ((_ goodsInfo: GoodInfoModel) -> ())? override func viewDidLoad() { super.viewDidLoad() setupUI() view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(0) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupUI(){ navigationItem.titleView = searchBar let btn = UIButton(type: .custom) btn.setTitle("取消", for: .normal) btn.titleLabel?.font = k14Font btn.frame = CGRect.init(x: 0, y: 0, width: kTitleHeight, height: kTitleHeight) btn.addTarget(self, action: #selector(cancleSearchClick), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn) } /// 懒加载UITableView fileprivate lazy var tableView : UITableView = { let table = UITableView(frame: CGRect.zero, style: .plain) table.dataSource = self table.delegate = self table.tableFooterView = UIView() table.separatorColor = kGrayLineColor table.register(GYZShopGoodsSearchCell.self, forCellReuseIdentifier: searchShopGoodsCell) return table }() /// 搜索框 lazy var searchBar : UISearchBar = { let search = UISearchBar() search.backgroundImage = UIImage.init(named: "icon_search_clearbg") search.placeholder = "请输入商品名称" search.delegate = self //显示输入光标 search.tintColor = kYellowFontColor //弹出键盘 search.becomeFirstResponder() return search }() /// 取消搜索 func cancleSearchClick(){ searchBar.resignFirstResponder() self.dismiss(animated: false, completion: nil) } ///mark - UISearchBarDelegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() goodsName = searchBar.text! if goodsName.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请输入搜索内容") return } goodsModels.removeAll() requestGoodsListData() } ///获取商品数据 func requestGoodsListData(){ weak var weakSelf = self showLoadingView() GYZNetWork.requestNetwork("Goods/searchGoods",parameters: ["key":goodsName,"member_id":shopId], success: { (response) in weakSelf?.hiddenLoadingView() // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] guard let info = data["info"].array else { return } for item in info{ guard let itemInfo = item.dictionaryObject else { return } let model = GoodInfoModel.init(dict: itemInfo) weakSelf?.goodsModels.append(model) } if weakSelf?.goodsModels.count > 0{ weakSelf?.hiddenEmptyView() weakSelf?.tableView.reloadData() }else{ ///显示空页面 weakSelf?.showEmptyView(content:"暂无商品信息") } }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hiddenLoadingView() GYZLog(error) }) } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return goodsModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: searchShopGoodsCell) as! GYZShopGoodsSearchCell cell.setDatas(goodsModels[indexPath.row]) cell.selectionStyle = .none return cell } ///MARK : UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { cancleSearchClick() guard let tmpFinished = blockGoodsInfo else { return } tmpFinished(goodsModels[indexPath.row]) } }
mit
d449176893acbf290ffc010dbaf24b3b
30.083333
129
0.587897
5.19602
false
false
false
false
hisui/ReactiveSwift
ReactiveSwift/SetView.swift
1
2740
// Copyright (c) 2014 segfault.jp. All rights reserved. import Foundation public class SetView<E: Hashable>: SubjectSource<SetDiff<E>> { public init() {} override public var firstValue: Box<UpdateDiff> { return Box(SetDiff()) } public subscript(i: Int) -> E? { return nil } public func map<F>(f: E -> F) -> Stream<SetView<F>> { return .pure(SetView<F>()) } public func map<F>(f: E -> F, _ context: ExecutionContext) -> SetView<F> { return SetView<F>() } public var count: UInt { return 0 } public var array: [E] { return [] } public func compose() -> Stream<[E: ()]> { return unwrap.map { _ in undefined() } } } public class SetCollection<E: Hashable>: SetView<E> { private var raw: [E: ()] public init(a: [E] = []) { self.raw = newDictionary(a, value: ()) } override public var firstValue: Box<UpdateDiff> { return Box(SetDiff(Array(raw.keys))) } override public func merge(update: UpdateType) { for e in update.detail.delete { raw.removeValueForKey(e) } for e in update.detail.insert { raw.updateValue((), forKey: e) } commit(update) } public func update(diff: SetDiff<E>, _ sender: AnyObject? = nil) { merge(Update(diff, sender ?? self)) } public func delete(e: E, sender: AnyObject? = nil) { update(SetDiff([], [e]), sender) } public func insert(e: E, sender: AnyObject? = nil) { update(SetDiff([e], []), sender) } public func assign(a: [E], sender: AnyObject? = nil) { let tmp = newDictionary(a, value: ()) var delete = [E]() var insert = [E]() for e in tmp.keys { if !raw.containsKey(e) { insert.append(e) } } for e in raw.keys { if !tmp.containsKey(e) { delete.append(e) } } update(SetDiff(insert, delete)) } override public var count: UInt { return UInt(raw.count) } override public var array: [E] { return raw.keys.array } override public func compose() -> Stream<[E: ()]> { return unwrap.map { [unowned self] _ in self.raw } } } public class SetDiff<E: Hashable> { public let insert: [E] public let delete: [E] public init(_ insert: [E] = [], _ delete: [E] = []) { self.insert = insert self.delete = delete } } extension Dictionary { func containsKey(key: Key) -> Bool { switch self[key] { case .Some(_): return true case .None : return false } } } private func newDictionary<K: Hashable, V>(keys: [K], value: V) -> [K: V] { var o = [K: V]() for e in keys { o[e] = value } return o }
mit
a75729ba453b15ae214a75d85930e3b4
26.128713
91
0.555474
3.600526
false
false
false
false
otto-schnurr/MetalMatrixMultiply-swift
Source/Pipeline/MultiplicationData.swift
1
762
// // MultiplicationData.swift // // Created by Otto Schnurr on 12/19/2015. // Copyright © 2015 Otto Schnurr. All rights reserved. // // MIT License // file: ../../LICENSE.txt // http://opensource.org/licenses/MIT // /// For computing: /// ``` /// output = A^T * B /// ``` protocol MultiplicationData { associatedtype MatrixType: Matrix var inputA: MatrixType { get } var inputB: MatrixType { get } var output: MatrixType { get } } extension MultiplicationData { var inputDimensionsAreValid: Bool { return inputA.rowCount == inputB.rowCount } var outputDimensionsAreValid: Bool { return output.rowCount == inputA.columnCount && output.columnCount == inputB.columnCount } }
mit
af3c044db5481fd375fad0413ba6f902
19.567568
55
0.633377
4.20442
false
false
false
false
maxkonovalov/MKRingProgressView
Example/ProgressRingExample/ViewController.swift
1
1469
// // ViewController.swift // RingProgressExample // // Created by Max Konovalov on 21/10/2018. // Copyright © 2018 Max Konovalov. All rights reserved. // import MKRingProgressView import UIKit class ViewController: UIViewController { @IBOutlet var ringProgressView: RingProgressView! @IBOutlet var valueLabel: UILabel! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ringProgressView.ringWidth = ringProgressView.bounds.width * 0.2 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if case let parametersViewController as ParametersViewController = segue.destination { parametersViewController.delegate = self } } } extension ViewController: ParametersViewControllerDelegate { func parametersViewControllerDidChangeProgress(_ progress: Double) { ringProgressView.progress = progress valueLabel.text = String(format: "%.2f", progress) } func parametersViewControllerDidChangeStyle(_ style: RingProgressViewStyle) { ringProgressView.style = style } func parametersViewControllerDidChangeShadowOpacity(_ shadowOpacity: CGFloat) { ringProgressView.shadowOpacity = shadowOpacity } func parametersViewControllerDidChangeHidesRingForZeroProgressValue(_ hidesRingForZeroProgress: Bool) { ringProgressView.hidesRingForZeroProgress = hidesRingForZeroProgress } }
mit
27a942f4ee11d6e27ad2ac710f03c97c
31.622222
107
0.732289
5.224199
false
false
false
false
uasys/swift
test/SILGen/objc_attr_NSManaged.swift
1
5428
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop // This file is also used by objc_attr_NSManaged_multi.swift. import Foundation import gizmo @objc class X : NSObject { func foo() -> X { return self } } class SwiftGizmo : Gizmo { @NSManaged var x: X @NSManaged func kvc() // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC1x{{[_0-9a-zA-Z]*}}fgTo // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC1x{{[_0-9a-zA-Z]*}}fsTo // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC3kvc{{[_0-9a-zA-Z]*}}FTo // Make sure that we're calling through the @objc entry points. // CHECK-LABEL: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC7modifyX{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed SwiftGizmo) -> () { func modifyX() { // CHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[SELF:%.*]] : $SwiftGizmo, #SwiftGizmo.x!setter.1.foreign : (SwiftGizmo) -> (X) -> (), $@convention(objc_method) (X, SwiftGizmo) -> () // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[SELF]] : $SwiftGizmo, #SwiftGizmo.x!getter.1.foreign : (SwiftGizmo) -> () -> X, $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NEXT: apply [[GETTER]]([[SELF]]) : $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NOT: return // CHECK: apply [[SETTER]]([[XMOD:%.*]], [[SELF]]) : $@convention(objc_method) (X, SwiftGizmo) -> () x = x.foo() // CHECK: return } // CHECK-LABEL: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC8testFunc{{[_0-9a-zA-Z]*}}F func testFunc() { // CHECK: = class_method [volatile] %0 : $SwiftGizmo, #SwiftGizmo.kvc!1.foreign : (SwiftGizmo) -> () -> (), $@convention(objc_method) (SwiftGizmo) -> () // CHECK: return kvc() } } extension SwiftGizmo { @NSManaged func extKVC() // CHECK-LABEL: _T019objc_attr_NSManaged10SwiftGizmoC7testExt{{[_0-9a-zA-Z]*}}F func testExt() { // CHECK: = class_method [volatile] %0 : $SwiftGizmo, #SwiftGizmo.extKVC!1.foreign : (SwiftGizmo) -> () -> (), $@convention(objc_method) (SwiftGizmo) -> () // CHECK: return extKVC() } } final class FinalGizmo : SwiftGizmo { @NSManaged var y: String @NSManaged func kvc2() } extension FinalGizmo { @NSManaged func extKVC2() // CHECK-LABEL: _T019objc_attr_NSManaged10FinalGizmoC8testExt2{{[_0-9a-zA-Z]*}}F func testExt2() { // CHECK: = class_method [volatile] %0 : $FinalGizmo, #FinalGizmo.extKVC2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> () // CHECK: return extKVC2() } } // CHECK-LABEL: sil hidden @_T019objc_attr_NSManaged9testFinalSSAA0E5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String { // CHECK: bb0([[ARG:%.*]] : @owned $FinalGizmo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.kvc2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> () // CHECK-NOT: return // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.y!getter.1.foreign : (FinalGizmo) -> () -> String, $@convention(objc_method) (FinalGizmo) -> @autoreleased NSString // CHECK: return func testFinal(_ obj: FinalGizmo) -> String { obj.kvc2() return obj.y } // SR-2673: @NSManaged property can't satisfy protocol requirement @objc protocol ObjCProto { var managedProp: String { get set } var managedExtProp: AnyObject { get } } class ProtoAdopter: Gizmo, ObjCProto { @NSManaged var managedProp: String } extension ProtoAdopter { @NSManaged var managedExtProp: AnyObject } // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC1xAA1XCfgTo : $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10SwiftGizmoC1xAA1XCfsTo // CHECK-NOT: sil hidden @_T019objc_attr_NSManaged10{{[_0-9a-zA-Z]*}}FinalGizmoC1yytfgTo // The vtable should not contain any entry points for getters and setters. // CHECK-LABEL: sil_vtable SwiftGizmo { // CHECK-NEXT: #SwiftGizmo.modifyX!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC7modifyXyyF // CHECK-NEXT: #SwiftGizmo.testFunc!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC8testFuncyyF // CHECK-NEXT: #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoCSQyACGycfc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoCSQyACGSi7bellsOn_tcfc // CHECK-NEXT: #SwiftGizmo.deinit!deallocator: _T019objc_attr_NSManaged10SwiftGizmoCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable FinalGizmo { // CHECK-NEXT: #SwiftGizmo.modifyX!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC7modifyX{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: #SwiftGizmo.testFunc!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC8testFunc{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10FinalGizmoC{{[_0-9a-zA-Z]*}}fc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10FinalGizmoC{{[_0-9a-zA-Z]*}}fc // CHECK-NEXT: #FinalGizmo.deinit!deallocator: _T019objc_attr_NSManaged10FinalGizmoCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable ProtoAdopter { // CHECK-NOT: managed{{.*}}Prop // CHECK: {{^}$}}
apache-2.0
39bb30d181ddb089cd07da82b9b7e731
43.491803
200
0.67594
3.317848
false
true
false
false
tjw/swift
test/NameBinding/dynamic-member-lookup.swift
3
10232
// RUN: %target-swift-frontend -typecheck -verify %s var global = 42 @dynamicMemberLookup struct Gettable { subscript(dynamicMember member: StaticString) -> Int { return 42 } } @dynamicMemberLookup struct Settable { subscript(dynamicMember member: StaticString) -> Int { get {return 42} set {} } } @dynamicMemberLookup struct MutGettable { subscript(dynamicMember member: StaticString) -> Int { mutating get { return 42 } } } @dynamicMemberLookup struct NonMutSettable { subscript(dynamicMember member: StaticString) -> Int { get { return 42 } nonmutating set {} } } func test_function(b: Settable) { var bm = b bm.flavor = global } func test(a: Gettable, b: Settable, c: MutGettable, d: NonMutSettable) { global = a.wyverns a.flavor = global // expected-error {{cannot assign to property: 'a' is a 'let' constant}} global = b.flavor b.universal = global // expected-error {{cannot assign to property: 'b' is a 'let' constant}} b.thing += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a 'let' constant}} var bm = b global = bm.flavor bm.universal = global bm.thing += 1 var cm = c global = c.dragons // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} global = c[dynamicMember: "dragons"] // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} global = cm.dragons c.woof = global // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} var dm = d global = d.dragons // ok global = dm.dragons // ok d.woof = global // ok dm.woof = global // ok } func test_iuo(a : Gettable!, b : Settable!) { global = a.wyverns a.flavor = global // expected-error {{cannot assign through dynamic lookup property: subscript is get-only}} global = b.flavor b.universal = global // expected-error {{cannot assign through dynamic lookup property: 'b' is a 'let' constant}} var bm : Settable! = b global = bm.flavor bm.universal = global } //===----------------------------------------------------------------------===// // Returning a function //===----------------------------------------------------------------------===// @dynamicMemberLookup struct FnTest { subscript(dynamicMember member: StaticString) -> (_ a : Int)->() { return { a in () } } } func test_function(x : FnTest) { x.phunky(12) } func test_function_iuo(x : FnTest!) { x.flavor(12) } //===----------------------------------------------------------------------===// // Existential Cases //===----------------------------------------------------------------------===// @dynamicMemberLookup protocol ProtoExt { } extension ProtoExt { subscript(dynamicMember member: String) -> String { get {} } } extension String: ProtoExt { } func testProtoExt() -> String { let str = "test" return str.sdfsdfsdf } //===----------------------------------------------------------------------===// // Explicitly declared members take precedence //===----------------------------------------------------------------------===// @dynamicMemberLookup struct Dog { public var name = "Kaylee" subscript(dynamicMember member: String) -> String { return "Zoey" } } func testDog(person: Dog) -> String { return person.name + person.otherName } //===----------------------------------------------------------------------===// // Returning an IUO //===----------------------------------------------------------------------===// @dynamicMemberLookup struct IUOResultTest { subscript(dynamicMember member: StaticString) -> Int! { get { return 42 } nonmutating set {} } } func test_iuo_result(x : IUOResultTest) { x.foo?.negate() // Test mutating writeback. let _ : Int = x.bar // Test implicitly forced optional let b = x.bar // Should promote to 'Int?' let _ : Int = b // expected-error {{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'}} } //===----------------------------------------------------------------------===// // Error cases //===----------------------------------------------------------------------===// // Subscript index must be ExpressibleByStringLiteral. @dynamicMemberLookup struct Invalid1 { // expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid1' to have a 'subscript(dynamicMember:)' member with a string index}} subscript(dynamicMember member: Int) -> Int { return 42 } } // Subscript may not be variadic. @dynamicMemberLookup struct Invalid2 { // expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid2' to have a 'subscript(dynamicMember:)' member with a string index}} subscript(dynamicMember member: String...) -> Int { return 42 } } // References to overloads are resolved just like normal subscript lookup: // they are either contextually disambiguated or are invalid. @dynamicMemberLookup struct Ambiguity { subscript(dynamicMember member: String) -> Int { return 42 } subscript(dynamicMember member: String) -> Float { return 42 } } func testAmbiguity(a : Ambiguity) { let _ : Int = a.flexibility let _ : Float = a.dynamism _ = a.dynamism // expected-error {{ambiguous use of 'subscript(dynamicMember:)'}} } // expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}} @dynamicMemberLookup extension Int { subscript(dynamicMember member: String) -> Int { fatalError() } } @dynamicMemberLookup // expected-error {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}} func NotAllowedOnFunc() { } // @dynamicMemberLookup cannot be declared on a base class and fulfilled with a // derived class. // expected-error @+1 {{@dynamicMemberLookup attribute requires 'InvalidBase' to have a 'subscript(dynamicMember:)' member with a string index}} @dynamicMemberLookup class InvalidBase {} class InvalidDerived : InvalidBase { subscript(dynamicMember: String) -> Int { get {}} } // expected-error @+1 {{value of type 'InvalidDerived' has no member 'dynamicallyLookedUp'}} _ = InvalidDerived().dynamicallyLookedUp //===----------------------------------------------------------------------===// // Test Existential //===----------------------------------------------------------------------===// @dynamicMemberLookup protocol PyVal { subscript(dynamicMember member: StaticString) -> PyVal { get nonmutating set } } extension PyVal { subscript(dynamicMember member: StaticString) -> PyVal { get { fatalError() } nonmutating set {} } } struct MyType : PyVal { } func testMutableExistential(a : PyVal, b : MyType) -> PyVal { a.x.y = b b.x.y = b return a.foo.bar.baz } // Verify the protocol compositions and protocol refinements work. protocol SubPyVal : PyVal { } typealias ProtocolComp = AnyObject & PyVal func testMutableExistential2(a : AnyObject & PyVal, b : SubPyVal, c : ProtocolComp & AnyObject) { a.x.y = b b.x.y = b c.x.y = b } //===----------------------------------------------------------------------===// // JSON example //===----------------------------------------------------------------------===// @dynamicMemberLookup enum JSON { case IntValue(Int) case StringValue(String) case ArrayValue(Array<JSON>) case DictionaryValue(Dictionary<String, JSON>) var stringValue : String? { if case .StringValue(let str) = self { return str } return nil } subscript(index: Int) -> JSON? { if case .ArrayValue(let arr) = self { return index < arr.count ? arr[index] : nil } return nil } subscript(key: String) -> JSON? { if case .DictionaryValue(let dict) = self { return dict[key] } return nil } subscript(dynamicMember member: String) -> JSON? { if case .DictionaryValue(let dict) = self { return dict[member] } return nil } } func test_json_example(x : JSON) -> String? { _ = x.name?.first return x.name?.first?.stringValue } //===----------------------------------------------------------------------===// // Derived Class Example //===----------------------------------------------------------------------===// @dynamicMemberLookup class BaseClass { subscript(dynamicMember member: String) -> Int { return 42 } } class DerivedClass : BaseClass { } func testDerivedClass(x : BaseClass, y : DerivedClass) -> Int { return x.life - y.the + x.universe - y.and + x.everything } // Test that derived classes can add a setter. class DerivedClassWithSetter : BaseClass { override subscript(dynamicMember member: String) -> Int { get { return super[dynamicMember: member] } set { } } } func testOverrideSubscript(a : BaseClass, b: DerivedClassWithSetter) { let x = a.frotz + b.garbalaz b.baranozo = x a.balboza = 12 // expected-error {{cannot assign to property}} } //===----------------------------------------------------------------------===// // Generics //===----------------------------------------------------------------------===// @dynamicMemberLookup struct SettableGeneric1<T> { subscript(dynamicMember member: StaticString) -> T? { get {} nonmutating set {} } } func testGenericType<T>(a : SettableGeneric1<T>, b : T) -> T? { a.dfasdf = b return a.dfsdffff } func testConcreteGenericType(a : SettableGeneric1<Int>) -> Int? { a.dfasdf = 42 return a.dfsdffff } @dynamicMemberLookup struct SettableGeneric2<T> { subscript<U: ExpressibleByStringLiteral>(dynamicMember member: U) -> T { get {} nonmutating set {} } } func testGenericType2<T>(a : SettableGeneric2<T>, b : T) -> T? { a[dynamicMember: "fasdf"] = b a.dfasdf = b return a.dfsdffff } func testConcreteGenericType2(a : SettableGeneric2<Int>) -> Int? { a.dfasdf = 42 return a.dfsdffff } //===----------------------------------------------------------------------===// // Keypaths //===----------------------------------------------------------------------===// @dynamicMemberLookup class C { subscript(dynamicMember member: String) -> Int { return 7 } } _ = \C.[dynamicMember: "hi"] _ = \C.testLookup
apache-2.0
8e12fed3b7fdfe663b59db4c6ca43b88
25.102041
144
0.571931
4.402754
false
true
false
false
guanix/swift-sodium
Examples/OSX/AppDelegate.swift
3
1440
// // AppDelegate.swift // Example OSX // // Created by RamaKrishna Mallireddy on 19/04/15. // Copyright (c) 2015 Frank Denis. All rights reserved. // import Cocoa import Sodium @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application let sodium = Sodium()! let aliceKeyPair = sodium.box.keyPair()! let bobKeyPair = sodium.box.keyPair()! let message: NSData = "My Test Message".toData()! println("Original Message:\(message.toString())") let encryptedMessageFromAliceToBob: NSData = sodium.box.seal(message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! println("Encrypted Message:\(encryptedMessageFromAliceToBob)") let messageVerifiedAndDecryptedByBob = sodium.box.open(encryptedMessageFromAliceToBob, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey) println("Decrypted Message:\(messageVerifiedAndDecryptedByBob!.toString())") } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
isc
e1614774ce290a4c4cc9deb3022447fe
27.8
84
0.666667
4.982699
false
false
false
false
tjw/swift
test/DebugInfo/apple-types-accel.swift
4
1084
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend %s -c -g -o %t.o // RUN: %llvm-dwarfdump --apple-types %t.o \ // RUN: | %FileCheck --check-prefix=CHECK-ACCEL %s // RUN: %llvm-dwarfdump --debug-info %t.o \ // RUN: | %FileCheck --check-prefix=CHECK-DWARF %s // RUN: %llvm-dwarfdump --verify %t.o // REQUIRES: OS=macosx // Verify that the unmangles basenames end up in the accelerator table. // CHECK-ACCEL-DAG: String: {{.*}}"Int64" // CHECK-ACCEL-DAG: String: {{.*}}"foo" // Verify that the mangled names end up in the debug info. // CHECK-DWARF: TAG_module // CHECK-DWARF-NEXT: AT_name ("main") // CHECK-DWARF: TAG_structure_type // CHECK-DWARF-NEXT: AT_name ("foo") // CHECK-DWARF-NEXT: AT_linkage_name ("$S4main3fooCD") // Verify the IR interface: // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "foo" // CHECK-SAME: line: [[@LINE+2]] // CHECK-SAME: identifier: "$S4main3fooCD" class foo { var x : Int64 = 1 } func main() -> Int64 { var thefoo = foo(); return thefoo.x } main()
apache-2.0
1bc0f55d031bfd5aa58f4f01407dd865
30.882353
71
0.633764
2.716792
false
false
false
false
uasys/swift
test/SILGen/objc_bridging.swift
1
38686
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu // REQUIRES: objc_interop import Foundation import Appliances func getDescription(_ o: NSObject) -> String { return o.description } // CHECK-LABEL: sil hidden @_T013objc_bridging14getDescription{{.*}}F // CHECK: bb0([[ARG:%.*]] : @owned $NSObject): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSObject, #NSObject.description!getter.1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]([[BORROWED_ARG]]) // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString): // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]], // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : @owned $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : @owned $String): // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[NATIVE]] // CHECK:} func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // CHECK-LABEL: sil hidden @_T013objc_bridging18getUppercaseString{{.*}}F // CHECK: bb0([[ARG:%.*]] : @owned $NSString): // -- The 'self' argument of NSString methods doesn't bridge. // CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK-NOT: function_ref @swift_StringToNSString // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSString, #NSString.uppercase!1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]([[BORROWED_ARG]]) : $@convention(objc_method) (NSString) -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : @owned $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : @owned $String): // CHECK: return [[NATIVE]] // CHECK: } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { var s = s f.setFoo(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging6setFoo{{.*}}F // CHECK: bb0([[ARG0:%.*]] : @owned $Foo, {{%.*}} : @owned $String): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setFoo!1.foreign // CHECK: [[NATIVE:%.*]] = load // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Optional<NSString>, Foo) -> () // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // @interface Foo -(BOOL) zim; @end func getZim(_ f: Foo) -> Bool { return f.zim() } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-i386: bb0([[SELF:%.*]] : @owned $Foo): // CHECK-ios-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-i386: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-watchos-i386: bb0([[SELF:%.*]] : @owned $Foo): // CHECK-watchos-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-watchos-i386: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-watchos-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-watchos-i386: return [[BOOL]] : $Bool // CHECK-watchos-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-macosx-x86_64: bb0([[SELF:%.*]] : @owned $Foo): // CHECK-macosx-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-x86_64: bb0([[SELF:%.*]] : @owned $Foo): // CHECK-ios-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-ios-x86_64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-ios-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-x86_64: return [[BOOL]] : $Bool // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-arm64: bb0([[SELF:%.*]] : @owned $Foo): // CHECK-arm64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-arm64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-arm64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-arm64: return [[BOOL]] : $Bool // CHECK-arm64: } // @interface Foo -(void) setZim: (BOOL)b; @end func setZim(_ f: Foo, b: Bool) { f.setZim(b) } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-i386: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK-ios-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-ios-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-i386: destroy_value [[ARG0]] // CHECK-ios-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-macosx-x86_64: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK-macosx-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-macosx-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-macosx-x86_64: destroy_value [[ARG0]] // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-x86_64: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK-ios-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-x86_64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-ios-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-x86_64: destroy_value [[ARG0]] // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-arm64: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK-arm64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-arm64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-arm64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-arm64: destroy_value [[ARG0]] // CHECK-arm64: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-watchos-i386: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK-watchos-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-watchos-i386: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-watchos-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-watchos-i386: destroy_value [[ARG0]] // CHECK-watchos-i386: } // @interface Foo -(_Bool) zang; @end func getZang(_ f: Foo) -> Bool { return f.zang() } // CHECK-LABEL: sil hidden @_T013objc_bridging7getZangSbSo3FooCF // CHECK: bb0([[ARG:%.*]] : @owned $Foo) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.zang!1.foreign // CHECK: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Foo) -> Bool // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[BOOL]] // @interface Foo -(void) setZang: (_Bool)b; @end func setZang(_ f: Foo, _ b: Bool) { f.setZang(b) } // CHECK-LABEL: sil hidden @_T013objc_bridging7setZangySo3FooC_SbtF // CHECK: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZang!1.foreign // CHECK: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_T013objc_bridging7setZangySo3FooC_SbtF' // NSString *bar(void); func callBar() -> String { return bar() } // CHECK-LABEL: sil hidden @_T013objc_bridging7callBar{{.*}}F // CHECK: bb0: // CHECK: [[BAR:%.*]] = function_ref @bar // CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() : $@convention(c) () -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString): // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: bb5([[NATIVE:%.*]] : @owned $String): // CHECK: return [[NATIVE]] // CHECK: } // void setBar(NSString *s); func callSetBar(_ s: String) { var s = s setBar(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging10callSetBar{{.*}}F // CHECK: bb0({{%.*}} : @owned $String): // CHECK: [[SET_BAR:%.*]] = function_ref @setBar // CHECK: [[NATIVE:%.*]] = load // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]]) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } var NSS: NSString // -- NSString methods don't convert 'self' extension NSString { var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABvgTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABvsTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE11nsstrResultAByFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyABFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } } class Bas : NSObject { // -- Bridging thunks for String properties convert between NSString var strRealProp: String = "Hello" // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : @unowned $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_bridging.Bas.strRealProp.getter // CHECK: [[PROPIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSvg // CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[BORROWED_THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]]) // CHECK: end_borrow [[BORROWED_PROP_COPY]] from [[PROP_COPY]] // CHECK: destroy_value [[PROP_COPY]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSvg // CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[PROP_ADDR]] : $*String // CHECK: [[PROP:%.*]] = load [copy] [[READ]] // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSvsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[VALUE:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSvs // CHECK: apply [[SETIMPL]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strRealPropSSvsTo' // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSvs // CHECK: bb0(%0 : @owned $String, %1 : @guaranteed $Bas): // CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[STR_ADDR]] : $*String // CHECK: assign {{.*}} to [[WRITE]] // CHECK: } var strFakeProp: String { get { return "" } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : @unowned $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[GETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSvg // CHECK: [[STR:%.*]] = apply [[GETTER]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSvsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSvs // CHECK: apply [[SETTER]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strFakePropSSvsTo' // -- Bridging thunks for explicitly NSString properties don't convert var nsstrRealProp: NSString var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCvsTo : $@convention(objc_method) (NSString, Bas) -> // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // -- Bridging thunks for String methods convert between NSString func strResult() -> String { return "" } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9strResultSSyFTo // CHECK: bb0([[THIS:%.*]] : @unowned $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC9strResultSSyF // CHECK: [[STR:%.*]] = apply [[METHOD]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } func strArg(_ s: String) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgySSFTo // CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgySSF // CHECK: apply [[METHOD]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC6strArgySSFTo' // -- Bridging thunks for explicitly NSString properties don't convert func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11nsstrResultSo8NSStringCyFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgySo8NSStringCF // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } init(str: NSString) { nsstrRealProp = str super.init() } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> () // CHECK: bb0([[NSARRAY:%[0-9]+]] : @unowned $NSArray, [[SELF:%[0-9]+]] : @unowned $Bas): // CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ // CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type // CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgySayyXlGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] : $Bas // CHECK: return [[RESULT]] : $() func arrayArg(_ array: [AnyObject]) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11arrayResultSayyXlGyFTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Bas): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC11arrayResultSayyXlGyF : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]] // CHECK: destroy_value [[ARRAY]] // CHECK: return [[NSARRAY]] func arrayResult() -> [AnyObject] { return [] } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGvsTo : $@convention(objc_method) (NSArray, Bas) -> () var arrayProp: [String] = [] } // CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlockS3SXB_SS1xtF func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String { // CHECK: bb0([[BLOCK:%.*]] : @owned $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : @owned $String): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String) // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: destroy_value [[NSSTR]] // CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]] // CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: destroy_value [[STRING]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] : $String return f(x) } // CHECK: } // end sil function '_T013objc_bridging16applyStringBlockS3SXB_SS1xtF' // CHECK-LABEL: sil hidden @_T013objc_bridging15bridgeCFunction{{.*}}F func bridgeCFunction() -> (String!) -> (String!) { // CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringSQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String> // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: return [[THICK]] return NSStringFromString } func forceNSArrayMembers() -> (NSArray, NSArray) { let x = NSArray(objects: nil, count: 0) return (x, x) } // Check that the allocating initializer shim for initializers that take pointer // arguments lifetime-extends the bridged pointer for the right duration. // <rdar://problem/16738050> // CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfC // CHECK: [[SELF:%.*]] = alloc_ref_dynamic // CHECK: [[METHOD:%.*]] = function_ref @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfcTO // CHECK: [[RESULT:%.*]] = apply [[METHOD]] // CHECK: return [[RESULT]] // Check that type lowering preserves the bool/BOOL distinction when bridging // imported C functions. // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool // FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks // at the underlying Clang decl of the bridged decl to decide whether it needs // bridging. // // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool func bools(_ x: Bool) -> (Bool, Bool) { useBOOL(x) useBool(x) return (getBOOL(), getBool()) } // CHECK-LABEL: sil hidden @_T013objc_bridging9getFridge{{.*}}F // CHECK: bb0([[HOME:%[0-9]+]] : @owned $APPHouse): func getFridge(_ home: APPHouse) -> Refrigerator { // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]]) // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // CHECK: destroy_value [[HOME]] : $APPHouse // CHECK: return [[RESULT]] : $Refrigerator return home.fridge } // FIXME(integers): the following checks should be updated for the new integer // protocols. <rdar://problem/29939484> // XCHECK-LABEL: sil hidden @_T013objc_bridging16updateFridgeTemp{{.*}}F // XCHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double): func updateFridgeTemp(_ home: APPHouse, delta: Double) { // += // XCHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiySdz_SdtF // Borrowed home // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // Temporary fridge // XCHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator // Get operation // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]]) // Addition // XCHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature // XCHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]]) // Setter // XCHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator // XCHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign // XCHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV19_bridgeToObjectiveCSo15APPRefrigeratorCyF // XCHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]]) // XCHECK: apply [[SETTER]]([[OBJC_ARG]], [[BORROWED_HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> () // XCHECK: destroy_value [[OBJC_ARG]] // XCHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // XCHECK: destroy_value [[HOME]] home.fridge.temperature += delta } // CHECK-LABEL: sil hidden @_T013objc_bridging20callNonStandardBlockySi5value_tF func callNonStandardBlock(value: Int) { // CHECK: enum $Optional<@convention(block) () -> @owned Optional<AnyObject>> takesNonStandardBlock { return value } } func takeTwoAnys(_ lhs: Any, _ rhs: Any) -> Any { return lhs } // CHECK-LABEL: sil hidden @_T013objc_bridging22defineNonStandardBlockyyp1x_tF func defineNonStandardBlock(x: Any) { // CHECK: function_ref @_T013objc_bridging22defineNonStandardBlockyyp1x_tFypypcfU_ // CHECK: function_ref @_T0ypypIxir_yXlyXlIyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> @out Any, AnyObject) -> @autoreleased AnyObject let fn : @convention(block) (Any) -> Any = { y in takeTwoAnys(x, y) } } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypypIxir_yXlyXlIyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> @out Any, AnyObject) -> @autoreleased AnyObject // CHECK: bb0(%0 : @trivial $*@block_storage @callee_owned (@in Any) -> @out Any, %1 : @unowned $AnyObject): // CHECK: [[T0:%.*]] = copy_value %1 : $AnyObject // CHECK: [[T1:%.*]] = open_existential_ref [[T0]] : $AnyObject // CHECK: [[ARG:%.*]] = alloc_stack $Any // CHECK: [[T2:%.*]] = init_existential_addr [[ARG]] // CHECK: store [[T1]] to [init] [[T2]] // CHECK: [[RESULT:%.*]] = alloc_stack $Any // CHECK: apply {{.*}}([[RESULT]], [[ARG]]) // CHECK-LABEL: sil hidden @_T013objc_bridging15castToCFunctionySV3ptr_tF : $@convention(thin) (UnsafeRawPointer) -> () { func castToCFunction(ptr: UnsafeRawPointer) { // CHECK: [[CASTFN:%.*]] = function_ref @_T0s13unsafeBitCastq_x_q_m2totr0_lF // CHECK: [[OUT:%.*]] = alloc_stack $@convention(c) (Optional<AnyObject>) -> () // CHECK: [[IN:%.]] = alloc_stack $UnsafeRawPointer // CHECK: store %0 to [trivial] [[IN]] : $*UnsafeRawPointer // CHECK: [[META:%.*]] = metatype $@thick (@convention(c) (Optional<AnyObject>) -> ()).Type // CHECK: apply [[CASTFN]]<UnsafeRawPointer, @convention(c) (AnyObject?) -> ()>([[OUT]], [[IN]], [[META]]) : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 // CHECK: [[RESULT:%.*]] = load [trivial] %3 : $*@convention(c) (Optional<AnyObject>) -> () typealias Fn = @convention(c) (AnyObject?) -> Void unsafeBitCast(ptr, to: Fn.self)(nil) }
apache-2.0
c6e12fe8505ab48bebe22ef629d770d4
56.558036
269
0.636444
3.315248
false
false
false
false
zerdzhong/LeetCode
swift/LeetCode.playground/Pages/22_Generate_Parentheses.xcplaygroundpage/Contents.swift
1
831
//: [Previous](@previous) //https://leetcode.com/problems/generate-parentheses/ import Foundation class Solution { func generateParenthesis(_ n: Int) -> [String] { var parenthesis = [String]() generate(parArr: &parenthesis, str: "", left: n, right: n) return parenthesis } func generate(parArr: inout [String], str: String, left: Int, right: Int) -> Void { if left == 0 && right == 0 { parArr.append(str) return } if left > 0 { generate(parArr: &parArr, str: str + "(", left: left - 1, right: right) } if right > left { generate(parArr: &parArr, str: str + ")", left: left, right: right - 1) } } } Solution().generateParenthesis(2) //: [Next](@next)
mit
d67fc5c24f0977a9133fccffad887edd
24.181818
87
0.519856
3.938389
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/Calendar.swift
1
66249
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_implementationOnly import CoreFoundation internal func __NSCalendarIsAutoupdating(_ calendar: NSCalendar) -> Bool { return false } internal func __NSCalendarCurrent() -> NSCalendar { return _NSCopyOnWriteCalendar(backingCalendar: CFCalendarCopyCurrent()._nsObject) } internal func __NSCalendarInit(_ identifier: String) -> NSCalendar? { return NSCalendar(identifier: NSCalendar.Identifier(rawValue: identifier)) } /** `Calendar` encapsulates information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. It provides information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time. */ public struct Calendar : Hashable, Equatable, ReferenceConvertible, _MutableBoxing { public typealias ReferenceType = NSCalendar private var _autoupdating: Bool internal var _handle: _MutableHandle<NSCalendar> /// Calendar supports many different kinds of calendars. Each is identified by an identifier here. public enum Identifier { /// The common calendar in Europe, the Western Hemisphere, and elsewhere. case gregorian case buddhist case chinese case coptic case ethiopicAmeteMihret case ethiopicAmeteAlem case hebrew case iso8601 case indian case islamic case islamicCivil case japanese case persian case republicOfChina /// A simple tabular Islamic calendar using the astronomical/Thursday epoch of CE 622 July 15 case islamicTabular /// The Islamic Umm al-Qura calendar used in Saudi Arabia. This is based on astronomical calculation, instead of tabular behavior. case islamicUmmAlQura } /// An enumeration for the various components of a calendar date. /// /// Several `Calendar` APIs use either a single unit or a set of units as input to a search algorithm. /// /// - seealso: `DateComponents` public enum Component { case era case year case month case day case hour case minute case second case weekday case weekdayOrdinal case quarter case weekOfMonth case weekOfYear case yearForWeekOfYear case nanosecond case calendar case timeZone } /// Returns the user's current calendar. /// /// This calendar does not track changes that the user makes to their preferences. public static var current: Calendar { return Calendar(adoptingReference: __NSCalendarCurrent(), autoupdating: false) } /// A Calendar that tracks changes to user's preferred calendar. /// /// If mutated, this calendar will no longer track the user's preferred calendar. /// /// - note: The autoupdating Calendar will only compare equal to another autoupdating Calendar. public static var autoupdatingCurrent: Calendar { // swift-corelibs-foundation does not yet support autoupdating, but we can return the current calendar (which will not change). return Calendar(adoptingReference: __NSCalendarCurrent(), autoupdating: true) } // MARK: - // MARK: init /// Returns a new Calendar. /// /// - parameter identifier: The kind of calendar to use. public init(identifier: Identifier) { let result = __NSCalendarInit(Calendar._toNSCalendarIdentifier(identifier).rawValue)! _handle = _MutableHandle(adoptingReference: result) _autoupdating = false } // MARK: - // MARK: Bridging internal init(reference: NSCalendar) { _handle = _MutableHandle(reference: reference) if __NSCalendarIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSCalendar, autoupdating: Bool) { _handle = _MutableHandle(adoptingReference: reference) _autoupdating = autoupdating } // MARK: - // /// The identifier of the calendar. public var identifier: Identifier { return Calendar._fromNSCalendarIdentifier(_handle.map({ $0.calendarIdentifier })) } /// The locale of the calendar. public var locale: Locale? { get { return _handle.map { $0.locale } } set { _applyMutation { $0.locale = newValue } } } /// The time zone of the calendar. public var timeZone: TimeZone { get { return _handle.map { $0.timeZone } } set { _applyMutation { $0.timeZone = newValue } } } /// The first weekday of the calendar. public var firstWeekday: Int { get { return _handle.map { $0.firstWeekday } } set { _applyMutation { $0.firstWeekday = newValue } } } /// The number of minimum days in the first week. public var minimumDaysInFirstWeek: Int { get { return _handle.map { $0.minimumDaysInFirstWeek } } set { _applyMutation { $0.minimumDaysInFirstWeek = newValue } } } /// A list of eras in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["BC", "AD"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var eraSymbols: [String] { return _handle.map { $0.eraSymbols } } /// A list of longer-named eras in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Before Christ", "Anno Domini"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var longEraSymbols: [String] { return _handle.map { $0.longEraSymbols } } /// A list of months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var monthSymbols: [String] { return _handle.map { $0.monthSymbols } } /// A list of shorter-named months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortMonthSymbols: [String] { return _handle.map { $0.shortMonthSymbols } } /// A list of very-shortly-named months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortMonthSymbols: [String] { return _handle.map { $0.veryShortMonthSymbols } } /// A list of standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneMonthSymbols: [String] { return _handle.map { $0.standaloneMonthSymbols } } /// A list of shorter-named standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneMonthSymbols: [String] { return _handle.map { $0.shortStandaloneMonthSymbols } } /// A list of very-shortly-named standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortStandaloneMonthSymbols: [String] { return _handle.map { $0.veryShortStandaloneMonthSymbols } } /// A list of weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var weekdaySymbols: [String] { return _handle.map { $0.weekdaySymbols } } /// A list of shorter-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortWeekdaySymbols: [String] { return _handle.map { $0.shortWeekdaySymbols } } /// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortWeekdaySymbols: [String] { return _handle.map { $0.veryShortWeekdaySymbols } } /// A list of standalone weekday names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneWeekdaySymbols: [String] { return _handle.map { $0.standaloneWeekdaySymbols } } /// A list of shorter-named standalone weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneWeekdaySymbols: [String] { return _handle.map { $0.shortStandaloneWeekdaySymbols } } /// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortStandaloneWeekdaySymbols: [String] { return _handle.map { $0.veryShortStandaloneWeekdaySymbols } } /// A list of quarter names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var quarterSymbols: [String] { return _handle.map { $0.quarterSymbols } } /// A list of shorter-named quarters in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortQuarterSymbols: [String] { return _handle.map { $0.shortQuarterSymbols } } /// A list of standalone quarter names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneQuarterSymbols: [String] { return _handle.map { $0.standaloneQuarterSymbols } } /// A list of shorter-named standalone quarters in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneQuarterSymbols: [String] { return _handle.map { $0.shortStandaloneQuarterSymbols } } /// The symbol used to represent "AM", localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `"AM"`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var amSymbol: String { return _handle.map { $0.amSymbol } } /// The symbol used to represent "PM", localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `"PM"`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var pmSymbol: String { return _handle.map { $0.pmSymbol } } // MARK: - // /// Returns the minimum range limits of the values that a given component can take on in the receiver. /// /// As an example, in the Gregorian calendar the minimum range of values for the Day component is 1-28. /// - parameter component: A component to calculate a range for. /// - returns: The range, or nil if it could not be calculated. public func minimumRange(of component: Component) -> Range<Int>? { return _handle.map { Range($0.minimumRange(of: Calendar._toCalendarUnit([component]))) } } /// The maximum range limits of the values that a given component can take on in the receive /// /// As an example, in the Gregorian calendar the maximum range of values for the Day component is 1-31. /// - parameter component: A component to calculate a range for. /// - returns: The range, or nil if it could not be calculated. public func maximumRange(of component: Component) -> Range<Int>? { return _handle.map { Range($0.maximumRange(of: Calendar._toCalendarUnit([component]))) } } @available(*, unavailable, message: "use range(of:in:for:) instead") public func range(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> NSRange { fatalError() } /// Returns the range of absolute time values that a smaller calendar component (such as a day) can take on in a larger calendar component (such as a month) that includes a specified absolute time. /// /// You can use this method to calculate, for example, the range the `day` component can take on in the `month` in which `date` lies. /// - parameter smaller: The smaller calendar component. /// - parameter larger: The larger calendar component. /// - parameter date: The absolute time for which the calculation is performed. /// - returns: The range of absolute time values smaller can take on in larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined). public func range(of smaller: Component, in larger: Component, for date: Date) -> Range<Int>? { return _handle.map { Range($0.range(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date)) } } /// Returns, via two inout parameters, the starting time and duration of a given calendar component that contains a given date. /// /// - seealso: `range(of:for:)` /// - seealso: `dateInterval(of:for:)` /// - parameter component: A calendar component. /// - parameter start: Upon return, the starting time of the calendar component that contains the date. /// - parameter interval: Upon return, the duration of the calendar component that contains the date. /// - parameter date: The specified date. /// - returns: `true` if the starting time and duration of a component could be calculated, otherwise `false`. public func dateInterval(of component: Component, start: inout Date, interval: inout TimeInterval, for date: Date) -> Bool { if let result = _handle.map({ $0.range(of: Calendar._toCalendarUnit([component]), for: date)}) { start = result.start interval = result.duration return true } else { return false } } /// Returns the starting time and duration of a given calendar component that contains a given date. /// /// - parameter component: A calendar component. /// - parameter date: The specified date. /// - returns: A new `DateInterval` if the starting time and duration of a component could be calculated, otherwise `nil`. public func dateInterval(of component: Component, for date: Date) -> DateInterval? { var start: Date = Date(timeIntervalSinceReferenceDate: 0) var interval: TimeInterval = 0 if self.dateInterval(of: component, start: &start, interval: &interval, for: date) { return DateInterval(start: start, duration: interval) } else { return nil } } /// Returns, for a given absolute time, the ordinal number of a smaller calendar component (such as a day) within a specified larger calendar component (such as a week). /// /// The ordinality is in most cases not the same as the decomposed value of the component. Typically return values are 1 and greater. For example, the time 00:45 is in the first hour of the day, and for components `hour` and `day` respectively, the result would be 1. An exception is the week-in-month calculation, which returns 0 for days before the first week in the month containing the date. /// /// - note: Some computations can take a relatively long time. /// - parameter smaller: The smaller calendar component. /// - parameter larger: The larger calendar component. /// - parameter date: The absolute time for which the calculation is performed. /// - returns: The ordinal number of smaller within larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined). public func ordinality(of smaller: Component, in larger: Component, for date: Date) -> Int? { let result = _handle.map { $0.ordinality(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date) } if result == NSNotFound { return nil } return result } // MARK: - // @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } // MARK: - // @available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead") public func date(byAdding unit: NSCalendar.Unit, value: Int, to date: Date, options: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by adding components to a given date. /// /// - parameter components: A set of values to add to the date. /// - parameter date: The starting date. /// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`. /// - returns: A new date, or nil if a date could not be calculated with the given input. public func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = false) -> Date? { return _handle.map { $0.date(byAdding: components, to: date, options: wrappingComponents ? [.wrapComponents] : []) } } @available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead") public func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by adding an amount of a specific component to a given date. /// /// - parameter component: A single component to add. /// - parameter value: The value of the specified component to add. /// - parameter date: The starting date. /// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`. /// - returns: A new date, or nil if a date could not be calculated with the given input. public func date(byAdding component: Component, value: Int, to date: Date, wrappingComponents: Bool = false) -> Date? { return _handle.map { $0.date(byAdding: Calendar._toCalendarUnit([component]), value: value, to: date, options: wrappingComponents ? [.wrapComponents] : []) } } /// Returns a date created from the specified components. /// /// - parameter components: Used as input to the search algorithm for finding a corresponding date. /// - returns: A new `Date`, or nil if a date could not be found which matches the components. public func date(from components: DateComponents) -> Date? { return _handle.map { $0.date(from: components) } } @available(*, unavailable, renamed: "dateComponents(_:from:)") public func components(_ unitFlags: NSCalendar.Unit, from date: Date) -> DateComponents { fatalError() } /// Returns all the date components of a date, using the calendar time zone. /// /// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date. /// - parameter date: The `Date` to use. /// - returns: The date components of the specified date. public func dateComponents(_ components: Set<Component>, from date: Date) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: date) } } @available(*, unavailable, renamed: "dateComponents(in:from:)") public func components(in timezone: TimeZone, from date: Date) -> DateComponents { fatalError() } /// Returns all the date components of a date, as if in a given time zone (instead of the `Calendar` time zone). /// /// The time zone overrides the time zone of the `Calendar` for the purposes of this calculation. /// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date. /// - parameter timeZone: The `TimeZone` to use. /// - parameter date: The `Date` to use. /// - returns: All components, calculated using the `Calendar` and `TimeZone`. public func dateComponents(in timeZone: TimeZone, from date: Date) -> DateComponents { return _handle.map { $0.components(in: timeZone, from: date) } } @available(*, unavailable, renamed: "dateComponents(_:from:to:)") public func components(_ unitFlags: NSCalendar.Unit, from startingDate: Date, to resultDate: Date, options opts: NSCalendar.Options = []) -> DateComponents { fatalError() } /// Returns the difference between two dates. /// /// - parameter components: Which components to compare. /// - parameter start: The starting date. /// - parameter end: The ending date. /// - returns: The result of calculating the difference from start to end. public func dateComponents(_ components: Set<Component>, from start: Date, to end: Date) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) } } @available(*, unavailable, renamed: "dateComponents(_:from:to:)") public func components(_ unitFlags: NSCalendar.Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: NSCalendar.Options = []) -> DateComponents { fatalError() } /// Returns the difference between two dates specified as `DateComponents`. /// /// For components which are not specified in each `DateComponents`, but required to specify an absolute date, the base value of the component is assumed. For example, for an `DateComponents` with just a `year` and a `month` specified, a `day` of 1, and an `hour`, `minute`, `second`, and `nanosecond` of 0 are assumed. /// Calendrical calculations with unspecified `year` or `year` value prior to the start of a calendar are not advised. /// For each `DateComponents`, if its `timeZone` property is set, that time zone is used for it. If the `calendar` property is set, that is used rather than the receiving calendar, and if both the `calendar` and `timeZone` are set, the `timeZone` property value overrides the time zone of the `calendar` property. /// /// - parameter components: Which components to compare. /// - parameter start: The starting date components. /// - parameter end: The ending date components. /// - returns: The result of calculating the difference from start to end. public func dateComponents(_ components: Set<Component>, from start: DateComponents, to end: DateComponents) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) } } /// Returns the value for one component of a date. /// /// - parameter component: The component to calculate. /// - parameter date: The date to use. /// - returns: The value for the component. public func component(_ component: Component, from date: Date) -> Int { return _handle.map { $0.component(Calendar._toCalendarUnit([component]), from: date) } } @available(*, unavailable, message: "Use date(from:) instead") public func date(era: Int, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() } @available(*, unavailable, message: "Use date(from:) instead") public func date(era: Int, yearForWeekOfYear: Int, weekOfYear: Int, weekday: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() } /// Returns the first moment of a given Date, as a Date. /// /// For example, pass in `Date()`, if you want the start of today. /// If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. /// - parameter date: The date to search. /// - returns: The first moment of the given date. public func startOfDay(for date: Date) -> Date { return _handle.map { $0.startOfDay(for: date) } } @available(*, unavailable, renamed: "compare(_:to:toGranularity:)") public func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> ComparisonResult { fatalError() } /// Compares the given dates down to the given component, reporting them `orderedSame` if they are the same in the given component and all larger components, otherwise either `orderedAscending` or `orderedDescending`. /// /// - parameter date1: A date to compare. /// - parameter date2: A date to compare. /// - parameter component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour. public func compare(_ date1: Date, to date2: Date, toGranularity component: Component) -> ComparisonResult { return _handle.map { $0.compare(date1, to: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) } } @available(*, unavailable, renamed: "isDate(_:equalTo:toGranularity:)") public func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> Bool { fatalError() } /// Compares the given dates down to the given component, reporting them equal if they are the same in the given component and all larger components. /// /// - parameter date1: A date to compare. /// - parameter date2: A date to compare. /// - parameter component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour. /// - returns: `true` if the given date is within tomorrow. public func isDate(_ date1: Date, equalTo date2: Date, toGranularity component: Component) -> Bool { return _handle.map { $0.isDate(date1, equalTo: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) } } /// Returns `true` if the given date is within the same day as another date, as defined by the calendar and calendar's locale. /// /// - parameter date1: A date to check for containment. /// - parameter date2: A date to check for containment. /// - returns: `true` if `date1` and `date2` are in the same day. public func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool { return _handle.map { $0.isDate(date1, inSameDayAs: date2) } } /// Returns `true` if the given date is within today, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within today. public func isDateInToday(_ date: Date) -> Bool { return _handle.map { $0.isDateInToday(date) } } /// Returns `true` if the given date is within yesterday, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within yesterday. public func isDateInYesterday(_ date: Date) -> Bool { return _handle.map { $0.isDateInYesterday(date) } } /// Returns `true` if the given date is within tomorrow, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within tomorrow. public func isDateInTomorrow(_ date: Date) -> Bool { return _handle.map { $0.isDateInTomorrow(date) } } /// Returns `true` if the given date is within a weekend period, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within a weekend. public func isDateInWeekend(_ date: Date) -> Bool { return _handle.map { $0.isDateInWeekend(date) } } /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// /// Note that a given entire day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - seealso: `dateIntervalOfWeekend(containing:)` /// - parameter date: The date at which to start the search. /// - parameter start: When the result is `true`, set /// - returns: `true` if a date range could be found, and `false` if the date is not in a weekend. public func dateIntervalOfWeekend(containing date: Date, start: inout Date, interval: inout TimeInterval) -> Bool { if let result = _handle.map({ $0.range(ofWeekendContaining: date) }) { start = result.start interval = result.duration return true } else { return false } } /// Returns a `DateInterval` of the weekend contained by the given date, or nil if the date is not in a weekend. /// /// - parameter date: The date contained in the weekend. /// - returns: A `DateInterval`, or nil if the date is not in a weekend. public func dateIntervalOfWeekend(containing date: Date) -> DateInterval? { return _handle.map({ $0.range(ofWeekendContaining: date) }) } /// Returns the range of the next weekend via two inout parameters. The weekend starts strictly after the given date. /// /// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date. /// /// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - parameter date: The date at which to begin the search. /// - parameter direction: Which direction in time to search. The default value is `.forward`. /// - returns: A `DateInterval`, or nil if the weekend could not be found. public func nextWeekend(startingAfter date: Date, start: inout Date, interval: inout TimeInterval, direction: SearchDirection = .forward) -> Bool { // The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all. if let result = _handle.map({ $0.nextWeekendAfter(date, options: direction == .backward ? [.searchBackwards] : []) }) { start = result.start interval = result.duration return true } else { return false } } /// Returns a `DateInterval` of the next weekend, which starts strictly after the given date. /// /// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date. /// /// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - parameter date: The date at which to begin the search. /// - parameter direction: Which direction in time to search. The default value is `.forward`. /// - returns: A `DateInterval`, or nil if weekends do not exist in the specific calendar or locale. public func nextWeekend(startingAfter date: Date, direction: SearchDirection = .forward) -> DateInterval? { // The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all. return _handle.map({ $0.nextWeekendAfter(date, options: direction == .backward ? [.searchBackwards] : []) }) } // MARK: - // MARK: Searching /// The direction in time to search. public enum SearchDirection { /// Search for a date later in time than the start date. case forward /// Search for a date earlier in time than the start date. case backward } /// Determines which result to use when a time is repeated on a day in a calendar (for example, during a daylight saving transition when the times between 2:00am and 3:00am may happen twice). public enum RepeatedTimePolicy { /// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the first occurrence. case first /// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the last occurrence. case last } /// A hint to the search algorithm to control the method used for searching for dates. public enum MatchingPolicy { /// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the next existing time which exists. /// /// For example, during a daylight saving transition there may be no 2:37am. The result would then be 3:00am, if that does exist. case nextTime /// If specified, and there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the method will return the next existing value of the missing component and preserves the lower components' values (e.g., no 2:37am results in 3:37am, if that exists). case nextTimePreservingSmallerComponents /// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the previous existing value of the missing component and preserves the lower components' values. /// /// For example, during a daylight saving transition there may be no 2:37am. The result would then be 1:37am, if that does exist. case previousTimePreservingSmallerComponents /// If specified, the algorithm travels as far forward or backward as necessary looking for a match. /// /// For example, if searching for Feb 29 in the Gregorian calendar, the algorithm may choose March 1 instead (for example, if the year is not a leap year). If you wish to find the next Feb 29 without the algorithm adjusting the next higher component in the specified `DateComponents`, then use the `strict` option. /// - note: There are ultimately implementation-defined limits in how far distant the search will go. case strict } @available(*, unavailable, message: "use nextWeekend(startingAfter:matching:matchingPolicy:repeatedTimePolicy:direction:using:) instead") public func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { fatalError() } /// Computes the dates which match (or most closely match) a given set of components, and calls the closure once for each of them, until the enumeration is stopped. /// /// There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. /// /// If `direction` is set to `.backward`, this method finds the previous match before the given date. The intent is that the same matches as for a `.forward` search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). /// /// If an exact match is not possible, and requested with the `strict` option, nil is passed to the closure and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) /// /// Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the `DateComponents` matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). /// /// The enumeration is stopped by setting `stop` to `true` in the closure and returning. It is not necessary to set `stop` to `false` to keep the enumeration going. /// - parameter start: The `Date` at which to start the search. /// - parameter components: The `DateComponents` to use as input to the search algorithm. /// - parameter matchingPolicy: Determines the behavior of the search algorithm when the input produces an ambiguous result. /// - parameter repeatedTimePolicy: Determines the behavior of the search algorithm when the input produces a time that occurs twice on a particular day. /// - parameter direction: Which direction in time to search. The default value is `.forward`, which means later in time. /// - parameter block: A closure that is called with search results. public func enumerateDates(startingAfter start: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward, using block: (_ result: Date?, _ exactMatch: Bool, _ stop: inout Bool) -> Void) { _handle.map { $0.enumerateDates(startingAfter: start, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) { (result, exactMatch, stop) in var stopv = false block(result, exactMatch, &stopv) if stopv { stop.pointee = true } } } } @available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead") public func nextDate(after date: Date, matching comps: DateComponents, options: NSCalendar.Options = []) -> Date? { fatalError() } /// Computes the next date which matches (or most closely matches) a given set of components. /// /// The general semantics follow those of the `enumerateDates` function. /// To compute a sequence of results, use the `enumerateDates` function, rather than looping and calling this method with the previous loop iteration's result. /// - parameter date: The starting date. /// - parameter components: The components to search for. /// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`. /// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`. /// - parameter direction: Specifies the direction in time to search. Default is `.forward`. /// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found. public func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? { return _handle.map { $0.nextDate(after: date, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) } } @available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead") public func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: NSCalendar.Options = []) -> Date? { fatalError() } // MARK: - // @available(*, unavailable, renamed: "date(bySetting:value:of:)") public func date(bySettingUnit unit: NSCalendar.Unit, value v: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the component already has that value, this may result in a date which is the same as the given date. /// /// Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. /// If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other components to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. /// The exact behavior of this method is implementation-defined. For example, if changing the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? The algorithm will try to produce a result which is in the next-larger component to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For more control over the exact behavior, use `nextDate(after:matching:matchingPolicy:behavior:direction:)`. public func date(bySetting component: Component, value: Int, of date: Date) -> Date? { return _handle.map { $0.date(bySettingUnit: Calendar._toCalendarUnit([component]), value: value, of: date, options: []) } } @available(*, unavailable, message: "use date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) instead") public func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by setting hour, minute, and second to a given time on a specified `Date`. /// /// If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). /// The intent is to return a date on the same day as the original date argument. This may result in a date which is backward than the given date, of course. /// - parameter hour: A specified hour. /// - parameter minute: A specified minute. /// - parameter second: A specified second. /// - parameter date: The date to start calculation with. /// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`. /// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`. /// - parameter direction: Specifies the direction in time to search. Default is `.forward`. /// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found. public func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: MatchingPolicy = .nextTime, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? { return _handle.map { $0.date(bySettingHour: hour, minute: minute, second: second, of: date, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) } } /// Determine if the `Date` has all of the specified `DateComponents`. /// /// It may be useful to test the return value of `nextDate(after:matching:matchingPolicy:behavior:direction:)` to find out if the components were obeyed or if the method had to fudge the result value due to missing time (for example, a daylight saving time transition). /// /// - returns: `true` if the date matches all of the components, otherwise `false`. public func date(_ date: Date, matchesComponents components: DateComponents) -> Bool { return _handle.map { $0.date(date, matchesComponents: components) } } // MARK: - public func hash(into hasher: inout Hasher) { // We implement hash ourselves, because we need to make sure autoupdating calendars have the same hash if _autoupdating { hasher.combine(false) } else { hasher.combine(true) hasher.combine(_handle.map { $0 }) } } public static func ==(lhs: Calendar, rhs: Calendar) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { // NSCalendar's isEqual is broken (27019864) so we must implement this ourselves return lhs.identifier == rhs.identifier && lhs.locale == rhs.locale && lhs.timeZone == rhs.timeZone && lhs.firstWeekday == rhs.firstWeekday && lhs.minimumDaysInFirstWeek == rhs.minimumDaysInFirstWeek } } // MARK: - // MARK: Conversion Functions /// Turn our more-specific options into the big bucket option set of NSCalendar internal static func _toCalendarOptions(matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy, direction: SearchDirection) -> NSCalendar.Options { var result: NSCalendar.Options = [] switch matchingPolicy { case .nextTime: result.insert(.matchNextTime) case .nextTimePreservingSmallerComponents: result.insert(.matchNextTimePreservingSmallerUnits) case .previousTimePreservingSmallerComponents: result.insert(.matchPreviousTimePreservingSmallerUnits) case .strict: result.insert(.matchStrictly) } switch repeatedTimePolicy { case .first: result.insert(.matchFirst) case .last: result.insert(.matchLast) } switch direction { case .backward: result.insert(.searchBackwards) case .forward: break } return result } internal static func _toCalendarUnit(_ units: Set<Component>) -> NSCalendar.Unit { let unitMap: [Component : NSCalendar.Unit] = [.era: .era, .year: .year, .month: .month, .day: .day, .hour: .hour, .minute: .minute, .second: .second, .weekday: .weekday, .weekdayOrdinal: .weekdayOrdinal, .quarter: .quarter, .weekOfMonth: .weekOfMonth, .weekOfYear: .weekOfYear, .yearForWeekOfYear: .yearForWeekOfYear, .nanosecond: .nanosecond, .calendar: .calendar, .timeZone: .timeZone] var result = NSCalendar.Unit() for u in units { result.insert(unitMap[u]!) } return result } internal static func _fromCalendarUnit(_ unit: NSCalendar.Unit) -> Component { switch unit { case .era: return .era case .year: return .year case .month: return .month case .day: return .day case .hour: return .hour case .minute: return .minute case .second: return .second case .weekday: return .weekday case .weekdayOrdinal: return .weekdayOrdinal case .quarter: return .quarter case .weekOfMonth: return .weekOfMonth case .weekOfYear: return .weekOfYear case .yearForWeekOfYear: return .yearForWeekOfYear case .nanosecond: return .nanosecond case .calendar: return .calendar case .timeZone: return .timeZone default: fatalError() } } internal static func _fromCalendarUnits(_ units: NSCalendar.Unit) -> Set<Component> { var result = Set<Component>() if units.contains(.era) { result.insert(.era) } if units.contains(.year) { result.insert(.year) } if units.contains(.month) { result.insert(.month) } if units.contains(.day) { result.insert(.day) } if units.contains(.hour) { result.insert(.hour) } if units.contains(.minute) { result.insert(.minute) } if units.contains(.second) { result.insert(.second) } if units.contains(.weekday) { result.insert(.weekday) } if units.contains(.weekdayOrdinal) { result.insert(.weekdayOrdinal) } if units.contains(.quarter) { result.insert(.quarter) } if units.contains(.weekOfMonth) { result.insert(.weekOfMonth) } if units.contains(.weekOfYear) { result.insert(.weekOfYear) } if units.contains(.yearForWeekOfYear) { result.insert(.yearForWeekOfYear) } if units.contains(.nanosecond) { result.insert(.nanosecond) } if units.contains(.calendar) { result.insert(.calendar) } if units.contains(.timeZone) { result.insert(.timeZone) } return result } internal static func _toNSCalendarIdentifier(_ identifier: Identifier) -> NSCalendar.Identifier { if #available(macOS 10.10, iOS 8.0, *) { let identifierMap: [Identifier : NSCalendar.Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .iso8601: .ISO8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina, .islamicTabular: .islamicTabular, .islamicUmmAlQura: .islamicUmmAlQura] return identifierMap[identifier]! } else { let identifierMap: [Identifier : NSCalendar.Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .iso8601: .ISO8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina] return identifierMap[identifier]! } } internal static func _fromNSCalendarIdentifier(_ identifier: NSCalendar.Identifier) -> Identifier { if #available(macOS 10.10, iOS 8.0, *) { let identifierMap: [NSCalendar.Identifier : Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .ISO8601: .iso8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina, .islamicTabular: .islamicTabular, .islamicUmmAlQura: .islamicUmmAlQura] return identifierMap[identifier]! } else { let identifierMap: [NSCalendar.Identifier : Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .ISO8601: .iso8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina] return identifierMap[identifier]! } } } extension Calendar : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable { private var _kindDescription : String { if self == .autoupdatingCurrent { return "autoupdatingCurrent" } else if self == .current { return "current" } else { return "fixed" } } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription: String { return "\(identifier) (\(_kindDescription))" } public var customMirror: Mirror { let children: [(label: String?, value: Any)] = [ (label: "identifier", value: identifier), (label: "kind", value: _kindDescription), (label: "locale", value: locale as Any), (label: "timeZone", value: timeZone), (label: "firstWeekday", value: firstWeekday), (label: "minimumDaysInFirstWeek", value: minimumDaysInFirstWeek) ] return Mirror(self, children: children, displayStyle: .struct) } } extension Calendar: _ObjectiveCBridgeable { public typealias _ObjectType = NSCalendar @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSCalendar { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(NSCalendar.self) to \(self)") } } @discardableResult public static func _conditionallyBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) -> Bool { result = Calendar(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCalendar?) -> Calendar { var result: Calendar? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension Calendar : Codable { private enum CodingKeys : Int, CodingKey { case identifier case locale case timeZone case firstWeekday case minimumDaysInFirstWeek } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifierString = try container.decode(String.self, forKey: .identifier) let identifier = Calendar._fromNSCalendarIdentifier(NSCalendar.Identifier(rawValue: identifierString)) self.init(identifier: identifier) self.locale = try container.decodeIfPresent(Locale.self, forKey: .locale) self.timeZone = try container.decode(TimeZone.self, forKey: .timeZone) self.firstWeekday = try container.decode(Int.self, forKey: .firstWeekday) self.minimumDaysInFirstWeek = try container.decode(Int.self, forKey: .minimumDaysInFirstWeek) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) let identifier = Calendar._toNSCalendarIdentifier(self.identifier).rawValue try container.encode(identifier, forKey: .identifier) try container.encode(self.locale, forKey: .locale) try container.encode(self.timeZone, forKey: .timeZone) try container.encode(self.firstWeekday, forKey: .firstWeekday) try container.encode(self.minimumDaysInFirstWeek, forKey: .minimumDaysInFirstWeek) } }
apache-2.0
09f025467a8e5edb4836c3c4fbd635c6
53.080816
874
0.658108
4.750054
false
false
false
false
daxiangfei/RTSwiftUtils
RTSwiftUtils/Extension/BaseDataExtension.swift
1
4420
// // BaseDataExtension.swift // XiaoZhuGeJinFu // // Created by rongteng on 16/7/26. // Copyright © 2016年 rongteng. All rights reserved. // import Foundation extension Double { ///保留小数点后两位 不进位 public var toDecimal:Double { let handler = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let dec = NSDecimalNumber(value: self) let dd = dec.rounding(accordingToBehavior: handler) return dd.doubleValue } ///取整 public var toIntString:String { let intValue = floor(self) //舍弃小数位 return String(format: "%.0f", intValue) } ///保留后两位小数点 小数点后两位不进位 public var toDecimalString:String { let handler = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let dec = NSDecimalNumber(value: self) let dd = dec.rounding(accordingToBehavior: handler) return "\(dd.doubleValue)"; } public var intValue:Int { let intValue = floor(self) //舍弃小数位 return Int(intValue) } //字符串值 public var stringValue:String { //正常使用 String(self) 会出现 //1、如1.40 返回的是1.4 //2、如1.00 或者 1 返回的是1.0 //3、其它的正常显现 4.59 返回4.59 let strValue = String(self) let subStrArr = strValue.components(separatedBy: ".") guard subStrArr.count == 2 else { return strValue} let lastStr = subStrArr[1] if lastStr.count >= 2 { return strValue }else { return subStrArr[0] + "." + lastStr + "0" } } ///减去 public func subtracting(_ value:Double) -> Double { let payAmountNum = NSDecimalNumber(value: self) let surplusAmountNum = NSDecimalNumber(value: value) let newDecimal = payAmountNum.subtracting(surplusAmountNum).doubleValue return newDecimal } ///判断小数点后的值是否为零,为零则返回整数部分的值,不为零就返回全部 public var judgeDoubleOrInt : String { let num = Int(self) if self > Double(num) { return String(self) } return String(num) } ///保留小数点后两位 不进位 public var toFloatDecimal:Float { let handler = NSDecimalNumberHandler(roundingMode: .down, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let hundredDe = NSDecimalNumber(value: 1) let numOne = NSDecimalNumber(value: self) let result = numOne.multiplying(by: hundredDe, withBehavior: handler) return result.floatValue } ///判断小数点后的值是否为零,为零则返回true,不为零就返回false public var judgeDoubleIsorInt : Bool { let num = Int(self) if self > Double(num) { return false } return true } } extension Float { ///保留小数点后两位 不进位 public var toDecimal:Float { let fl = floor(self * 100) return fl/100 } ///保留后两位小数点 小数点后两位不进位 public var toDecimalString: String { return String(format: "%.2f", self.toDecimal) } ///取整 public var toIntString:String { let intVL = floor(self) //舍弃小数位 return String(format: "%.0f", intVL) } public var stringValue:String { return String(format: "%.2f",self) } public var intValue:Int { let intValue = floorf(self) //舍弃小数位 return Int(intValue) } } extension Int { public var ratioWidth:CGFloat { let floatValue = CGFloat(self) let value = UIScreen.main.bounds.width * floatValue/320 return value < floatValue ? floatValue:value } public var ratioHeight:CGFloat { let floatValue = CGFloat(self) let value = UIScreen.main.bounds.height * floatValue/568 return value < floatValue ? floatValue:value } public var stringValue: String { return String(self) } } extension CGFloat { public var ratioWidth:CGFloat { let value = UIScreen.main.bounds.width * self/320 return value < self ? self:value } public var ratioHeight:CGFloat { let value = UIScreen.main.bounds.height * self/568 return value < self ? self:value } public var intValue:Int { return Int(self) } }
mit
3c3c77f4c481a182ebebf682a88e7c49
23.221557
172
0.673424
3.605169
false
false
false
false
CodaFi/PersistentStructure.swift
Persistent/AbstractSeq.swift
1
2253
// // AbstractSeq.swift // Persistent // // Created by Robert Widmann on 11/15/15. // Copyright © 2015 TypeLift. All rights reserved. // public class AbstractSeq : ISeq, ISequential, IList, IHashEq { private let _hash : Int private let _hasheq : Int internal let _meta : IPersistentMap? init() { _hash = -1 _hasheq = -1 _meta = nil } init(meta : IPersistentMap?) { _hash = -1 _hasheq = -1 _meta = meta } public func equiv(obj: AnyObject) -> Bool { if !(obj is ISequential || obj is IList) { return false } for (e1, e2) in zip(self.seq.generate(), Utils.seq(obj).generate()) { if !Utils.equiv(e1, other: e2) { return false } } return self.seq.count == Utils.seq(obj).count } public func isEqual(obj: AnyObject) -> Bool { if self === obj { return true } if !(obj is ISequential || obj is IList) { return false } for (e1, e2) in zip(self.seq.generate(), Utils.seq(obj).generate()) { if !Utils.equiv(e1, other: e2) { return false } } return self.seq.count == Utils.seq(obj).count } public var count : Int { var i : Int = 1; for var s : ISeq? = self.next; s != nil; s = s!.next, i = i.successor() { if let ss = s as? ICounted { return i + ss.count; } } return i; } public var hasheq : Int { return 0 } public func lastIndexOf(other : AnyObject) -> Int { return -1 } public func subListFromIndex(fromIndex : Int, toIndex: Int) -> IList? { return nil } public func containsObject(object: AnyObject) -> Bool { return false } public var toArray : Array<AnyObject> { return [] } public var isEmpty : Bool { return true } public var seq : ISeq { return self } public var first : AnyObject? { fatalError("\(__FUNCTION__) unimplemented") } public var next : ISeq { fatalError("\(__FUNCTION__) unimplemented") } public var empty : IPersistentCollection { return PersistentList.empty } public var more : ISeq { if let s : ISeq = self.next { return s } return PersistentList.empty } public func cons(other : AnyObject) -> IPersistentCollection { return AbstractCons(first: other, rest: self) } public func cons(other: AnyObject) -> ISeq { return AbstractCons(first: other, rest: self) } }
mit
5074344fbf4a400ffabbc23848289fa3
18.247863
75
0.631439
2.947644
false
false
false
false
johnnysay/GoodAccountsMakeGoodFriends
Good Accounts/Controllers/ParticipantViewController.swift
1
6482
// // ParticipantViewController.swift // Good Accounts // // Created by Johnny on 13/02/2016. // Copyright © 2016 fake. All rights reserved. // import UIKit import RealmSwift import Reusable final class ParticipantViewController: UIViewController, StoryboardBased { var activeField: UITextField? @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var spendingTextField: UITextField! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var validateButton: UIButton! @IBOutlet weak var scrollView: UIScrollView! private struct Segue { static let unwindAndSave = "unwindAndSave" static let unwindAndCancel = "unwindAndCancel" } /// Current participant. var participant: Participant? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self spendingTextField.delegate = self cancelButton.layer.cornerRadius = 8 cancelButton.backgroundColor = Color.darkBlue validateButton.layer.cornerRadius = 8 validateButton.backgroundColor = Color.darkBlue addKeyboardToolbar() registerForKeyboardNotifications() guard let participant = participant else { return } nameTextField.text = participant.name if participant.investment != 0.0 { spendingTextField.text = NumberFormatter.string(from: participant.investment) } } // MARK: - Scrolling with keyboard appearing / disappearing func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWasShown(notification: NSNotification) { guard let info = notification.userInfo else { return } guard let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return } let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets var aRect = view.frame aRect.size.height -= keyboardSize.height guard let activeField = activeField else { return } if !aRect.contains(activeField.frame.origin) { scrollView.scrollRectToVisible(activeField.frame, animated: true) } } @objc func keyboardWillBeHidden(notification: NSNotification) { // Once keyboard disappears, restore original positions guard let info = notification.userInfo else { return } guard let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return } let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: -keyboardSize.height, right: 0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets view.endEditing(true) } // MARK: - Keyboard func addKeyboardToolbar() { let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 50)) toolbar.barStyle = .default let previousBarButtonItem = UIBarButtonItem(title: "Préc.", style: .plain, target: self, action: #selector(previousButtonAction)) let nextBarButtonItem = UIBarButtonItem(title: "Suiv.", style: .plain, target: self, action: #selector(nextButtonAction)) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let doneBarButtonItem = UIBarButtonItem(title: "OK", style: .done, target: self, action: #selector(doneButtonAction)) var items = [UIBarButtonItem]() items.append(previousBarButtonItem) items.append(nextBarButtonItem) items.append(flexibleSpace) items.append(doneBarButtonItem) toolbar.items = items toolbar.sizeToFit() nameTextField.inputAccessoryView = toolbar spendingTextField.inputAccessoryView = toolbar } @objc func previousButtonAction() { if nameTextField.isFirstResponder { nameTextField.resignFirstResponder() } else if spendingTextField.isFirstResponder { nameTextField.becomeFirstResponder() } } @objc func nextButtonAction() { if nameTextField.isFirstResponder { spendingTextField.becomeFirstResponder() } else if spendingTextField.isFirstResponder { spendingTextField.resignFirstResponder() } } @objc func doneButtonAction() { nameTextField.resignFirstResponder() spendingTextField.resignFirstResponder() } // MARK: - Actions @IBAction func cancelEditing(_ sender: UIButton) { dismiss(animated: true, completion: nil) } @IBAction func validateEditing(_ sender: UIButton) { if let name = nameTextField.text { if !name.isEmpty { try! Realm().write { participant?.name = name } } } var investment: Double? switch spendingTextField.text { case .none, .some(""): investment = 0.0 case .some(let investmentString): investment = NumberFormatter.double(from: investmentString) } if let investment = investment { try! Realm().write { participant?.investment = investment } } NotificationCenter.default.post(name: .editingParticipant, object: nil) dismiss(animated: true, completion: nil) } } // MARK: - UITextFiedDelegate extension ParticipantViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { activeField = textField } func textFieldDidEndEditing(_ textField: UITextField) { activeField = nil } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if textField == nameTextField { spendingTextField.becomeFirstResponder() } return true } }
mit
0d945e1c3a7d6da51f605121a2e5ac14
30.921182
131
0.671142
5.151033
false
false
false
false
1yvT0s/XWebView
XWebView/XWVMetaObject.swift
1
9480
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import ObjectiveC class XWVMetaObject: CollectionType { enum Member { case Method(selector: Selector, arity: Int32) case Property(getter: Selector, setter: Selector) case Initializer(selector: Selector, arity: Int32) var isMethod: Bool { switch self { case let .Method(_): return true default: return false } } var isProperty: Bool { switch self { case let .Property(_, _): return true default: return false } } var isInitializer: Bool { switch self { case let .Initializer(_, _): return true default: return false } } var selector: Selector? { switch self { case let .Method(selector, _): assert(selector != Selector()) return selector case let .Initializer(selector, _): assert(selector != Selector()) return selector default: return nil } } var getter: Selector? { switch self { case let .Property(getter, _): assert(getter != Selector()) return getter default: return nil } } var setter: Selector? { switch self { case let .Property(getter, setter): assert(getter != Selector()) return setter default: return nil } } var type: String { let promise: Bool let arity: Int32 switch self { case let .Method(selector, a): promise = selector.description.hasSuffix(":promiseObject:") || selector.description.hasSuffix("PromiseObject:") arity = a case let .Initializer(selector, a): promise = true arity = a < 0 ? a: a + 1 default: promise = false arity = -1 } if !promise && arity < 0 { return "" } return "#" + (arity >= 0 ? "\(arity)" : "") + (promise ? "p" : "a") } } let plugin: AnyClass private var members = [String: Member]() private static let exclusion: Set<Selector> = { var methods = instanceMethods(forProtocol: XWVScripting.self) methods.remove(Selector("invokeDefaultMethodWithArguments:")) return methods.union([ Selector(".cxx_construct"), Selector(".cxx_destruct"), Selector("dealloc"), Selector("copy") ]) }() init(plugin: AnyClass) { self.plugin = plugin let cls: AnyClass = plugin enumerateExcluding(self.dynamicType.exclusion) { (var name, var member) -> Bool in switch member { case let .Method(selector, _): if let end = find(name, ":") { name = name[name.startIndex ..< end] } if cls.conformsToProtocol(XWVScripting.self) { if cls.isSelectorExcludedFromScript?(selector) ?? false { return true } if selector == Selector("invokeDefaultMethodWithArguments:") { member = .Method(selector: selector, arity: -1) name = "" } else { name = cls.scriptNameForSelector?(selector) ?? name } } else if name.hasPrefix("_") { return true } case let .Property(_, _): if cls.conformsToProtocol(XWVScripting.self) { if let isExcluded = cls.isKeyExcludedFromScript where name.withCString(isExcluded) { return true } if let scriptNameForKey = cls.scriptNameForKey { name = name.withCString(scriptNameForKey) ?? name } } else if name.hasPrefix("_") { return true } case let .Initializer(selector, _): if selector == Selector("initByScriptWithArguments:") { member = .Initializer(selector: selector, arity: -1) name = "" } else if cls.conformsToProtocol(XWVScripting.self) { name = cls.scriptNameForSelector?(selector) ?? name } if !name.isEmpty { return true } } assert(self.members.indexForKey(name) == nil, "Script name '\(name)' has conflict") self.members[name] = member return true } } private func enumerateExcluding(selectors: Set<Selector>, callback: ((String, Member)->Bool)) -> Bool { var known = selectors // enumerate properties let properties = class_copyPropertyList(plugin, nil) if properties != nil { for var prop = properties; prop.memory != nil; prop = prop.successor() { let name = String(UTF8String: property_getName(prop.memory))! // get getter var attr = property_copyAttributeValue(prop.memory, "G") let getter = Selector(attr == nil ? name : String(UTF8String: attr)!) free(attr) if known.contains(getter) { continue } known.insert(getter) // get setter if readwrite var setter = Selector() attr = property_copyAttributeValue(prop.memory, "R") if attr == nil { attr = property_copyAttributeValue(prop.memory, "S") if attr == nil { setter = Selector("set\(prefix(name, 1).uppercaseString)\(dropFirst(name)):") } else { setter = Selector(String(UTF8String: attr)!) } if known.contains(setter) { setter = Selector() } else { known.insert(setter) } } free(attr) let info = Member.Property(getter: getter, setter: setter) if !callback(name, info) { free(properties) return false } } free(properties) } // enumerate methods let methods = class_copyMethodList(plugin, nil) if methods != nil { for var method = methods; method.memory != nil; method = method.successor() { let sel = method_getName(method.memory) if !known.contains(sel) { let arity = Int32(method_getNumberOfArguments(method.memory) - 2) let member: Member if sel.description.hasPrefix("init") { member = Member.Initializer(selector: sel, arity: arity) } else { member = Member.Method(selector: sel, arity: arity) } if !callback(sel.description, member) { free(methods) return false } } } free(methods) } return true } } extension XWVMetaObject { // SequenceType typealias Generator = DictionaryGenerator<String, Member> func generate() -> Generator { return members.generate() } // CollectionType typealias Index = DictionaryIndex<String, Member> var startIndex: Index { return members.startIndex } var endIndex: Index { return members.endIndex } subscript (position: Index) -> (String, Member) { return members[position] } subscript (name: String) -> Member? { return members[name] } } private func instanceMethods(forProtocol aProtocol: Protocol) -> Set<Selector> { var selectors = Set<Selector>() for (req, inst) in [(true, true), (false, true)] { let methodList = protocol_copyMethodDescriptionList(aProtocol.self, req, inst, nil) if methodList != nil { for var desc = methodList; desc.memory.name != nil; desc = desc.successor() { selectors.insert(desc.memory.name) } free(methodList) } } return selectors }
apache-2.0
ae81156cd2dc824a4ef4ef91e15db2d8
33.852941
107
0.493143
5.392491
false
false
false
false
ashfurrow/ReactiveMoya
Example/ReactiveMoyaExample/ReactiveMoyaViewController.swift
3
2615
import UIKit import ReactiveCocoa import Result import Moya let ReactiveGithubProvider = ReactiveCocoaMoyaProvider<Github>() class ReactiveMoyaViewController: UITableViewController, UIGestureRecognizerDelegate { let repos = MutableProperty<NSArray>(NSArray()) override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: - API func downloadRepositories(username: String) { ReactiveGithubProvider.requestJSONArray(.UserRepositories(username)) |> start(error: { (error: NSError) in self.showErrorAlert("Github Fetch", error: error) }, next: { (result: NSArray) in self.repos.put(result) self.title = "\(username)'s repos" }) } func downloadZen() { ReactiveGithubProvider.requestString(.Zen) |> start(error: { (error: NSError) in self.showErrorAlert("Zen", error: error) }, next: { (string: String) in self.showAlert("Zen", message: string) }) } // MARK: - Actions // MARK: IBActions @IBAction func searchPressed(sender: UIBarButtonItem) { showInputPrompt("Username", message: "Enter a github username", action: { username in self.downloadRepositories(username) }) } @IBAction func zenPressed(sender: UIBarButtonItem) { downloadZen() } // MARK: - Delegates // MARK: UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.value.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell if let object = repos.value[indexPath.row] as? NSDictionary { cell.textLabel?.text = object["name"] as? String } return cell } // MARK: - Setup private func setup() { self.navigationController?.interactivePopGestureRecognizer.delegate = self // When repos changes and is non-nil, reload the table view repos.producer |> start(next: { _ in self.tableView.reloadData() }) // Download all repositories for "justinmakaila" downloadRepositories("justinmakaila") } }
mit
3bc73085e48441a6045f7ce38f0a7633
29.764706
118
0.590822
5.391753
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Prefix Sum/915_Partition Array into Disjoint Intervals.swift
1
2075
// 915_Partition Array into Disjoint Intervals // https://leetcode.com/problems/partition-array-into-disjoint-intervals/ // // Created by Honghao Zhang on 10/5/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // // Given an array A, partition it into two (contiguous) subarrays left and right so that: // //Every element in left is less than or equal to every element in right. //left and right are non-empty. //left has the smallest possible size. //Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists. // // // //Example 1: // //Input: [5,0,3,8,6] //Output: 3 //Explanation: left = [5,0,3], right = [8,6] //Example 2: // //Input: [1,1,1,0,6,12] //Output: 4 //Explanation: left = [1,1,1,0], right = [6,12] // // //Note: // //2 <= A.length <= 30000 //0 <= A[i] <= 10^6 //It is guaranteed there is at least one way to partition A as described. // // 寻找一个dividing line,左边的所有元素<=右边的所有元素 // 找到一个缝隙,使左边的元素都 <= 右边的元素 import Foundation class Num915 { // 看左向右扫描,保留最大值(左边数组保留最大值) // 看右向左扫描,保留最小值(右边数组保留最小值) // 然后再从左到右扫描,寻找第一个符合条件的point func partitionDisjoint(_ A: [Int]) -> Int { // stores the max element from 0...index var leftMax: [Int] = Array(repeating: Int.min, count: A.count) // stores the min element from index..<count var rightMin: [Int] = Array(repeating: Int.max, count: A.count) var _leftMax = Int.min for i in 0..<A.count { _leftMax = max(_leftMax, A[i]) leftMax[i] = _leftMax } var _rightMin = Int.max for i in (0..<A.count).reversed() { _rightMin = min(_rightMin, A[i]) rightMin[i] = _rightMin } // find the break point for i in 0..<(A.count - 1) { // left is 0...i if leftMax[i] <= rightMin[i + 1] { return i + 1 } } assertionFailure() return A.count } }
mit
df78b857606b175fa99f5d463427627e
24.216216
105
0.627546
2.952532
false
false
false
false
AbelSu131/ios-charts
Charts/Classes/Renderers/ChartYAxisRendererHorizontalBarChart.swift
1
9907
// // ChartYAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartYAxisRendererHorizontalBarChart: ChartYAxisRenderer { public override init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer); } /// Computes the axis values. public override func computeAxis(var #yMin: Double, var yMax: Double) { // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if (viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX) { var p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)); var p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)); if (!_yAxis.isInverted) { yMin = Double(p1.x); yMax = Double(p2.x); } else { yMin = Double(p2.x); yMax = Double(p1.x); } } computeAxisValues(min: yMin, max: yMax); } /// draws the y-axis labels to the screen public override func renderAxisLabels(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return; } var positions = [CGPoint](); positions.reserveCapacity(_yAxis.entries.count); for (var i = 0; i < _yAxis.entries.count; i++) { positions.append(CGPoint(x: CGFloat(_yAxis.entries[i]), y: 0.0)) } transformer.pointValuesToPixel(&positions); var lineHeight = _yAxis.labelFont.lineHeight; var yoffset = lineHeight + _yAxis.yOffset; var dependency = _yAxis.axisDependency; var labelPosition = _yAxis.labelPosition; var yPos: CGFloat = 0.0; if (dependency == .Left) { if (labelPosition == .OutsideChart) { yoffset = 3.0; yPos = viewPortHandler.contentTop; } else { yoffset = yoffset * -1; yPos = viewPortHandler.contentTop; } } else { if (labelPosition == .OutsideChart) { yoffset = yoffset * -1.0; yPos = viewPortHandler.contentBottom; } else { yoffset = 4.0; yPos = viewPortHandler.contentBottom; } } yPos -= lineHeight; drawYLabels(context: context, fixedPosition: yPos, positions: positions, offset: yoffset); } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _yAxis.axisLineWidth); if (_yAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } if (_yAxis.axisDependency == .Left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } /// draws the y-labels on the specified x-position internal func drawYLabels(#context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { var labelFont = _yAxis.labelFont; var labelTextColor = _yAxis.labelTextColor; for (var i = 0; i < _yAxis.entryCount; i++) { var text = _yAxis.getFormattedLabel(i); if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1) { return; } ChartUtils.drawText(context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } public override func renderGridLines(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawGridLinesEnabled) { return; } CGContextSaveGState(context); // pre alloc var position = CGPoint(); CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor); CGContextSetLineWidth(context, _yAxis.gridLineWidth); if (_yAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } // draw the horizontal grid for (var i = 0; i < _yAxis.entryCount; i++) { position.x = CGFloat(_yAxis.entries[i]); position.y = 0.0; transformer.pointValueToPixel(&position); CGContextBeginPath(context); CGContextMoveToPoint(context, position.x, viewPortHandler.contentTop); CGContextAddLineToPoint(context, position.x, viewPortHandler.contentBottom); CGContextStrokePath(context); } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _yAxis.limitLines; if (limitLines.count <= 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = CGFloat(l.limit); position.y = 0.0; position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = position.x; _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _limitLineSegmentsBuffer[1].x = position.x; _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = l.lineWidth; var yOffset: CGFloat = add / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
apache-2.0
ad5c628e9ef9556de7cfb76fb9cfd957
33.643357
234
0.557384
5.597175
false
false
false
false
wfleming/SwiftLint
Source/SwiftLintFramework/Rules/NestingRule.swift
2
3197
// // NestingRule.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public struct NestingRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.Warning) public init() {} public static let description = RuleDescription( identifier: "nesting", name: "Nesting", description: "Types should be nested at most 1 level deep, " + "and statements should be nested at most 5 levels deep.", nonTriggeringExamples: ["class", "struct", "enum"].flatMap { kind in ["\(kind) Class0 { \(kind) Class1 {} }\n", "func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " + "func func5() {\n}\n}\n}\n}\n}\n}\n"] } + ["enum Enum0 { enum Enum1 { case Case } }"], triggeringExamples: ["class", "struct", "enum"].map { kind in "\(kind) A { \(kind) B { ↓\(kind) C {} } }\n" } + [ "func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " + "func func5() {\n↓func func6() {\n}\n}\n}\n}\n}\n}\n}\n" ] ) public func validateFile(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { return validateFile(file, kind: kind, dictionary: dictionary, level: 0) } func validateFile(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable], level: Int) -> [StyleViolation] { var violations = [StyleViolation]() let typeKinds: [SwiftDeclarationKind] = [.Class, .Struct, .Typealias, .Enum] if let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) { if level > 1 && typeKinds.contains(kind) { violations.append(StyleViolation(ruleDescription: self.dynamicType.description, severity: configuration.severity, location: Location(file: file, byteOffset: offset), reason: "Types should be nested at most 1 level deep")) } else if level > 5 { violations.append(StyleViolation(ruleDescription: self.dynamicType.description, severity: configuration.severity, location: Location(file: file, byteOffset: offset), reason: "Statements should be nested at most 5 levels deep")) } } let substructure = dictionary["key.substructure"] as? [SourceKitRepresentable] ?? [] violations.appendContentsOf(substructure.flatMap { subItem in if let subDict = subItem as? [String: SourceKitRepresentable], kind = (subDict["key.kind"] as? String).flatMap(SwiftDeclarationKind.init) { return (kind, subDict) } return nil }.flatMap { kind, subDict in return self.validateFile(file, kind: kind, dictionary: subDict, level: level + 1) }) return violations } }
mit
4ad01eb2f7a621c82f9547e9d8e85dcc
44.614286
99
0.576887
4.516266
false
true
false
false
tarrencev/BitWallet
BitWallet/TransactViewController.swift
1
6132
// // TransactViewController.swift // BitWallet // // Created by Tarrence van As on 9/2/14. // Copyright (c) 2014 tva. All rights reserved. // import UIKit class TransactViewController: UIViewController, UITextFieldDelegate { private let amountView = UIView(frame: CGRectMake(0, 100, 320, 100)), currency = Currency.BTC private func createTransactInputAccessoryView() -> UIView { let transactInputAccessoryView = UIView(frame: CGRectMake(0, 0, 320, 50)), requestButton = UIButton(frame: CGRectMake(0, 0, 160, 50)), sendButton = UIButton(frame: CGRectMake(161, 0, 159, 50)), centerBorder = UIView(frame: CGRectMake(requestButton.frame.size.width, 0, 0.25, transactInputAccessoryView.frame.size.height)), bottomBorder = UIView(frame: CGRectMake(0, transactInputAccessoryView.frame.size.height, transactInputAccessoryView.frame.size.width, 0.5)), topBorder = UIView(frame: CGRectMake(0, 0, transactInputAccessoryView.frame.size.width, 0.5)) centerBorder.backgroundColor = Utilities.colorize(0xb5b5b5, alpha: 1) bottomBorder.backgroundColor = Utilities.colorize(0xb5b5b5, alpha: 1) topBorder.backgroundColor = Utilities.colorize(0xb5b5b5, alpha: 1) requestButton.setTitle("Request", forState: UIControlState.Normal) requestButton.tag = 300 requestButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20) requestButton.backgroundColor = Utilities.colorize(0xfcfcfc, alpha: 1) requestButton.setTitleColor(UIColor.blackColor(), forState: .Normal) requestButton.addTarget(self, action: Selector("createTransaction:"), forControlEvents: UIControlEvents.TouchUpInside) sendButton.setTitle("Send", forState: UIControlState.Normal) sendButton.tag = 301 sendButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20) sendButton.backgroundColor = Utilities.colorize(0xfcfcfc, alpha: 1) sendButton.setTitleColor(UIColor.blackColor(), forState: .Normal) sendButton.addTarget(self, action: Selector("createTransaction:"), forControlEvents: UIControlEvents.TouchUpInside) transactInputAccessoryView.addSubview(requestButton) transactInputAccessoryView.addSubview(sendButton) transactInputAccessoryView.addSubview(centerBorder) transactInputAccessoryView.addSubview(bottomBorder) transactInputAccessoryView.addSubview(topBorder) return transactInputAccessoryView } func createTransaction(sender: AnyObject) { let button = sender as UIButton switch (button.tag) { case 300: println("request") case 301: println("send") default: println("wut") } } private func createAmountView() { let amountTextField = UITextField(frame: CGRectMake(0, 0, 320, 100)), currencySwitchButton = UIButton(frame: CGRectMake(0, 0, 320, 100)) currencySwitchButton.backgroundColor = .clearColor(); currencySwitchButton.addTarget(self, action: "switchCurrency", forControlEvents: UIControlEvents.AllTouchEvents) amountTextField.placeholder = "฿0" amountTextField.tag = 500 amountTextField.textAlignment = .Center amountTextField.tintColor = .clearColor() amountTextField.textColor = .whiteColor() amountTextField.keyboardType = UIKeyboardType.DecimalPad amountTextField.font = UIFont(name: "HelveticaNeue", size: 80) amountTextField.autoresizingMask = .FlexibleWidth | .FlexibleHeight // amountTextField.becomeFirstResponder() amountTextField.inputAccessoryView = createTransactInputAccessoryView() amountTextField.delegate = self amountView.addSubview(amountTextField) amountView.addSubview(currencySwitchButton) } private func createHeaderView() -> UIView { let navBar = UIView(frame: CGRectMake(0, 0, 320, 50)), bankButton = UIButton(frame: CGRectMake(275, 9, 32, 32)), receiveBitcoinButton = UIButton(frame: CGRectMake(15, 9, 32, 32)), titleLabel = UILabel(frame: CGRectMake(47, 0, 228, 50)) navBar.backgroundColor = Utilities.colorize(0x35485c, alpha: 1) bankButton.setBackgroundImage(UIImage(named: "wallet"), forState: UIControlState.Normal) receiveBitcoinButton.setBackgroundImage(UIImage(named: "cash_receiving"), forState: UIControlState.Normal) titleLabel.text = "Guap" titleLabel.textAlignment = .Center titleLabel.textColor = .whiteColor() titleLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 20) navBar.addSubview(bankButton) navBar.addSubview(receiveBitcoinButton) navBar.addSubview(titleLabel) return navBar } func switchCurrency() { } override func viewDidLoad() { super.viewDidLoad() createAmountView() self.view.addSubview(amountView) self.view.addSubview(createHeaderView()) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewIsScrollingOffScreen() { self.view.endEditing(true) println("scrolling off screen") } func viewIsScrollingOnScreen() { println("scrolling on screen") amountView.viewWithTag(500)?.becomeFirstResponder() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let text: String = textField.text if countElements(text) == 0 { textField.text = "฿" + string return false } return true } private enum Currency { case USD case BTC } }
mit
8e0ad2d60b7c036e022109540da82b5e
38.535484
152
0.664328
4.965964
false
false
false
false
ostanik/ArcChallenge
ArcTouchChallenge/View/StopsTableViewCell.swift
1
979
// // StopsTableViewCell.swift // ArcTouchChallenge // // Created by Ostanik on 30/10/16. // Copyright © 2016 Ostanik. All rights reserved. // import UIKit class StopsTableViewCell: UITableViewCell { @IBOutlet weak var bottomLine: UIView! @IBOutlet weak var topLine: UIView! @IBOutlet weak var name: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func bind(stop:Stop, position: StopPosition) { self.name.text = stop.name switch position { case .first: self.topLine.isHidden = true break case .last: self.bottomLine.isHidden = true break default: self.bottomLine.isHidden = false self.topLine.isHidden = false break } } }
mit
fdba40dc5e01382d919c49feee95ed26
22.853659
65
0.603272
4.506912
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPIGeofence/PIGeofenceDeleteOperation.swift
1
1881
/** * IBMPIGeofence * PIGeofenceDeleteOperation.swift * * Performs all communication to the PI Rest API. * * © Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import CocoaLumberjack @objc(IBMPIGeofenceDeleteOperation) final class PIGeofenceDeleteOperation:PIServiceOperation { let geofenceCode:String init(service: PIService,geofenceCode:String) { self.geofenceCode = geofenceCode super.init(service: service) self.name = "com.ibm.pi.PIGeofenceDeleteOperation" } override func main() { let path = "pi-config/v2/tenants/\(service.tenantCode)/orgs/\(service.orgCode!)/geofences/\(geofenceCode)" let url = NSURL(string:path,relativeToURL:self.service.baseURL) let URLComponents = NSURLComponents(URL:url!,resolvingAgainstBaseURL:true)! DDLogVerbose("\(URLComponents.URL)",asynchronous:false) let request = NSMutableURLRequest(URL:URLComponents.URL!,cachePolicy:.ReloadIgnoringLocalCacheData,timeoutInterval:service.timeout) setBasicAuthHeader(request) request.HTTPMethod = "DELETE" performRequest(request) { self.executing = false self.finished = true } } }
epl-1.0
d72e5110dbbeecb96a0abe4ad83fa005
31.431034
139
0.680851
4.585366
false
false
false
false
PGSSoft/AutoMate
AutoMate/PageObjects/HealthPermissionPage.swift
1
4073
// // HealthPermissionPage.swift // AutoMate // // Created by Bartosz Janda on 15.02.2017. // Copyright © 2017 PGS Software. All rights reserved. // import Foundation import XCTest // MARK: - HealthPermissionPage #if os(iOS) /// Page object representing HealthKit permission view. /// /// It can only allow to tap on buttons: /// /// - Allow /// - Deny /// - Turn on all permissions /// - Turn off all permissions /// /// **Example:** /// /// ```swift /// let healthPermissionPage = HealthPermissionPage(in: self.app) /// healthPermissionPage.turnOnAllElement.tap() /// healthPermissionPage.allowElement.tap() /// ``` open class HealthPermissionPage: BaseAppPage, HealthAlertAllow, HealthAlertDeny, HealthAlertTurnOnAll, HealthAlertTurnOffAll { // MARK: Elements /// Navigation bar on HealthKit permission view. /// /// This bar can be used to identify if the permission view is visible. open var healthAccessElement: XCUIElement { return view.navigationBars[Locators.healthAccess] } } // MARK: - IdentifiableByElement extension HealthPermissionPage: IdentifiableByElement { /// Identifing `XCUIElement`. /// /// The `healthAccessElement` is used. public var identifingElement: XCUIElement { return healthAccessElement } } // MARK: - Locators public extension HealthPermissionPage { /// Locators used in the HealthKit permission view. /// /// - `healthAccess`: Navigation bar identifier. enum Locators: String, Locator { /// Navigation bar identifier. case healthAccess = "Health Access" } } // MARK: - Health protocols /// Protocol defining health alert allow element and messages. public protocol HealthAlertAllow: SystemMessages { /// Allow messages. static var allow: [String] { get } /// Allow element. var allowElement: XCUIElement { get } } /// Protocol defining health alert deny element and messages. public protocol HealthAlertDeny: SystemMessages { /// Deny messages. static var deny: [String] { get } /// Deny element. var denyElement: XCUIElement { get } } /// Protocol defining health alert "turn on all" element and messages. public protocol HealthAlertTurnOnAll: SystemMessages { /// Turn On All messages. static var turnOnAll: [String] { get } /// Turn On All element. var turnOnAllElement: XCUIElement { get } } /// Protocol defining health alert "turn off all" element and messages. public protocol HealthAlertTurnOffAll: SystemMessages { /// Turn Off All messages. static var turnOffAll: [String] { get } /// Turn Off All element. var turnOffAllElement: XCUIElement { get } } // MARK: - Default implementation extension HealthAlertAllow where Self: BaseAppPage { /// Allow element. public var allowElement: XCUIElement { guard let button = view.buttons.elements(withLabelsMatching: type(of: self).allow).first else { preconditionFailure("Cannot find allow button.") } return button } } extension HealthAlertDeny where Self: BaseAppPage { /// Deny element. public var denyElement: XCUIElement { guard let button = view.buttons.elements(withLabelsMatching: type(of: self).deny).first else { preconditionFailure("Cannot find deny button.") } return button } } extension HealthAlertTurnOnAll where Self: BaseAppPage { /// Turn On All element. public var turnOnAllElement: XCUIElement { guard let button = view.staticTexts.elements(withLabelsMatching: type(of: self).turnOnAll).first else { preconditionFailure("Cannot find turn on all button.") } return button } } extension HealthAlertTurnOffAll where Self: BaseAppPage { /// Turn Off All element. public var turnOffAllElement: XCUIElement { guard let button = view.staticTexts.elements(withLabelsMatching: type(of: self).turnOffAll).first else { preconditionFailure("Cannot find turn off all button.") } return button } } #endif
mit
8a3ba2b016be43480d98aedab109efb4
27.879433
126
0.687377
4.373792
false
false
false
false
dduan/swift
stdlib/public/Platform/Platform.swift
1
10894
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public var noErr: OSStatus { return 0 } /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. public struct DarwinBoolean : Boolean, BooleanLiteralConvertible { var _value: UInt8 public init(_ value: Bool) { self._value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { return _value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension DarwinBoolean : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension DarwinBoolean : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension DarwinBoolean : Equatable {} @warn_unused_result public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool { return lhs.boolValue == rhs.boolValue } @warn_unused_result public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } @warn_unused_result public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(x: DarwinBoolean) -> Bool { return Bool(x) } // FIXME: We can't make the fully-generic versions @_transparent due to // rdar://problem/19418937, so here are some @_transparent overloads // for DarwinBoolean. @_transparent @warn_unused_result public func && <T : Boolean>( lhs: T, @autoclosure rhs: () -> DarwinBoolean ) -> Bool { return lhs.boolValue ? rhs().boolValue : false } @_transparent @warn_unused_result public func || <T : Boolean>( lhs: T, @autoclosure rhs: () -> DarwinBoolean ) -> Bool { return lhs.boolValue ? true : rhs().boolValue } #endif //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// public var errno : Int32 { get { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) return __error().pointee #else return __errno_location().pointee #endif } set(val) { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) return __error().pointee = val #else return __errno_location().pointee = val #endif } } //===----------------------------------------------------------------------===// // stdio.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) public var stdin : UnsafeMutablePointer<FILE> { get { return __stdinp } set { __stdinp = newValue } } public var stdout : UnsafeMutablePointer<FILE> { get { return __stdoutp } set { __stdoutp = newValue } } public var stderr : UnsafeMutablePointer<FILE> { get { return __stderrp } set { __stderrp = newValue } } #endif //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("_swift_Platform_open") func _swift_Platform_open( path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt @warn_unused_result @_silgen_name("_swift_Platform_openat") func _swift_Platform_openat(fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt @warn_unused_result public func open( path: UnsafePointer<CChar>, _ oflag: CInt ) -> CInt { return _swift_Platform_open(path, oflag, 0) } @warn_unused_result public func open( path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt { return _swift_Platform_open(path, oflag, mode) } @warn_unused_result public func openat( fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt ) -> CInt { return _swift_Platform_openat(fd, path, oflag, 0) } @warn_unused_result public func openat( fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt { return _swift_Platform_openat(fd, path, oflag, mode) } @warn_unused_result @_silgen_name("_swift_Platform_fcntl") internal func _swift_Platform_fcntl( fd: CInt, _ cmd: CInt, _ value: CInt ) -> CInt @warn_unused_result @_silgen_name("_swift_Platform_fcntlPtr") internal func _swift_Platform_fcntlPtr( fd: CInt, _ cmd: CInt, _ ptr: UnsafeMutablePointer<Void> ) -> CInt @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt ) -> CInt { return _swift_Platform_fcntl(fd, cmd, 0) } @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt, _ value: CInt ) -> CInt { return _swift_Platform_fcntl(fd, cmd, value) } @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt, _ ptr: UnsafeMutablePointer<Void> ) -> CInt { return _swift_Platform_fcntlPtr(fd, cmd, ptr) } public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var S_IFWHT: mode_t { return mode_t(0o160000) } #endif public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var S_ISTXT: mode_t { return S_ISVTX } public var S_IREAD: mode_t { return S_IRUSR } public var S_IWRITE: mode_t { return S_IWUSR } public var S_IEXEC: mode_t { return S_IXUSR } #endif //===----------------------------------------------------------------------===// // unistd.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func fork() -> Int32 { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func vfork() -> Int32 { fatalError("unavailable function can't be called") } #endif //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) } #elseif os(Linux) || os(FreeBSD) public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #else internal var _ignore = _UnsupportedPlatformError() #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: UnsafeMutablePointer<sem_t> { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) // The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS. return UnsafeMutablePointer<sem_t>(bitPattern: -1) #elseif os(Linux) || os(FreeBSD) // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) #else _UnsupportedPlatformError() #endif } @warn_unused_result @_silgen_name("_swift_Platform_sem_open2") internal func _swift_Platform_sem_open2( name: UnsafePointer<CChar>, _ oflag: CInt ) -> UnsafeMutablePointer<sem_t> @warn_unused_result @_silgen_name("_swift_Platform_sem_open4") internal func _swift_Platform_sem_open4( name: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t> @warn_unused_result public func sem_open( name: UnsafePointer<CChar>, _ oflag: CInt ) -> UnsafeMutablePointer<sem_t> { return _swift_Platform_sem_open2(name, oflag) } @warn_unused_result public func sem_open( name: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t> { return _swift_Platform_sem_open4(name, oflag, mode, value) } //===----------------------------------------------------------------------===// // Misc. //===----------------------------------------------------------------------===// // FreeBSD defines extern char **environ differently than Linux. #if os(FreeBSD) @warn_unused_result @_silgen_name("_swift_FreeBSD_getEnv") func _swift_FreeBSD_getEnv( ) -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>>> public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>> { return _swift_FreeBSD_getEnv().pointee } #endif
apache-2.0
2aa9f1332ac519bb42f5692d84b24fbe
26.440806
82
0.593079
3.542764
false
false
false
false
lstn-ltd/lstn-sdk-ios
Example/Tests/Example.swift
1
1560
// // Example.swift // Lstn // // Created by Dan Halliday on 18/10/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import Lstn class Example { let player = Lstn.createPlayer() let article = "12345-an-article-id" let publisher = "12345-a-publisher-id" var loading = false var playing = false var progress = 0.0 var error = false init() { self.player.delegate = self } func loadButtonWasTapped() { self.player.load(article: self.article, publisher: self.publisher) } func playButtonWasTapped() { self.player.play() } func stopButtonWasTapped() { self.player.stop() } } extension Example: PlayerDelegate { func loadingDidStart() { self.loading = true self.error = false } func loadingDidFinish() { self.loading = false } func loadingDidFail() { self.loading = false self.error = true } func playbackDidStart() { self.playing = true self.error = false } func playbackDidProgress(amount: Double) { self.progress = amount } func playbackDidStop() { self.playing = false } func playbackDidFinish() { self.playing = false } func playbackDidFail() { self.playing = false self.error = true } func requestPreviousItem() { // Playlist implementation omitted for brevity } func requestNextItem() { // Playlist implementation omitted for brevity } }
mit
adfd546671be5bf5c6fcd7395e8dc7f3
16.91954
74
0.592046
4.124339
false
false
false
false
pinchih/PCLSlideInMenu
PCLSlideInMenu/PCLSlideInMenu.swift
1
6380
// // PCLSlideInMenu.swift // PCLSlideInMenu // // Created by Pin-Chih on 8/6/16. // Copyright © 2016 Pin-Chih. All rights reserved. // import UIKit public protocol PCLSlideInMenuDataSource{ func menuItemAt(Index:Int) -> MenuItemInfo func menuItemCount() -> Int func menuItemSpacing() -> CGFloat } @objc protocol PCLSlideInMenuDelegate{ @objc optional func menuItemClickedAt(Index:Int) } public struct MenuItemInfo { var iconImage : UIImage var iconWidthAndHeight : CGFloat var backgroundColor : UIColor } extension Int { var degreesToRadians: CGFloat { return CGFloat(Double(self) * M_PI / 180) } var radiansToDegrees: CGFloat { return CGFloat(Double(self) * 180 / M_PI) } } enum animationType { case slideIn case rotate } class PCLSlideInMenu: NSObject { let backView = UIView() var dataSource : PCLSlideInMenuDataSource?{ didSet{ itemCount = dataSource!.menuItemCount() spacing = dataSource!.menuItemSpacing() } } var delegate : PCLSlideInMenuDelegate? var itemCount : Int = 0 var spacing : CGFloat = 0.0 var viewArr : [UIImageView] = [] let offSetInX : CGFloat = 80.0 let offSetInY : CGFloat = 60.0 var animation : animationType = .slideIn override init() { super.init() backgroundViewSetup() } // MARK : - View setup func backgroundViewSetup(){ backView.backgroundColor = UIColor.init(white: 0, alpha: 0.3) backView.alpha = 0 backView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissView))) } func setupMenu(_ info:MenuItemInfo,window:UIWindow,Index:Int) -> UIImageView{ let view = UIImageView() view.image = info.iconImage if Index == 0{ view.frame = CGRect(x: window.frame.width, y: window.frame.height - self.offSetInX,width: info.iconWidthAndHeight, height: info.iconWidthAndHeight) }else{ view.frame = CGRect(x: window.frame.width, y: window.frame.height - self.offSetInX - spacing*CGFloat(Index),width: info.iconWidthAndHeight, height: info.iconWidthAndHeight) } view.layer.masksToBounds = true view.layer.cornerRadius = view.frame.width/2 view.backgroundColor = info.backgroundColor view.isUserInteractionEnabled = true view.tag = Index view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(menuItemClicked))) return view } // MARK : - Animation func showMenu(){ if let window = UIApplication.shared.keyWindow{ backView.frame = window.frame if viewArr.count == 0{ window.addSubview(backView) for i in 0..<itemCount{ let menuItem = dataSource!.menuItemAt(Index: i) let viewToAdd = setupMenu(menuItem, window: window,Index: i) viewArr.append(viewToAdd) window.addSubview(viewToAdd) } } // Show background View UIView.animate(withDuration: 0.5, animations: { self.backView.alpha = 1 }, completion: nil) // Show menu items animateRecursive(0) } } func animateRecursive(_ Index:Int){ if Index == self.viewArr.count { return }else{ UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { let view = self.viewArr[Index] switch self.animation{ case .slideIn: view.frame = CGRect(x: view.frame.origin.x - self.offSetInX, y: view.frame.origin.y,width: view.frame.width, height: view.frame.height) break case .rotate: view.frame = CGRect(x: view.frame.origin.x - self.offSetInX, y: view.frame.origin.y,width: view.frame.width, height: view.frame.height) view.transform = CGAffineTransform(rotationAngle: 270.degreesToRadians) break } }, completion: { (finished) in if finished{ return self.animateRecursive(Index+1) } }) } } func menuItemClicked(_ sender:UITapGestureRecognizer){ guard let userDelegate = self.delegate?.menuItemClickedAt else{ fatalError("Delegate method menuItemClickedAt(Index:Int) is not implemented") } let imgView = sender.view as! UIImageView userDelegate(imgView.tag) dismissView() } func dismissView(){ UIView.animate(withDuration: 0.3, animations: { self.backView.alpha = 0 for i in 0..<self.viewArr.count{ let view = self.viewArr[i] switch self.animation{ case .slideIn: view.frame = CGRect(x: view.frame.origin.x + self.offSetInX, y: view.frame.origin.y, width: view.frame.width, height: view.frame.height) break case .rotate: view.frame = CGRect(x: view.frame.origin.x + self.offSetInX, y: view.frame.origin.y, width: view.frame.width, height: view.frame.height) //view.transform = CGAffineTransformMakeRotation(180.degreesToRadians) view.transform = CGAffineTransform.identity break } } }) } }
mit
a82daef88965bbc02673da068a5a2474
28.261468
184
0.525631
5.074781
false
false
false
false
joostholslag/BNRiOS
iOSProgramming6ed/24 - Accessibility/Solutions/Photorama/Photorama/CoreDataStack.swift
1
2877
// // Copyright © 2015 Big Nerd Ranch // import Foundation import CoreData class CoreDataStack { let managedObjectModelName: String private lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource(self.managedObjectModelName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() private var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls.first! }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { var coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let pathComponent = "\(self.managedObjectModelName).sqlite" let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(pathComponent) let store = try! coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) return coordinator }() lazy var mainQueueContext: NSManagedObjectContext = { let moc = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) moc.persistentStoreCoordinator = self.persistentStoreCoordinator moc.name = "Main Queue Context (UI Context)" return moc }() lazy var privateQueueContext: NSManagedObjectContext = { let moc = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) moc.parentContext = self.mainQueueContext moc.name = "Primary Private Queue Context" return moc }() required init(modelName: String) { managedObjectModelName = modelName } func saveChanges() throws { var error: ErrorType? privateQueueContext.performBlockAndWait { () -> Void in if self.privateQueueContext.hasChanges { do { try self.privateQueueContext.save() } catch let saveError { error = saveError } } } if let error = error { throw error } mainQueueContext.performBlockAndWait { () -> Void in if self.mainQueueContext.hasChanges { do { try self.mainQueueContext.save() } catch let saveError { error = saveError } } } if let error = error { throw error } } }
gpl-3.0
37b8139728962aa76eeccee1ce075112
28.346939
87
0.576495
6.672854
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCombineSwift/Sources/Auth/Auth+Combine.swift
1
26624
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if canImport(Combine) && swift(>=5.0) import Combine import FirebaseAuth // Make this class discoverable from Objective-C. Don't instantiate directly. @objc(FIRCombineAuthLibrary) private class __CombineAuthLibrary: NSObject {} @available(swift 5.0) @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, *) public extension Auth { // MARK: - Authentication State Management /// Registers a publisher that publishes authentication state changes. /// /// The publisher emits values when: /// /// - It is registered, /// - a user with a different UID from the current user has signed in, or /// - the current user has signed out. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher emitting a `User` instance (if the user has signed in) or `nil` (if the user has signed out). /// The publisher will emit on the *main* thread. func authStateDidChangePublisher() -> AnyPublisher<User?, Never> { let subject = PassthroughSubject<User?, Never>() let handle = addStateDidChangeListener { auth, user in subject.send(user) } return subject .handleEvents(receiveCancel: { self.removeStateDidChangeListener(handle) }) .eraseToAnyPublisher() } /// Registers a publisher that publishes ID token state changes. /// /// The publisher emits values when: /// /// - It is registered, /// - a user with a different UID from the current user has signed in, /// - the ID token of the current user has been refreshed, or /// - the current user has signed out. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher emitting a `User` instance (if a different user is signed in or /// the ID token of the current user has changed) or `nil` (if the user has signed out). /// The publisher will emit on the *main* thread. func idTokenDidChangePublisher() -> AnyPublisher<User?, Never> { let subject = PassthroughSubject<User?, Never>() let handle = addIDTokenDidChangeListener { auth, user in subject.send(user) } return subject .handleEvents(receiveCancel: { self.removeIDTokenDidChangeListener(handle) }) .eraseToAnyPublisher() } /// Sets the `currentUser` on the calling Auth instance to the provided `user` object. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter user: The user object to be set as the current user of the calling Auth instance. /// - Returns: A publisher that emits when the user of the calling Auth instance has been updated or /// an error was encountered. The publisher will emit on the **main** thread. @discardableResult func updateCurrentUser(_ user: User) -> Future<Void, Error> { Future<Void, Error> { promise in self.updateCurrentUser(user) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } // MARK: - Anonymous Authentication /// Asynchronously creates an anonymous user and assigns it as the calling Auth instance's current user. /// /// If there is already an anonymous user signed in, that user will be returned instead. /// If there is any other existing user signed in, that user will be signed out. /// /// The publisher will emit events on the **main** thread. /// /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are /// not enabled. Enable them in the Auth section of the Firebase console. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func signInAnonymously() -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signInAnonymously { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } // MARK: - Email/Password Authentication /// Creates and, on success, signs in a user with the given email address and password. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - email: The user's email address. /// - password: The user's desired password. /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed. /// - `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up /// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user /// used, and prompt the user to sign in with one of those. /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts /// are not enabled. Enable them in the Auth section of the Firebase console. /// - `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is /// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo /// dictionary object will contain more detailed explanation that can be shown to the user. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func createUser(withEmail email: String, password: String) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.createUser(withEmail: email, password: password) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } /// Signs in a user with the given email address and password. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - email: The user's email address. /// - password: The user's password. /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password /// accounts are not enabled. Enable them in the Auth section of the /// Firebase console. /// - `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `AuthErrorCodeWrongPassword` - Indicates the user attempted /// sign in with an incorrect password. /// - `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func signIn(withEmail email: String, password: String) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signIn(withEmail: email, password: password) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } // MARK: - Email/Link Authentication /// Signs in using an email address and email sign-in link. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - email: The user's email address. /// - link: The email sign-in link. /// - Returns: A publisher that emits the result of the sign in flow. The publisher will emit on the *main* thread. /// - Remark: /// Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password /// accounts are not enabled. Enable them in the Auth section of the /// Firebase console. /// - `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @available(watchOS, unavailable) @discardableResult func signIn(withEmail email: String, link: String) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signIn(withEmail: email, link: link) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } /// Sends a sign in with email link to provided email address. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - email: The email address of the user. /// - actionCodeSettings: An `ActionCodeSettings` object containing settings related to /// handling action codes. /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. @available(watchOS, unavailable) @discardableResult func sendSignInLink(toEmail email: String, actionCodeSettings: ActionCodeSettings) -> Future<Void, Error> { Future<Void, Error> { promise in self.sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } // MARK: - Email-based Authentication Helpers /// Fetches the list of all sign-in methods previously used for the provided email address. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter email: The email address for which to obtain a list of sign-in methods. /// - Returns: A publisher that emits a list of sign-in methods for the specified email /// address, or an error if one occurred. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed. /// /// See `AuthErrors` for a list of error codes that are common to all API methods func fetchSignInMethods(forEmail email: String) -> Future<[String], Error> { Future<[String], Error> { promise in self.fetchSignInMethods(forEmail: email) { signInMethods, error in if let error = error { promise(.failure(error)) } else if let signInMethods = signInMethods { promise(.success(signInMethods)) } } } } // MARK: - Password Reset /// Resets the password given a code sent to the user outside of the app and a new password for the user. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - code: Out-of-band (OOB) code given to the user outside of the app. /// - newPassword: The new password. /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is considered too weak. /// - `AuthErrorCodeOperationNotAllowed` - Indicates the admin disabled sign in with the specified identity provider. /// - `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired. /// - `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func confirmPasswordReset(withCode code: String, newPassword: String) -> Future<Void, Error> { Future<Void, Error> { promise in self.confirmPasswordReset(withCode: code, newPassword: newPassword) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } /// Checks the validity of a verify password reset code. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The password reset code to be verified. /// - Returns: A publisher that emits an error if the code could not be verified. If the code could be /// verified, the publisher will emit the email address of the account the code was issued for. /// The publisher will emit on the *main* thread. @discardableResult func verifyPasswordResetCode(_ code: String) -> Future<String, Error> { Future<String, Error> { promise in self.verifyPasswordResetCode(code) { email, error in if let error = error { promise(.failure(error)) } else if let email = email { promise(.success(email)) } } } } /// Checks the validity of an out of band code. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The out of band code to check validity. /// - Returns: A publisher that emits the email address of the account the code was issued for or an error if /// the code could not be verified. The publisher will emit on the *main* thread. @discardableResult func checkActionCode(code: String) -> Future<ActionCodeInfo, Error> { Future<ActionCodeInfo, Error> { promise in self.checkActionCode(code) { actionCodeInfo, error in if let error = error { promise(.failure(error)) } else if let actionCodeInfo = actionCodeInfo { promise(.success(actionCodeInfo)) } } } } /// Applies out of band code. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter code: The out-of-band (OOB) code to be applied. /// - Returns: A publisher that emits an error if the code could not be applied. The publisher will emit on the *main* thread. /// - Remark: This method will not work for out-of-band codes which require an additional parameter, /// such as password reset codes. @discardableResult func applyActionCode(code: String) -> Future<Void, Error> { Future<Void, Error> { promise in self.applyActionCode(code) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } /// Initiates a password reset for the given email address. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter email: The email address of the user. /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in the request. /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console for this action. /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending update email. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func sendPasswordReset(withEmail email: String) -> Future<Void, Error> { Future<Void, Error> { promise in self.sendPasswordReset(withEmail: email) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } /// Initiates a password reset for the given email address and `ActionCodeSettings`. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter email: The email address of the user. /// - Parameter actionCodeSettings: An `ActionCodeSettings` object containing settings related to /// handling action codes. /// - Returns: A publisher that emits whether the call was successful or not. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeInvalidRecipientEmail` - Indicates an invalid recipient email was sent in the request. /// - `AuthErrorCodeInvalidSender` - Indicates an invalid sender email is set in the console for this action. /// - `AuthErrorCodeInvalidMessagePayload` - Indicates an invalid email template for sending update email. /// - `AuthErrorCodeMissingIosBundleID` - Indicates that the iOS bundle ID is missing /// when `handleCodeInApp` is set to YES. /// - `AuthErrorCodeMissingAndroidPackageName` - Indicates that the android package name is missing /// when the `androidInstallApp` flag is set to true. /// - `AuthErrorCodeUnauthorizedDomain` - Indicates that the domain specified in the continue URL is not whitelisted /// in the Firebase console. /// - `AuthErrorCodeInvalidContinueURI` - Indicates that the domain specified in the continue URI is not valid. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func sendPasswordReset(withEmail email: String, actionCodeSettings: ActionCodeSettings) -> Future<Void, Error> { Future<Void, Error> { promise in self.sendPasswordReset(withEmail: email, actionCodeSettings: actionCodeSettings) { error in if let error = error { promise(.failure(error)) } else { promise(.success(())) } } } } // MARK: - Other Authentication providers #if os(iOS) || targetEnvironment(macCatalyst) /// Signs in using the provided auth provider instance. /// /// The publisher will emit events on the **main** thread. /// /// - Parameters: /// - provider: An instance of an auth provider used to initiate the sign-in flow. /// - uiDelegate: Optionally, an instance of a class conforming to the `AuthUIDelegate` /// protocol. This is used for presenting the web context. If `nil`, a default `AuthUIDelegate` /// will be used. /// - Returns: A publisher that emits an `AuthDataResult` when the sign-in flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts are not enabled. /// Enable them in the Auth section of the Firebase console. /// - `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a /// `SFSafariViewController` or `WKWebView` failed. /// - `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a /// `SFSafariViewController` or `WKWebView`.` /// - `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during a web sign-in flow.` /// - `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to present a new web /// context while one was already being presented.` /// - `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was cancelled prematurely /// by the user.` /// - `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted by the credential /// (e.g. the email in a Facebook access token) is already in use by an existing account that cannot be /// authenticated with this sign-in method. Call `fetchProvidersForEmail` for this user’s email and then /// prompt them to sign in with any of the sign-in providers returned. This error will only be thrown if /// the "One account per email address" setting is enabled in the Firebase console, under Auth settings. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func signIn(with provider: FederatedAuthProvider, uiDelegate: AuthUIDelegate?) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signIn(with: provider, uiDelegate: uiDelegate) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } #endif // os(iOS) || targetEnvironment(macCatalyst) /// Asynchronously signs in to Firebase with the given Auth token. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter token: A self-signed custom auth token. /// - Returns: A publisher that emits an `AuthDataResult` when the sign-in flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `AuthErrorCodeInvalidCustomToken` - Indicates a validation error with the custom token. /// - `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `AuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key /// belong to different projects. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func signIn(withCustomToken token: String) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signIn(withCustomToken: token) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } /// Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook /// login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional /// identity provider data. /// /// The publisher will emit events on the **main** thread. /// /// - Parameter credential: The credential supplied by the IdP. /// - Returns: A publisher that emits an `AuthDataResult` when the sign-in flow completed /// successfully, or an error otherwise. The publisher will emit on the *main* thread. /// - Remark: Possible error codes: /// - `FIRAuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid. /// This could happen if it has expired or it is malformed. /// - `FIRAuthErrorCodeOperationNotAllowed` - Indicates that accounts /// with the identity provider represented by the credential are not enabled. /// Enable them in the Auth section of the Firebase console. /// - `FIRAuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted /// by the credential (e.g. the email in a Facebook access token) is already in use by an /// existing account, that cannot be authenticated with this sign-in method. Call /// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of /// the sign-in providers returned. This error will only be thrown if the "One account per /// email address" setting is enabled in the Firebase console, under Auth settings. /// - `FIRAuthErrorCodeUserDisabled` - Indicates the user's account is disabled. /// - `FIRAuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an /// incorrect password, if credential is of the type EmailPasswordAuthCredential. /// - `FIRAuthErrorCodeInvalidEmail` - Indicates the email address is malformed. /// - `FIRAuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was /// created with an empty verification ID. /// - `FIRAuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential /// was created with an empty verification code. /// - `FIRAuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential /// was created with an invalid verification Code. /// - `FIRAuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was /// created with an invalid verification ID. /// - `FIRAuthErrorCodeSessionExpired` - Indicates that the SMS code has expired. /// /// See `AuthErrors` for a list of error codes that are common to all API methods @discardableResult func signIn(with credential: AuthCredential) -> Future<AuthDataResult, Error> { Future<AuthDataResult, Error> { promise in self.signIn(with: credential) { authDataResult, error in if let error = error { promise(.failure(error)) } else if let authDataResult = authDataResult { promise(.success(authDataResult)) } } } } } #endif // canImport(Combine) && swift(>=5.0)
apache-2.0
57199d5fce5feaac3f0b35cb003072a7
46.620751
130
0.64876
4.66118
false
false
false
false
mennovf/Swift-MathEagle
MathEagleTests/ComplexTests.swift
1
3912
// // ComplexTests.swift // MathEagle // // Created by Rugen Heidbuchel on 06/03/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Cocoa import XCTest import MathEagle class ComplexTests: XCTestCase { let ACCURACY = 10.0 ** -7 // MARK: General Test func testGeneralComplexMath() { let i = Complex.imaginaryUnit let x = -3.0 + 4.5*i let y = -5.0 + 2.8*i let z = 1.0 + 2.0*i print("\n\n\n", appendNewline: false) print("x = \(x)") print("y = \(y)") print("z = \(z)") print("x + y = \(x+y)") print("x * y = \(x*y)") print("e^z = \(exp(z))") print("sqrt(z) = \(sqrt(z))") print("\n\n\n", appendNewline: false) } // MARK: Init Tests func testRealImaginaryInit() { var z = Complex(1, 2) XCTAssertEqual(1, z.real) XCTAssertEqual(2, z.imaginary) z = Complex(-2.3, 23.56) XCTAssertEqual(-2.3, z.real) XCTAssertEqual(23.56, z.imaginary) } func testModulusArgumentInit() { let z = Complex(modulus: 2.0, argument: PI/2) XCTAssertEqualWithAccuracy(0, z.real, accuracy: ACCURACY) XCTAssertEqualWithAccuracy(2, z.imaginary, accuracy: ACCURACY) } // func testIntegerLiteralInit() { // // var z: Complex = 2 // XCTAssertEqual(2, z.real) // XCTAssertEqual(0, z.imaginary) // } // MARK: Basic Properties Tests func testModulusAndArgument() { var z = Complex(1, 2) XCTAssertEqualWithAccuracy(sqrt(5), z.modulus, accuracy: ACCURACY) XCTAssertEqualWithAccuracy(atan(2), z.argument, accuracy: ACCURACY) z = Complex(-2, -2) XCTAssertEqualWithAccuracy(sqrt(8), z.modulus, accuracy: ACCURACY) XCTAssertEqualWithAccuracy(5*PI/4, z.argument, accuracy: ACCURACY) } func testQuadrant() { var z = Complex(1, 2) XCTAssertEqual(Quadrant.First, z.quadrant) z = Complex(-1, 2) XCTAssertEqual(Quadrant.Second, z.quadrant) z = Complex(-1, -2) XCTAssertEqual(Quadrant.Third, z.quadrant) z = Complex(1, -2) XCTAssertEqual(Quadrant.Fourth, z.quadrant) } // MARK: Function Extension Tests func testExp() { let z = exp(Complex(1, 2)) XCTAssertEqualWithAccuracy(exp(1) * cos(2), z.real, accuracy: ACCURACY) XCTAssertEqualWithAccuracy(exp(1) * sin(2), z.imaginary, accuracy: ACCURACY) } // MARK: Test Operations func testEquality() { let z = Complex(1, 2) XCTAssertEqual(Complex(1, 2), z) } func testComparability() { let z = Complex(1, 2) let x = Complex(3, -5) XCTAssertTrue(z < x) XCTAssertTrue(x > z) XCTAssertFalse(z > z) } func testAddition() { let z = Complex(1, 2) let x = Complex(-1, 3.4) XCTAssertEqual(Complex(0, 5.4), z + x) } func testSubstracion() { let z = Complex(1, 2) let x = Complex(-1, 3.4) XCTAssertEqual(Complex(2, -1.4), z - x) } func testMultiplication() { let z = Complex(1, 2) let x = Complex(-1, 3.4) XCTAssertEqual(Complex(-7.8, 1.4), z * x) XCTAssertEqual(Complex(-7.8, 1.4), x * z) } func testDivision() { let z = Complex(1, 2) let x = Complex(-1, 3.4) XCTAssertTrue(Complex(5.8/12.56, -5.4/12.56).equals(z / x, accuracy: ACCURACY)) } }
mit
0b6100636176aa823773dfd08e8c30c2
21.482759
87
0.503579
3.951515
false
true
false
false
sinhdev/ios
TouchEventDemo/TouchEventDemo/TouchGestureRecognizerViewController.swift
1
1824
// // TouchGestureRecognizerViewController.swift // TouchEventDemo // // Created by Sinh NX on 8/17/17. // Copyright © 2017 Sinh NX. All rights reserved. // import UIKit class TouchGestureRecognizerViewController: UIViewController { @IBOutlet weak var imgCover: UIImageView! @IBOutlet weak var lblPosition: UILabel! @IBOutlet weak var lblTouch: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imgTransform = imgCover.transform self.view.isUserInteractionEnabled = true self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapEvent))) self.view.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(pinchGuestureAction))) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pinchGuestureAction(_ sender: UIPinchGestureRecognizer) { if sender.state == .began || sender.state == .changed { imgCover.transform = imgCover.transform.scaledBy(x: sender.scale, y: sender.scale) } else if sender.state == .ended { imgCover.transform = imgTransform! } } private var imgTransform:CGAffineTransform? func tapEvent(_ sender: UITapGestureRecognizer) { tapCount += 1 } private var tapCount:Int = 1 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { lblTouch.text = "Tap Count: \(tapCount)" let t = touches.first t?.location(in: lblTouch) lblPosition.text = "x = \(t?.location(in: lblTouch).x ?? 0), y = \(t?.location(in: lblTouch).y ?? 0)" } }
mit
5989034dc3661a7ff71363a5a66ad59b
36.204082
118
0.664838
4.468137
false
false
false
false
blitzagency/amigo-swift
Amigo/SQLiteBatchOperation.swift
1
9729
// // SQLiteBatchOperation.swift // Amigo // // Created by Adam Venturella on 1/14/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation public class SQLiteBatchOperation: AmigoBatchOperation{ let session: AmigoSession var insertCache = [String: [String]]() var upsertCache = [String: [String]]() var updateCache = [String: [String]]() var deleteCache = [String: [String]]() var deleteThroughCache = [String: [String]]() var insertThroughCache = [String: [String]]() var upsertThroughCache = [String: [String]]() var statements = "" public required init(session: AmigoSession){ self.session = session } public func add<T: AmigoModel>(obj: T) { add(obj, upsert: false) } public func add<T: AmigoModel>(obj: [T]) { obj.forEach{ add($0, upsert: false) } } public func add<T: AmigoModel>(obj: [T], upsert isUpsert: Bool = false) { obj.forEach{ add($0, upsert: isUpsert) } } public func add<T: AmigoModel>(obj: T, upsert isUpsert: Bool = false) { let action = session.addAction(obj) let model = obj.amigoModel if action == .Insert || isUpsert { if let relationship = model.throughModelRelationship{ addThroughModel(obj, relationship: relationship, upsert: isUpsert) } else { statements = statements + buildInsert(obj, upsert: isUpsert) + "\n" } } else { // deny an update for a model without a primary key guard let _ = obj.amigoModel.primaryKey.modelValue(obj) else { return } statements = statements + buildUpdate(obj) + "\n" } } public func addThroughModel<T: AmigoModel>(obj: T, relationship: ManyToMany, upsert isUpsert: Bool = false){ let model = obj.amigoModel let left = relationship.left let right = relationship.right var leftKey: String! var rightKey: String! model.foreignKeys.forEach{ (key: String, c: Column) -> Void in guard let fk = c.foreignKey else { return } if fk.relatedColumn == left.primaryKey{ leftKey = key } if fk.relatedColumn == right.primaryKey{ rightKey = key } } // this will save the 2 foreign keys as well. // if we have to do this then the associationTable // will get it's inserts as well. This effectively // defeats the batching, but such is life, we don't have // enough info to proceed so we have to do it. // // Batching with ThoughModels is only effective if // you have all the keys. For example if you are // syncing with a remote server and that server is // providing you all of the primary keys for the // models involved. if model.primaryKey.modelValue(obj) == nil{ session.add(obj, upsert: isUpsert) return } if obj.valueForKeyPath("\(leftKey).\(left.primaryKey!.label)") == nil{ if let leftModel = obj.valueForKeyPath("\(leftKey)") as? AmigoModel { session.add(leftModel, upsert: isUpsert) } } if obj.valueForKeyPath("\(rightKey).\(right.primaryKey!.label)") == nil{ if let rightModel = obj.valueForKeyPath("\(rightKey)") as? AmigoModel { session.add(rightModel, upsert: isUpsert) } } // if we don't have these parms, we don't proceed guard let leftParam = left.primaryKey!.serialize(obj.valueForKeyPath("\(leftKey).\(left.primaryKey!.label)")), let rightParam = right.primaryKey!.serialize(obj.valueForKeyPath("\(rightKey).\(right.primaryKey!.label)")), let throughParam = model.primaryKey!.serialize(model.primaryKey.modelValue(obj)) else { return } // insert the ThroughModel statements = statements + buildInsert(obj, upsert: isUpsert) + "\n" let params = [leftParam, rightParam, throughParam] let sql = buildInsertThough(obj, relationship: relationship, params: params, upsert: false) // insert the data into the proper association table statements = statements + sql + "\n" } public func delete<T: AmigoModel>(obj: [T]){ obj.forEach(delete) } public func delete<T: AmigoModel>(obj: T){ // deny an delete for a model without a primary key guard let _ = obj.amigoModel.primaryKey.modelValue(obj) else { return } statements = statements + buildDelete(obj) + "\n" deleteThroughModelRelationship(obj) } public func deleteThroughModelRelationship<T: AmigoModel>(obj: T){ let model = obj.amigoModel guard let relationship = model.throughModelRelationship, let value = model.primaryKey.modelValue(obj) else { return } statements = statements + buildDeleteThroughModel(obj, relationship: relationship, value: value) + "\n" } public func execute(){ session.engine.execute(statements) } func buildUpdate<T: AmigoModel>(obj: T) -> String { let model = obj.amigoModel let fragments: [String] let sqlParams = session.insertParams(obj) let params = sqlParams.queryParams + [model.primaryKey.modelValue(obj)!] if let parts = updateCache[obj.qualifiedName] { fragments = parts } else { let (sql, _) = session.updateSQL(obj) let parts = sql.componentsSeparatedByString("?") updateCache[obj.qualifiedName] = parts fragments = parts } let sql = buildSQL(fragments, params: params) return sql } func buildInsert<T: AmigoModel>(value: T, upsert isUpsert: Bool = false) -> String { let fragments: [String] let values = session.insertParams(value, upsert: isUpsert) var cache = isUpsert ? upsertCache : insertCache if let parts = cache[value.qualifiedName] { fragments = parts } else { let model = value.amigoModel let sql = isUpsert ? session.upsertSQL(model) : session.insertSQL(model) let parts = sql.componentsSeparatedByString("?") cache[value.qualifiedName] = parts if isUpsert{ upsertCache = cache } else { insertCache = cache } fragments = parts } let sql = buildSQL(fragments, params: values.queryParams) return sql } func buildInsertThough<T: AmigoModel>(obj: T, relationship: ManyToMany, params: [AnyObject], upsert isUpsert: Bool = false) -> String { let fragments: [String] var cache = isUpsert ? upsertThroughCache : insertThroughCache if let parts = cache[obj.qualifiedName] { fragments = parts } else { let sql: String = session.insertThroughModelSQL(obj, relationship: relationship, upsert: isUpsert) let parts = sql.componentsSeparatedByString("?") cache[obj.qualifiedName] = parts if isUpsert{ upsertThroughCache = cache } else { insertThroughCache = cache } fragments = parts } let sql = buildSQL(fragments, params: params) return sql } func buildDelete<T: AmigoModel>(obj: T) -> String { let model = obj.amigoModel let fragments: [String] let params = [model.primaryKey.serialize(model.primaryKey.modelValue(obj))!] if let parts = deleteCache[obj.qualifiedName] { fragments = parts } else { let (sql, _) = session.deleteSQL(obj) let parts = sql.componentsSeparatedByString("?") deleteCache[obj.qualifiedName] = parts fragments = parts } let sql = buildSQL(fragments, params: params) return sql } func buildDeleteThroughModel<T: AmigoModel>(obj: T, relationship: ManyToMany, value: AnyObject) -> String{ let model = obj.amigoModel let fragments: [String] let params = [model.primaryKey!.serialize(model.primaryKey.modelValue(obj))!] if let parts = deleteThroughCache[obj.qualifiedName] { fragments = parts } else { let (sql, _) = session.deleteThroughModelSQL(obj, relationship: relationship, value: value) let parts = sql.componentsSeparatedByString("?") deleteThroughCache[obj.qualifiedName] = parts fragments = parts } let sql = buildSQL(fragments, params: params) return sql } func buildSQL(queryFragments: [String], params: [AnyObject]) -> String{ var sql = "" let escaped = params.map(escape) escaped.enumerate().forEach{ index, part in sql = sql + queryFragments[index] + part } sql = sql + queryFragments.last! return sql } func escape(value: AnyObject) -> String{ if let string = value as? String { return SQLiteFormat.escapeWithQuotes(string) } if let _ = value as? NSNull{ let result = SQLiteFormat.escapeWithQuotes(nil) return result } if let data = value as? NSData { return SQLiteFormat.escapeBlob(data) } return SQLiteFormat.escapeWithoutQuotes(String(value)) } }
mit
ed597b04b67981b27ab0856de9e93b78
30.794118
139
0.587479
4.554307
false
false
false
false
jeanpimentel/HonourBridge
HonourBridge/HonourBridge/Honour/Library/Rules/Contains.swift
1
1159
// // StartsWith.swift // Honour // // Created by Jean Pimentel on 4/30/15. // Copyright (c) 2015 Honour. All rights reserved. // import Foundation public class Contains : Rule { private var value: String private var caseSensitive: Bool = true public init(value: String) { self.value = value; } public init(_ value: String) { self.value = value; } public init(value: String, caseSensitive: Bool) { self.value = value; self.caseSensitive = caseSensitive; } public init(_ value: String, caseSensitive: Bool) { self.value = value; self.caseSensitive = caseSensitive; } public override func validate(value: String) -> Bool { if count(self.value) == 0 { return true } return self.caseSensitive ? validateSensitive(value) : validateInsensitive(value) } func validateSensitive(value: String) -> Bool { return value.rangeOfString(self.value) != nil } func validateInsensitive(value: String) -> Bool { return value.lowercaseString.rangeOfString(self.value.lowercaseString) != nil } }
mit
e27c6c63ccb825962d6ce3dcfa570e35
21.745098
89
0.624676
4.276753
false
false
false
false
RayTao/CoreAnimation_Collection
CoreAnimation_Collection/CAMediaTimingFunction.swift
1
10914
// // CAMediaTimingFunction.swift // CoreAnimation_Collection // // Created by ray on 16/2/15. // Copyright © 2016年 ray. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class CAMediaTimingFunctionController: UIViewController { let colorView = UIView.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let colorLayer = CALayer() override func viewDidLoad() { super.viewDidLoad() self.colorLayer.frame = colorView.frame; self.colorLayer.position = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2); self.colorLayer.backgroundColor = UIColor.blue.cgColor; self.view.layer.addSublayer(self.colorLayer); colorView.backgroundColor = UIColor.red colorView.center = self.view.center self.view.addSubview(colorView) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //get the touch point let point = touches.first!.location(in: self.view); //otherwise (slowly) move the layer to new position CATransaction.begin() CATransaction.setAnimationDuration(2.0); CATransaction.setAnimationTimingFunction(CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)) self.colorLayer.position = point; CATransaction.commit(); UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseOut, animations: { () -> Void in self.colorView.center = point; }, completion: nil) } } class KeyFrameMediaTimingViewController: UIViewController { let layerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) let colorLayer = CALayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. layerView.backgroundColor = UIColor.white layerView.center = self.view.center self.view.addSubview(layerView) colorLayer.frame = CGRect(x: 50, y: 50, width: 100, height: 100) self.colorLayer.backgroundColor = UIColor.blue.cgColor; layerView.layer.addSublayer(colorLayer) let changeColorBtn = UIButton.init(frame: CGRect(x: layerView.bounds.width/2-60, y: layerView.bounds.maxY - 40, width: 120, height: 31)) changeColorBtn.addTarget(self, action: #selector(KeyFrameMediaTimingViewController.changeColor), for: .touchUpInside) changeColorBtn.layer.borderColor = UIColor.darkGray.cgColor changeColorBtn.layer.borderWidth = 1.0 changeColorBtn.setTitle("change Color", for: UIControlState()) changeColorBtn.setTitleColor(UIColor.blue, for: UIControlState()) layerView.addSubview(changeColorBtn) } func changeColor() { //create a keyframe animation let animation = CAKeyframeAnimation(); animation.keyPath = "backgroundColor"; animation.duration = 4.5; animation.values = [ UIColor.blue.cgColor, UIColor.red.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor ]; //add timing function let fn = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn) animation.timingFunctions = [fn, fn, fn]; //apply animation to layer self.colorLayer.add(animation, forKey:nil); } } /// 用贝塞尔曲线画出MediaTimingFunction曲线图 class BezierMediaTimingFunctionController: UIViewController { let layerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 220, height: 220)) override func viewDidLoad() { super.viewDidLoad() layerView.backgroundColor = UIColor.white layerView.center = self.view.center self.view.addSubview(layerView) let transformSegment = UISegmentedControl.init(items: [kCAMediaTimingFunctionLinear,kCAMediaTimingFunctionEaseOut,kCAMediaTimingFunctionEaseIn,kCAMediaTimingFunctionEaseInEaseOut]) transformSegment.center = CGPoint(x: self.view.center.x, y: self.view.frame.maxY - 50) transformSegment.addTarget(self, action: #selector(BezierMediaTimingFunctionController.switchFunction(_:)), for: .valueChanged) self.view.addSubview(transformSegment) } func switchFunction(_ segment: UISegmentedControl) { if layerView.layer.sublayers?.count > 0 { for sublayer in layerView.layer.sublayers! { sublayer.removeFromSuperlayer() } } let title = segment.titleForSegment(at: segment.selectedSegmentIndex)! BezierMediaTimingFunctionController.drawBezier(CAMediaTimingFunction.init(name: title), inView: layerView) } class func drawBezier(_ function: CAMediaTimingFunction, inView: UIView) { //get control points var controlPoint1: [Float] = [0,0] var controlPoint2: [Float] = [0,0] function.getControlPoint(at: 1, values: &controlPoint1) function.getControlPoint(at: 2, values: &controlPoint2) //create curve let path = UIBezierPath.init() path.move(to: CGPoint.zero) path.addCurve(to: CGPoint(x: 1.0, y: 1.0), controlPoint1: CGPoint(x: CGFloat( controlPoint1[0]), y: CGFloat(controlPoint1[1])), controlPoint2: CGPoint(x: CGFloat( controlPoint2[0]), y: CGFloat(controlPoint2[1]))) //scale the path up to a reasonable size for display let width = min(inView.frame.width, inView.frame.height) path.apply(CGAffineTransform(scaleX: width, y: width)) //create shape layer let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.red.cgColor; shapeLayer.fillColor = UIColor.clear.cgColor; shapeLayer.lineWidth = 4.0; shapeLayer.path = path.cgPath; inView.layer.addSublayer(shapeLayer); //flip geometry so that 0,0 is in the bottom-left inView.layer.isGeometryFlipped = true; } } class CustomMediaTimingFunctionController: AnchorPointViewController, CAAnimationDelegate { override func setAngle(_ angle: CGFloat, handView: UIView) { let transform = CATransform3DMakeRotation(angle, 0, 0, 1) //create transform animation let animation = CABasicAnimation(); animation.keyPath = "transform"; animation.fromValue = handView.layer.presentation()?.value(forKey: "transform"); animation.toValue = NSValue(caTransform3D: transform); animation.duration = 0.5; animation.delegate = self; animation.timingFunction = CAMediaTimingFunction.init(controlPoints: 1, 0, 0.75, 1); //apply animation handView.layer.transform = transform; handView.layer.add(animation, forKey:nil); } } class BallViewController: UIViewController, CAAnimationDelegate { let ballView = UIImageView.init(image: R.image.ball()) override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(ballView) animate() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.animate() } func getInterpolate(_ from: CGFloat, to: CGFloat, time: CGFloat) -> CGFloat { return (to - from) * time + from; } func bounceEaseOut(_ t: Double) -> Double { if (t < 4/11.0) { return (121 * t * t)/16.0; } else if (t < 8/11.0) { return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0; } else if (t < 9/10.0) { return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0; } return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0; } func interpolate(_ fromeValue: CGPoint,toValue: CGPoint,time: Double) -> NSValue { var resultValue = NSValue.init(cgPoint: CGPoint(x: 0,y: 0)) let result = CGPoint(x: getInterpolate(fromeValue.x, to: toValue.x, time: CGFloat(time)), y: getInterpolate(fromeValue.y, to: toValue.y, time: CGFloat(time))); resultValue = NSValue.init(cgPoint: result) return resultValue } func animate() { //reset ball to top of screen self.ballView.center = CGPoint(x: 150, y: 32); //set up animation parameters let fromValue = CGPoint(x: 150, y: 32); let toValue = CGPoint(x: 150, y: 268) let duration = 1.0; //generate keyframes let numFrames = duration * 60; let frames = NSMutableArray(); for i in 0 ..< Int(numFrames) { var time = 1.0/numFrames * Double(i); //apply easing time = bounceEaseOut(time); frames.add(interpolate(fromValue, toValue: toValue, time: time)) } //create keyframe animation let animation = CAKeyframeAnimation() animation.keyPath = "position"; animation.duration = 1.0; animation.delegate = self; // animation.values = [ // NSValue.init(CGPoint: CGPointMake(150,32)), // NSValue.init(CGPoint: CGPointMake(150, 268)), // NSValue.init(CGPoint: CGPointMake(150, 140)), // NSValue.init(CGPoint: CGPointMake(150, 268)), // NSValue.init(CGPoint: CGPointMake(150, 220)), // NSValue.init(CGPoint: CGPointMake(150, 268)), // NSValue.init(CGPoint: CGPointMake(150, 250)), // NSValue.init(CGPoint: CGPointMake(150, 268)) // ]; // animation.timingFunctions = [ // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseIn), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseOut), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseIn), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseOut), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseIn), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseOut), // CAMediaTimingFunction.init(name:kCAMediaTimingFunctionEaseIn) // ]; // animation.keyTimes = [0.0, 0.3, 0.5, 0.7, 0.8, 0.9, 0.95, 1.0]; animation.values = frames as [AnyObject]; //apply animation self.ballView.layer.position = CGPoint(x: 150, y: 268); self.ballView.layer.add(animation, forKey:nil); } }
mit
5af42e15d5417b78e05c62aaeda0cc3c
34.819079
220
0.624575
4.366079
false
false
false
false
JohnEstropia/CoreStore
Sources/DiffableDataSource.TableViewAdapter-UIKit.swift
1
9884
// // DiffableDataSource.TableViewAdapter-UIKit.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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. // #if canImport(UIKit) && (os(iOS) || os(tvOS)) import UIKit import CoreData // MARK: - DiffableDataSource extension DiffableDataSource { // MARK: - TableViewAdapter /** The `DiffableDataSource.TableViewAdapterAdapter` serves as a `UITableViewDataSource` that handles `ListPublisher` snapshots for a `UITableView`. Subclasses of `DiffableDataSource.TableViewAdapter` may override some `UITableViewDataSource` methods as needed. The `DiffableDataSource.TableViewAdapterAdapter` instance needs to be held on (retained) for as long as the `UITableView`'s lifecycle. ``` self.dataSource = DiffableDataSource.TableViewAdapter<Person>( tableView: self.tableView, dataStack: CoreStoreDefaults.dataStack, cellProvider: { (tableView, indexPath, person) in let cell = tableView.dequeueReusableCell(withIdentifier: "PersonCell") as! PersonCell cell.setPerson(person) return cell } ) ``` The dataSource can then apply changes from a `ListPublisher` as shown: ``` listPublisher.addObserver(self) { [weak self] (listPublisher) in self?.dataSource?.apply( listPublisher.snapshot, animatingDifferences: true ) } ``` `DiffableDataSource.TableViewAdapter` fully handles the reload animations. - SeeAlso: CoreStore's DiffableDataSource implementation is based on https://github.com/ra1028/DiffableDataSources */ open class TableViewAdapter<O: DynamicObject>: BaseAdapter<O, DefaultTableViewTarget<UITableView>>, UITableViewDataSource { // MARK: Public /** Initializes the `DiffableDataSource.TableViewAdapter`. This instance needs to be held on (retained) for as long as the `UITableView`'s lifecycle. ``` self.dataSource = DiffableDataSource.TableViewAdapter<Person>( tableView: self.tableView, dataStack: CoreStoreDefaults.dataStack, cellProvider: { (tableView, indexPath, person) in let cell = tableView.dequeueReusableCell(withIdentifier: "PersonCell") as! PersonCell cell.setPerson(person) return cell } ) ``` - parameter tableView: the `UITableView` to set the `dataSource` of. This instance is not retained by the `DiffableDataSource.TableViewAdapter`. - parameter dataStack: the `DataStack` instance that the dataSource will fetch objects from - parameter cellProvider: a closure that configures and returns the `UITableViewCell` for the object */ public init( tableView: UITableView, dataStack: DataStack, cellProvider: @escaping (UITableView, IndexPath, O) -> UITableViewCell? ) { self.cellProvider = cellProvider super.init(target: .init(tableView), dataStack: dataStack) tableView.dataSource = self } /** The target `UITableView` */ public var tableView: UITableView? { return self.target.base } // MARK: - UITableViewDataSource @objc @MainActor public dynamic func numberOfSections(in tableView: UITableView) -> Int { return self.numberOfSections() } @objc @MainActor public dynamic func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int { return self.numberOfItems(inSection: section) ?? 0 } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, titleForHeaderInSection section: Int ) -> String? { return self.sectionID(for: section) } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, titleForFooterInSection section: Int ) -> String? { return nil } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { guard let objectID = self.itemID(for: indexPath) else { Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) already removed from list") } guard let object = self.dataStack.fetchExisting(objectID) as O? else { Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) has been deleted") } guard let cell = self.cellProvider(tableView, indexPath, object) else { Internals.abort("\(Internals.typeName(UITableViewDataSource.self)) returned a `nil` cell for \(Internals.typeName(IndexPath.self)) \(indexPath)") } return cell } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, canEditRowAt indexPath: IndexPath ) -> Bool { return true } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath ) -> UITableViewCell.EditingStyle { return .delete } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath ) {} @objc @MainActor open dynamic func sectionIndexTitles( for tableView: UITableView ) -> [String]? { return nil } @objc @MainActor open dynamic func tableView( _ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int ) -> Int { return index } // MARK: Private @nonobjc private let cellProvider: (UITableView, IndexPath, O) -> UITableViewCell? } // MARK: - DefaultTableViewTarget public struct DefaultTableViewTarget<T: UITableView>: Target { // MARK: Public public typealias Base = T public private(set) weak var base: Base? public init(_ base: Base) { self.base = base } // MARK: DiffableDataSource.Target public var shouldSuspendBatchUpdates: Bool { return self.base?.window == nil } public func deleteSections(at indices: IndexSet, animated: Bool) { self.base?.deleteSections(indices, with: .automatic) } public func insertSections(at indices: IndexSet, animated: Bool) { self.base?.insertSections(indices, with: .automatic) } public func reloadSections(at indices: IndexSet, animated: Bool) { self.base?.reloadSections(indices, with: .automatic) } public func moveSection(at index: IndexSet.Element, to newIndex: IndexSet.Element, animated: Bool) { self.base?.moveSection(index, toSection: newIndex) } public func deleteItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.deleteRows(at: indexPaths, with: .automatic) } public func insertItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.insertRows(at: indexPaths, with: .automatic) } public func reloadItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.reloadRows(at: indexPaths, with: .automatic) } public func moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath, animated: Bool) { self.base?.moveRow(at: indexPath, to: newIndexPath) } public func performBatchUpdates(updates: () -> Void, animated: Bool, completion: @escaping () -> Void) { guard let base = self.base else { return } base.performBatchUpdates(updates, completion: { _ in completion() }) } public func reloadData() { self.base?.reloadData() } } } // MARK: Deprecated extension DiffableDataSource { @available(*, deprecated, renamed: "TableViewAdapter") public typealias TableView = TableViewAdapter } #endif
mit
12d5c1ec06cfcd09be71331dd871a6f6
30.778135
262
0.60943
5.391708
false
false
false
false
suncry/MLHybrid
Example/Pods/Kingfisher/Sources/ImageDownloader.swift
2
27334
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: URLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var url: URL? { return internalTask.originalRequest?.url } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } ///The code of errors which `ImageDownloader` might encountered. public enum KingfisherError: Int { /// badData: The downloaded data is not an image or the data is corrupted. case badData = 10000 /// notModified: The remote server responsed a 304 code. No image data downloaded. case notModified = 10001 /// The HTTP status code in response is not valid. If an invalid /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` /// in `userInfo` to see the code. case invalidStatusCode = 10002 /// notCached: The image rquested is not in cache but .onlyFromCache is activated. case notCached = 10003 /// The URL is invalid. case invalidURL = 20000 /// The downloading task is cancelled before started. case downloadCancelledBeforeStarting = 30000 } /// Key will be used in the `userInfo` of `.invalidStatusCode` public let KingfisherErrorStatusCodeKey = "statusCode" /// Protocol of `ImageDownloader`. public protocol ImageDownloaderDelegate: class { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter url: URL of the original request URL. - parameter response: The response object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) /** Called when the `ImageDownloader` object starts to download an image from specified URL. - parameter downloader: The `ImageDownloader` object starts the downloading. - parameter url: URL of the original request. - parameter response: The request object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) /** Check if a received HTTP status code is valid or not. By default, a status code between 200 to 400 (excluded) is considered as valid. If an invalid code is received, the downloader will raise an .invalidStatusCode error. It has a `userInfo` which includes this statusCode and localizedString error message. - parameter code: The received HTTP status code. - parameter downloader: The `ImageDownloader` object asking for validate status code. - returns: Whether this HTTP status code is valid or not. - Note: If the default 200 to 400 valid code does not suit your need, you can implement this method to change that behavior. */ func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool /** Called when the `ImageDownloader` object successfully downloaded image data from specified URL. - parameter downloader: The `ImageDownloader` object finishes data downloading. - parameter data: Downloaded data. - parameter url: URL of the original request URL. - returns: The data from which Kingfisher should use to create an image. - Note: This callback can be used to preprocess raw image data before creation of UIImage instance (i.e. decrypting or verification). */ func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? } extension ImageDownloaderDelegate { public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {} public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { return (200..<400).contains(code) } public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? { return data } } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponsable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionDelegate`. */ func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter task: The task whose request requires authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSessionTaskDelegate.urlSession(:task:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionTaskDelegate`. */ func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler(.performDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { class ImageFetchLoad { var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? var cancelSemaphore: DispatchSemaphore? } // MARK: - Public property /// The duration before the download is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session?.invalidateAndCancel() session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) } } /// Whether the download requests should use pipeling or not. Default is false. open var requestsUsePipelining = false fileprivate let sessionHandler: ImageDownloaderSessionHandler fileprivate var session: URLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? // MARK: - Internal property let barrierQueue: DispatchQueue let processQueue: DispatchQueue let cancelQueue: DispatchQueue typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) var fetchLoads = [URL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public static let `default` = ImageDownloader(name: "default") /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)") sessionHandler = ImageDownloaderSessionHandler() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) } deinit { session?.invalidateAndCancel() } func fetchLoad(for url: URL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] } return fetchLoad } /** Download an image with a URL and option. - parameter url: Target URL. - parameter retrieveImageTask: The task to cooporate with cache. Pass `nil` if you are not trying to use downloader and cache. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ @discardableResult open func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) request.httpShouldUsePipelining = requestsUsePipelining if let modifier = options?.modifier { guard let r = modifier.modified(for: request) else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } request = r } // There is a possiblility that request modifier changed the url to `nil` or empty. guard let url = request.url, !url.absoluteString.isEmpty else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) return nil } var downloadTask: RetrieveImageDownloadTask? setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTask(with: request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority dataTask.resume() self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } } // MARK: - Download method extension ImageDownloader { // A single key may have multiple callbacks. Only download once. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) { func prepareFetchLoad() { barrierQueue.sync(flags: .barrier) { let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) fetchLoads[url] = loadObjectForURL if let session = session { started(session, loadObjectForURL) } } } if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 { if fetchLoad.cancelSemaphore == nil { fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0) } cancelQueue.async { _ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture) fetchLoad.cancelSemaphore = nil prepareFetchLoad() } } else { prepareFetchLoad() } } func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { barrierQueue.sync(flags: .barrier) { if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } } // MARK: - NSURLSessionDataDelegate /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. // See https://github.com/onevcat/Kingfisher/issues/235 class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let downloader = downloadHolder else { completionHandler(.cancel) return } if let statusCode = (response as? HTTPURLResponse)?.statusCode, let url = dataTask.originalRequest?.url, !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) callCompletionHandlerFailure(error: error, url: url) } completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let downloader = downloadHolder else { return } if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { fetchLoad.responseData.append(data) if let expectedLength = dataTask.response?.expectedContentLength { for content in fetchLoad.contents { DispatchQueue.main.async { content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) } } } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { callCompletionHandlerFailure(error: error!, url: url) return } processImage(for: task, url: url) } /** This method is exposed since the compiler requests. Do not call it. */ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) } func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, task: task, didReceive: challenge, completionHandler: completionHandler) } private func cleanFetchLoad(for url: URL) { guard let downloader = downloadHolder else { return } downloader.barrierQueue.sync(flags: .barrier) { downloader.fetchLoads.removeValue(forKey: url) if downloader.fetchLoads.isEmpty { downloadHolder = nil } } } private func callCompletionHandlerFailure(error: Error, url: URL) { guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { return } // We need to clean the fetch load first, before actually calling completion handler. cleanFetchLoad(for: url) var leftSignal: Int repeat { leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0 } while leftSignal != 0 for content in fetchLoad.contents { content.options.callbackDispatchQueue.safeAsync { content.callback.completionHandler?(nil, error as NSError, url, nil) } } } private func processImage(for task: URLSessionTask, url: URL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. downloader.processQueue.async { guard let fetchLoad = downloader.fetchLoad(for: url) else { return } self.cleanFetchLoad(for: url) let data: Data? let fetchedData = fetchLoad.responseData as Data if let delegate = downloader.delegate { data = delegate.imageDownloader(downloader, didDownload: fetchedData, for: url) } else { data = fetchedData } // Cache the processed images. So we do not need to re-process the image if using the same processor. // Key is the identifier of processor. var imageCache: [String: Image] = [:] for content in fetchLoad.contents { let options = content.options let completionHandler = content.callback.completionHandler let callbackQueue = options.callbackDispatchQueue let processor = options.processor var image = imageCache[processor.identifier] if let data = data, image == nil { image = processor.process(item: .data(data), options: options) // Add the processed image to cache. // If `image` is nil, nothing will happen (since the key is not existing before). imageCache[processor.identifier] = image } if let image = image { downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) let imageModifier = options.imageModifier let finalImage = imageModifier.modify(image) if options.backgroundDecode { let decodedImage = finalImage.kf.decoded callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } } else { callbackQueue.safeAsync { completionHandler?(finalImage, nil, url, data) } } } else { if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) completionHandler?(nil, notModified, url, nil) continue } let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } } } } } } // Placeholder. For retrieving extension methods of ImageDownloaderDelegate extension ImageDownloader: ImageDownloaderDelegate {}
mit
3d9c02f260f1a35c683073e71b75068a
43.957237
227
0.662618
5.696957
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/ObjLiplisIcon.swift
1
5215
// // ObjIcon.swift // Liplis // // Liplisのアイコンインスタンス // //アップデート履歴 // 2015/05/04 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // // Created by sachin on 2015/05/04. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class ObjLiplisIcon { ///============================= /// プロパティ internal var imgSleep : UIImage! //おやすみアイコン internal var imgWakeup : UIImage! //起床アイコン internal var imgLog : UIImage! //回想アイコン internal var imgSetting : UIImage! //設定アイコン internal var imgIntro : UIImage! //会話アイコン internal var imgBack : UIImage! //時計背景アイコン internal var imgBattery_0 : UIImage! //0% internal var imgBattery_12 : UIImage! //12% internal var imgBattery_25 : UIImage! //25% internal var imgBattery_37 : UIImage! //37% internal var imgBattery_50 : UIImage! //50% internal var imgBattery_62 : UIImage! //62% internal var imgBattery_75 : UIImage! //75% internal var imgBattery_87 : UIImage! //87% internal var imgBattery_100 : UIImage! //100% internal var imgBattery_non : UIImage! // //============================================================ // //初期化処理 // //============================================================ /** デフォルトイニシャライザ */ internal init() { self.imgSleep = UIImage(named: "ico_zzz") self.imgWakeup = UIImage(named: "ico_waikup") self.imgLog = UIImage(named: "ico_log") self.imgSetting = UIImage(named: "ico_setting") self.imgIntro = UIImage(named: "ico_intro") self.imgBack = UIImage(named: "ico_back") self.imgBattery_0 = UIImage(named: "battery_0") self.imgBattery_12 = UIImage(named: "battery_12") self.imgBattery_25 = UIImage(named: "battery_25") self.imgBattery_37 = UIImage(named: "battery_37") self.imgBattery_50 = UIImage(named: "battery_50") self.imgBattery_62 = UIImage(named: "battery_62") self.imgBattery_75 = UIImage(named: "battery_75") self.imgBattery_87 = UIImage(named: "battery_87") self.imgBattery_100 = UIImage(named: "battery_100") self.imgBattery_non = UIImage(named: "battery_non") } /** デフォルトイニシャライザ */ internal init(windowPath : String) { self.imgSleep = UIImage(contentsOfFile: windowPath + "/ico_zzz.png") self.imgWakeup = UIImage(contentsOfFile: windowPath + "/ico_waikup.png") self.imgLog = UIImage(contentsOfFile: windowPath + "/ico_log.png") self.imgSetting = UIImage(contentsOfFile: windowPath + "/ico_setting.png") self.imgIntro = UIImage(contentsOfFile: windowPath + "/ico_intro.png") self.imgBack = UIImage(contentsOfFile: windowPath + "/ico_back.png") self.imgBattery_0 = UIImage(contentsOfFile: windowPath + "/battery_0.png") self.imgBattery_12 = UIImage(contentsOfFile: windowPath + "/battery_12.png") self.imgBattery_25 = UIImage(contentsOfFile: windowPath + "/battery_25.png") self.imgBattery_37 = UIImage(contentsOfFile: windowPath + "/battery_37.png") self.imgBattery_50 = UIImage(contentsOfFile: windowPath + "/battery_50.png") self.imgBattery_62 = UIImage(contentsOfFile: windowPath + "/battery_62.png") self.imgBattery_75 = UIImage(contentsOfFile: windowPath + "/battery_75.png") self.imgBattery_87 = UIImage(contentsOfFile: windowPath + "/battery_87.png") self.imgBattery_100 = UIImage(contentsOfFile: windowPath + "/battery_100.png") self.imgBattery_non = UIImage(contentsOfFile: windowPath + "/battery_non.png") //互換性対策 if self.imgIntro == nil{ self.imgIntro = UIImage(contentsOfFile: windowPath + "/ico_thinking_not.png") } } //============================================================ // //アイコン取得 // //============================================================ /** バッテリーアイコンを取得する */ internal func getBatteryIcon(batteryNowLevel : Int)->UIImage! { // if(batteryNowLevel <= 10) { return self.imgBattery_0 }else if(batteryNowLevel <= 12) { return self.imgBattery_12; }else if(batteryNowLevel <= 25) { return self.imgBattery_25; }else if(batteryNowLevel <= 37) { return self.imgBattery_37; }else if(batteryNowLevel <= 50) { return self.imgBattery_50 }else if(batteryNowLevel <= 62) { return self.imgBattery_62 }else if(batteryNowLevel <= 75) { return self.imgBattery_75 }else if(batteryNowLevel <= 87) { return self.imgBattery_87 }else if(batteryNowLevel > 87) { return self.imgBattery_100 } else { return self.imgBattery_non } } }
mit
d83e05fae033f68efd108f16b3e06915
34.985507
89
0.566969
3.790076
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Bubble/BubblesFetchReqest.swift
1
2916
// // BubblesFetchReqest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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 class BubblesFetchReqest: Request { override var method: RequestMethod { return .get } override var parameters: Dictionary<String, AnyObject> { return prepareParametersDictionary() } override var endpoint: String { if let creationId = creationId { return "creations/\(creationId)/bubbles" } if let galleryId = galleryId { return "galleries/\(galleryId)/bubbles" } if let userId = userId { return "users/\(userId)/bubbles" } return "" } fileprivate let creationId: String? fileprivate let galleryId: String? fileprivate let userId: String? fileprivate let page: Int? fileprivate let perPage: Int? init(creationId: String, page: Int?, perPage: Int?) { self.creationId = creationId self.page = page self.perPage = perPage self.galleryId = nil self.userId = nil } init(galleryId: String, page: Int?, perPage: Int?) { self.page = page self.perPage = perPage self.creationId = nil self.galleryId = galleryId self.userId = nil } init(userId: String, page: Int?, perPage: Int?) { self.page = page self.perPage = perPage self.creationId = nil self.galleryId = nil self.userId = userId } func prepareParametersDictionary() -> Dictionary<String, AnyObject> { var params = Dictionary<String, AnyObject>() if let page = page { params["page"] = page as AnyObject? } if let perPage = perPage { params["per_page"] = perPage as AnyObject? } return params } }
mit
afb2b445ecbcd45d66a8e15d8b83491b
32.136364
99
0.655693
4.458716
false
false
false
false
rchatham/SwiftyTypeForm
SwiftyTypeForm/FormField.swift
1
6923
// // FormField.swift // HermesTranslator // // Created by Reid Chatham on 1/18/17. // Copyright © 2017 Hermes Messenger LLC. All rights reserved. // import UIKit import PhoneNumberKit public protocol FormFieldDelegate: class { func formField(_ formField: FormField, returnedWith data: FormData) func formFieldDidEndEditing(_ formField: FormField) func formFieldCancelled(_ formField: FormField) func formFieldWasSelected(_ formField: FormField) } public protocol FormFieldDataSource: class {} public final class FormField: UIView, UITextFieldDelegate, FormType { public var configuration: FormFieldConfiguration = FormFieldConfiguration() { didSet { configurationUpdated() } } private(set) public var dataType: FormDataType = .text public weak var dataSource: FormFieldDataSource? public weak var delegate: FormFieldDelegate? fileprivate let stackView = UIStackView(arrangedSubviews: []) public var titleLabel: UILabel! public var inputField: UIView! public init(dataType: FormDataType, frame: CGRect = .zero) { self.dataType = dataType super.init(frame: frame) addSubview(stackView) addConstraints([ NSLayoutConstraint(item: self, attribute: .leadingMargin, relatedBy: .greaterThanOrEqual, toItem: stackView, attribute: .leading, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: self, attribute: .topMargin, relatedBy: .greaterThanOrEqual, toItem: stackView, attribute: .top, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: self, attribute: .trailingMargin, relatedBy: .greaterThanOrEqual, toItem: stackView, attribute: .trailing, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: self, attribute: .bottomMargin, relatedBy: .greaterThanOrEqual, toItem: stackView, attribute: .bottom, multiplier: 1.0, constant: 0.0) ]) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc internal func tap(_ sender: UITapGestureRecognizer) { resignFirstResponder() delegate?.formFieldCancelled(self) } @discardableResult override public func becomeFirstResponder() -> Bool { return inputField?.becomeFirstResponder() ?? false } @discardableResult override public func resignFirstResponder() -> Bool { return inputField?.resignFirstResponder() ?? false } public func getInput() -> FormData { var data = FormData(type: dataType, data: nil) switch dataType { case .text: data.data = (inputField as? UITextField)?.text case .image(_): data.data = (inputField as? UIImageView)?.image case .phone: guard let rawNumber = (inputField as? PhoneNumberTextField)?.text, let currentRegion = (inputField as? PhoneNumberTextField)?.currentRegion else { return data } data.data = try? PhoneNumberKit().parse(rawNumber, withRegion: currentRegion) } return data } public func configure(for data: FormData) { if inputField != nil { stackView.removeArrangedSubview(inputField) inputField.removeFromSuperview() } switch data.type { case .text, .phone: let textField = UITextField() textField.delegate = self textField.enablesReturnKeyAutomatically = true textField.returnKeyType = .done textField.inputAccessoryView = { let button = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(FormField.returnInput(_:)) ) $0.setItems([button], animated: false) $0.sizeToFit() return $0 } (UIToolbar()) inputField = textField case .image(_): let imageView = UIImageView() imageView.isUserInteractionEnabled = true imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FormField.pickPhoto(_:))) imageView.addGestureRecognizer(tapGesture) inputField = imageView } dataType = data.type stackView.addArrangedSubview(inputField) } @discardableResult @objc internal func returnInput(_ sender: Any) -> Bool { let input = getInput() delegate?.formField(self, returnedWith: input) resignFirstResponder() return true } @objc internal func pickPhoto(_ sender: UITapGestureRecognizer) { if case .image(let request) = dataType { request() { [weak self] image in guard let image = image else { return } (self?.inputField as? UIImageView)?.image = image self?.returnInput(sender) } } } private func setup() { let tap = UITapGestureRecognizer( target: self, action: #selector(FormField.tap(_:)) ) addGestureRecognizer(tap) configurationUpdated() } private func configurationUpdated() { backgroundColor = configuration.backgroundColor alpha = configuration.alpha _ = { $0.axis = configuration.axis $0.alignment = configuration.alignment $0.distribution = configuration.distribution $0.isBaselineRelativeArrangement = configuration.isBaselineRelativeArrangement $0.isLayoutMarginsRelativeArrangement = configuration.isLayoutMarginsRelativeArrangement $0.spacing = configuration.spacing } (stackView) } // MARK: - UITextFieldDelegate @objc public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return returnInput(textField) } @objc public func textFieldDidBeginEditing(_ textField: UITextField) { delegate?.formFieldWasSelected(self) } @objc public func textFieldDidEndEditing(_ textField: UITextField) { delegate?.formFieldDidEndEditing(self) } }
mit
04e74460e2e27519ad1274907d9d1b77
32.931373
109
0.581479
5.866102
false
true
false
false
josve05a/wikipedia-ios
WMF Framework/NSManagedObjectContext+WMFUtilities.swift
4
4370
public extension NSManagedObjectContext { func wmf_create<T: NSManagedObject>(entityNamed entityName: String, withValue value: Any, forKey key: String) -> T? { let object = NSEntityDescription.insertNewObject(forEntityName: entityName, into: self) as? T object?.setValue(value, forKey: key) return object } func wmf_create<T: NSManagedObject>(entityNamed entityName: String, withKeysAndValues dictionary: [String: Any?]) -> T? { let object = NSEntityDescription.insertNewObject(forEntityName: entityName, into: self) as? T for (key, value) in dictionary { object?.setValue(value, forKey: key) } return object } func wmf_fetch<T: NSManagedObject>(objectForEntityName entityName: String, withValue value: Any, forKey key: String) -> T? { let fetchRequest = NSFetchRequest<T>(entityName: entityName) fetchRequest.predicate = NSPredicate(format: "\(key) == %@", argumentArray: [value]) fetchRequest.fetchLimit = 1 var results: [T] = [] do { results = try fetch(fetchRequest) } catch let error { DDLogError("Error fetching: \(error)") } return results.first } func wmf_fetchOrCreate<T: NSManagedObject>(objectForEntityName entityName: String, withValue value: Any, forKey key: String) -> T? { return wmf_fetch(objectForEntityName: entityName, withValue: value, forKey: key) ?? wmf_create(entityNamed: entityName, withValue: value, forKey: key) } func wmf_fetch<T: NSManagedObject, V: Hashable>(objectsForEntityName entityName: String, withValues values: [V], forKey key: String) throws -> [T]? { let fetchRequest = NSFetchRequest<T>(entityName: entityName) fetchRequest.predicate = NSPredicate(format: "\(key) IN %@", argumentArray: [values]) fetchRequest.fetchLimit = values.count return try fetch(fetchRequest) } func wmf_fetchOrCreate<T: NSManagedObject, V: Hashable>(objectsForEntityName entityName: String, withValues values: [V], forKey key: String) throws -> [T]? { var results = try wmf_fetch(objectsForEntityName: entityName, withValues: values, forKey: key) as? [T] ?? [] var missingValues = Set(values) for result in results { guard let value = result.value(forKey: key) as? V else { continue } missingValues.remove(value) } for value in missingValues { guard let object = wmf_create(entityNamed: entityName, withValue: value, forKey: key) as? T else { continue } results.append(object) } return results } func wmf_batchProcessObjects<T: NSManagedObject>(matchingPredicate: NSPredicate? = nil, resetAfterSave: Bool = false, handler: (T) throws -> Void) throws { let fetchRequest = T.fetchRequest() let batchSize = 500 fetchRequest.predicate = matchingPredicate fetchRequest.fetchBatchSize = batchSize let results = try fetch(fetchRequest) for (index, result) in results.enumerated() { if let result = result as? T { try handler(result) } let count = index + 1 if count % batchSize == 0 || count == results.count { if hasChanges { try save() } if resetAfterSave { reset() } } } } func wmf_batchProcess<T: NSManagedObject>(matchingPredicate: NSPredicate? = nil, resetAfterSave: Bool = false, handler: ([T]) throws -> Void) throws { let fetchRequest = T.fetchRequest() let batchSize = 500 fetchRequest.predicate = matchingPredicate fetchRequest.fetchBatchSize = batchSize let results = try fetch(fetchRequest) as? [T] ?? [] var start: Int = 0 var end: Int = 0 while start < results.count { end = min(start + batchSize, results.count) try handler(Array<T>(results[start..<end])) if hasChanges { try save() } if resetAfterSave { reset() } start = end } } }
mit
ae798ac115b28ba1153a0bdb18561b57
40.619048
161
0.594966
4.915636
false
false
false
false
niceoasi/Study-iOS_Animations
Section 2_Auto Layout/Chapter 6/Example/starter/PackingList/ViewController.swift
1
2834
/* * Copyright (c) 2014-present Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController { //MARK: IB outlets @IBOutlet var tableView: UITableView! @IBOutlet var buttonMenu: UIButton! @IBOutlet var titleLabel: UILabel! //MARK: further class variables var slider: HorizontalItemList! var isMenuOpen = false var items: [Int] = [5, 6, 7] //MARK: class methods @IBAction func actionToggleMenu(_ sender: AnyObject) { } func showItem(_ index: Int) { print("tapped item \(index)") } } let itemTitles = ["Icecream money", "Great weather", "Beach ball", "Swim suit for him", "Swim suit for her", "Beach games", "Ironing board", "Cocktail mood", "Sunglasses", "Flip flops"] extension ViewController: UITableViewDelegate, UITableViewDataSource { // MARK: View Controller methods override func viewDidLoad() { super.viewDidLoad() self.tableView?.rowHeight = 54.0 } // MARK: Table View methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell cell.accessoryType = .none cell.textLabel?.text = itemTitles[items[indexPath.row]] cell.imageView?.image = UIImage(named: "summericons_100px_0\(items[indexPath.row]).png") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) showItem(items[indexPath.row]) } }
mit
d2e9070cbec69634ead72c417cb4e404
31.953488
185
0.726182
4.442006
false
false
false
false
flathead/Flame
Flame/Renderer.swift
1
7160
// // Renderer.swift // Flame // // Created by Kenny Deriemaeker on 3/04/16. // Copyright © 2016 Kenny Deriemaeker. All rights reserved. // import MetalKit class Renderer { static let sharedInstance = Renderer() // MARK: - Properties var device: MTLDevice! private var commandQueue: MTLCommandQueue! private var defaultLibrary: MTLLibrary! private var pipeline: MTLRenderPipelineState? private var depthStencilState: MTLDepthStencilState? private var depthTexture: MTLTexture! private var textureSampler: MTLSamplerState? private var fallbackTexture: MTLTexture? // MARK: - Init & deinit init() { device = MTLCreateSystemDefaultDevice() commandQueue = device.newCommandQueue() defaultLibrary = device.newDefaultLibrary()! } // MARK: - Public API func render(drawable: CAMetalDrawable) { guard let camera = Scene.sharedInstance.camera else { return } let renderPass = MTLRenderPassDescriptor() renderPass.colorAttachments[0].texture = drawable.texture renderPass.colorAttachments[0].clearColor = MTLClearColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0) renderPass.colorAttachments[0].loadAction = .Clear renderPass.colorAttachments[0].storeAction = .Store renderPass.depthAttachment.texture = depthTexture renderPass.depthAttachment.loadAction = .Clear renderPass.depthAttachment.storeAction = .Store renderPass.depthAttachment.clearDepth = 1.0 let commandQueue = device.newCommandQueue() let commandBuffer = commandQueue.commandBuffer() let commandEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass) if let pipelineState = pipeline { commandEncoder.setRenderPipelineState(pipelineState) } if let depthStencilState = depthStencilState { commandEncoder.setDepthStencilState(depthStencilState) } if let textureSampler = textureSampler { commandEncoder.setFragmentSamplerState(textureSampler, atIndex: 0) } commandEncoder.setFrontFacingWinding(.Clockwise) commandEncoder.setCullMode(.Back) camera.aspect = Float(drawable.texture.width) / Float(drawable.texture.height) let viewMatrix = camera.viewMatrix let projectionMatrix = camera.projectionMatrix for meshRenderer in Scene.sharedInstance.getMeshRenderers() { if meshRenderer.hidden { continue } if let entity = meshRenderer.entity { let modelMatrix = entity.transform.matrix let mvpMatrix = projectionMatrix * viewMatrix * modelMatrix let uniformBuffer = device.newBufferWithLength(sizeof(Float) * 16, options: .CPUCacheModeDefaultCache) let uniformBufferPtr = uniformBuffer.contents() memcpy(uniformBufferPtr, mvpMatrix.toArray(), sizeof(Float) * 16) commandEncoder.setVertexBuffer(uniformBuffer, offset: 0, atIndex: 1) if let fallbackTexture = fallbackTexture { commandEncoder.setFragmentTexture(fallbackTexture, atIndex: 0) } meshRenderer.draw(commandEncoder) } } commandEncoder.endEncoding() commandBuffer.presentDrawable(drawable) commandBuffer.commit() } func setup(framebufferSize: CGSize) { let vertexDescriptor = MTLVertexDescriptor() vertexDescriptor.attributes[0].format = .Float4 vertexDescriptor.attributes[0].bufferIndex = 0 vertexDescriptor.attributes[0].offset = 0 vertexDescriptor.attributes[1].format = .Float4 vertexDescriptor.attributes[1].bufferIndex = 0 vertexDescriptor.attributes[1].offset = sizeof(Float) * 4 vertexDescriptor.attributes[2].format = .Float2 vertexDescriptor.attributes[2].bufferIndex = 0 vertexDescriptor.attributes[2].offset = sizeof(Float) * 8 vertexDescriptor.layouts[0].stride = sizeof(Vertex) vertexDescriptor.layouts[0].stepRate = 1 vertexDescriptor.layouts[0].stepFunction = .PerVertex let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = defaultLibrary.newFunctionWithName("vertex_main") pipelineDescriptor.fragmentFunction = defaultLibrary.newFunctionWithName("fragment_main") pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm pipelineDescriptor.depthAttachmentPixelFormat = .Depth32Float pipelineDescriptor.vertexDescriptor = vertexDescriptor pipeline = try! device.newRenderPipelineStateWithDescriptor(pipelineDescriptor) let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthWriteEnabled = true depthStencilDescriptor.depthCompareFunction = .Less depthStencilState = device.newDepthStencilStateWithDescriptor(depthStencilDescriptor) createDepthTexture(framebufferSize) let textureSamplerDescriptor = MTLSamplerDescriptor() textureSamplerDescriptor.minFilter = .Nearest textureSamplerDescriptor.magFilter = .Nearest textureSamplerDescriptor.sAddressMode = .Repeat textureSamplerDescriptor.tAddressMode = .Repeat textureSampler = device.newSamplerStateWithDescriptor(textureSamplerDescriptor) let fallbackTextureSize = 8 let fallbackTextureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(.RGBA8Unorm, width: fallbackTextureSize, height: fallbackTextureSize, mipmapped: true) fallbackTexture = device.newTextureWithDescriptor(fallbackTextureDescriptor) let rawData = [UInt8](count: fallbackTextureSize * fallbackTextureSize * 4, repeatedValue: 0xFF) let rawTexture = NSData(bytes: rawData as [UInt8], length: rawData.count) fallbackTexture?.replaceRegion(MTLRegionMake2D(0, 0, fallbackTextureSize, fallbackTextureSize), mipmapLevel: 0, withBytes: UnsafePointer<UInt8>(rawTexture.bytes), bytesPerRow: 4 * fallbackTextureSize) } func resizeView(toSize size: NSSize) { createDepthTexture(size) } // MARK: - Private API private func createDepthTexture(size: NSSize) { let depthTextureDescriptor = MTLTextureDescriptor() depthTextureDescriptor.resourceOptions = .StorageModePrivate depthTextureDescriptor.usage = .RenderTarget depthTextureDescriptor.pixelFormat = .Depth32Float depthTextureDescriptor.width = Int(size.width) depthTextureDescriptor.height = Int(size.height) depthTexture = device.newTextureWithDescriptor(depthTextureDescriptor) } }
mit
0fe1aeba953749cc6047802d8428b706
38.772222
182
0.671742
5.778047
false
false
false
false