repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ApplePride/PIDOR
Examples/Swift/PIDOR/Decorator.swift
1
2018
// // Decorator.swift // PIDOR // // Created by Alexander on 3/1/17. // Copyright © 2017 ApplePride. All rights reserved. // import UIKit class Decorator: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var firstOption: UIButton! @IBOutlet weak var secondOption: UIButton! @IBOutlet weak var resultLabelCenter: NSLayoutConstraint! weak var handler: GayventHandler? override func viewDidLoad() { super.viewDidLoad() resultLabelCenter.constant = -self.view.frame.width handler?.viewDidLoad() } @IBAction func topButtonTapped(_ sender: Any) { handler?.topButtonPressed() } @IBAction func bottomButtonPressed(_ sender: Any) { handler?.bottomButtonPressed() } } extension Decorator: Decoratable { func setImages(_ names:[String]) { UIView.animate(withDuration: 0.25, animations: { self.firstOption.alpha = 0 self.secondOption.alpha = 0 }) { (finished) in self.firstOption.setImage(UIImage(named: names[0]), for: .normal) self.secondOption.setImage(UIImage(named: names[1]), for: .normal) UIView.animate(withDuration: 0.25, animations: { self.firstOption.alpha = 1 self.secondOption.alpha = 1 }) } } func showResults(is pidor: Bool) { UIView.animate(withDuration: 0.5, animations: { self.firstOption.alpha = 0 self.secondOption.alpha = 0 }) { (completed) in if !pidor { self.resultLabel.text = "LOH, NE PIDOR" } else { self.resultLabel.text = "WAY 2 GO BRUH" } UIView.animate(withDuration: 4) { self.resultLabelCenter.constant = self.view.frame.width self.view.layoutIfNeeded() } } } }
mit
b95014820cbfb8e71d645d1756fe55b4
27.814286
78
0.579078
4.423246
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Extensions/MoviesViewController+iOS.swift
1
4867
import Foundation import PopcornKit extension MoviesViewController:UISearchBarDelegate,PCTPlayerViewControllerDelegate,UIViewControllerTransitioningDelegate{ func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) { func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) { dismiss(animated: true) // Close player view controller first. let castPlayerViewController = storyboard?.instantiateViewController(withIdentifier: "CastPlayerViewController") as! CastPlayerViewController castPlayerViewController.media = playerViewController.media castPlayerViewController.localPathToMedia = playerViewController.localPathToMedia castPlayerViewController.directory = playerViewController.directory castPlayerViewController.url = playerViewController.url castPlayerViewController.startPosition = TimeInterval(playerViewController.progressBar.progress) present(castPlayerViewController, animated: true) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if searchBar.text?.isEmpty == true { self.showExternalTorrentWindow(self) return } var magnetLink = searchBar.text! // get magnet link that is inserted as a link tag from the website magnetLink = magnetLink.removingPercentEncoding! let userTorrent = Torrent.init(health: .excellent, url: magnetLink, quality: "1080p", seeds: 100, peers: 100, size: nil) var title = magnetLink if let startIndex = title.range(of: "dn="){ title = String(title[startIndex.upperBound...]) title = String(title[title.startIndex ... title.range(of: "&tr")!.lowerBound]) } let magnetTorrentMedia = Movie.init(title: title, id: "34", tmdbId: nil, slug: "magnet-link", summary: "", torrents: [userTorrent], subtitles: [:], largeBackgroundImage: nil, largeCoverImage: nil) let storyboard = UIStoryboard.main let loadingViewController = storyboard.instantiateViewController(withIdentifier: "PreloadTorrentViewController") as! PreloadTorrentViewController loadingViewController.transitioningDelegate = self loadingViewController.loadView() loadingViewController.titleLabel.text = title self.present(loadingViewController, animated: true) //Movie completion Blocks let error: (String) -> Void = { (errorMessage) in if self.presentedViewController != nil { self.dismiss(animated: false) } let vc = UIAlertController(title: "Error".localized, message: errorMessage, preferredStyle: .alert) vc.addAction(UIAlertAction(title: "OK".localized, style: .cancel, handler: nil)) vc.show(animated: true) } let finishedLoading: (PreloadTorrentViewController, UIViewController) -> Void = { (loadingVc, playerVc) in let flag = UIDevice.current.userInterfaceIdiom != .tv self.dismiss(animated: flag) self.present(playerVc, animated: flag) } let selectTorrent: (Array<String>) -> Int32 = { (torrents) in var selected = -1 let torrentSelection = UIAlertController(title: "Select file to play", message: nil, preferredStyle: .actionSheet) for torrent in torrents{ torrentSelection.addAction(UIAlertAction(title: torrent, style: .default, handler: { _ in selected = torrents.distance(from: torrents.startIndex, to: torrents.firstIndex(of: torrent)!) })) } DispatchQueue.main.sync { torrentSelection.show(animated: true) } while selected == -1{ print("hold")} return Int32(selected) } //Movie player view controller calls let playViewController = storyboard.instantiateViewController(withIdentifier: "PCTPlayerViewController") as! PCTPlayerViewController playViewController.delegate = self magnetTorrentMedia.play(fromFileOrMagnetLink: magnetLink, nextEpisodeInSeries: nil, loadingViewController: loadingViewController, playViewController: playViewController, progress: 0, errorBlock: error, finishedLoadingBlock: finishedLoading, selectingTorrentBlock: selectTorrent) } override func viewDidLoad() { self.magnetLinkTextField.delegate = self super.viewDidLoad() } }
gpl-3.0
df3556f1a83e836f140dd6509d06c787
53.077778
290
0.645367
6.061021
false
false
false
false
yuhaifei123/EmoticonKey
EmoticonKey/EmoticonKey/SnapKit/mode/EmoticonPackage.swift
1
6800
// // EmoticonPackage.swift // EmoticonKey // // Created by 虞海飞 on 2017/2/1. // Copyright © 2017年 虞海飞. All rights reserved. // import UIKit /* 结构: 1. 加载emoticons.plist拿到每组表情的路径 emoticons.plist(字典) 存储了所有组表情的数据 |----packages(字典数组) |-------id(存储了对应组表情对应的文件夹) 2. 根据拿到的路径加载对应组表情的info.plist info.plist(字典) |----id(当前组表情文件夹的名称) |----group_name_cn(组的名称) |----emoticons(字典数组, 里面存储了所有表情) |----chs(表情对应的文字) |----png(表情对应的图片) |----code(emoji表情对应的十六进制字符串) */ class EmoticonPackage: NSObject { //变成单例,这样可以降低性能 static let staticLoadPackages : [EmoticonPackage] = loadPackages(); /// 当前组表情文件夹的名称 var id: String? /// 组的名称 var group_name_cn : String? /// 当前组所有的表情对象 var emoticons: [Emoticon]? /// 获取所有组的表情数组 // 浪小花 -> 一组 -> 所有的表情模型(emoticons) // 默认 -> 一组 -> 所有的表情模型(emoticons) // emoji -> 一组 -> 所有的表情模型(emoticons) private class func loadPackages() -> [EmoticonPackage] { //创建数据 var packages = [EmoticonPackage](); //添加最近组 let pk = EmoticonPackage(id: ""); pk.group_name_cn = "最近"; pk.emoticons = [Emoticon](); pk.appendEmtyEmoticons(); packages.append(pk); let path = Bundle.main.path(forResource: "emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle") // 1.加载emoticons.plist let dict = NSDictionary(contentsOfFile: path!)! // 2.或emoticons中获取packages let dictArray = dict["packages"] as! [[String:AnyObject]] // 3.遍历packages数组 for d in dictArray{ // 4.取出ID, 创建对应的组 let package = EmoticonPackage(id: d["id"]! as! String) packages.append(package) package.loadEmoticons(); package.appendEmtyEmoticons(); } return packages } /// 加载每一组中所有的表情 func loadEmoticons() { let emoticonDict = NSDictionary(contentsOfFile: infoPath(fileName: "info.plist"))! group_name_cn = emoticonDict["group_name_cn"] as? String let dictArray = emoticonDict["emoticons"] as! [[String: String]] emoticons = [Emoticon](); //每个21就加删除按钮 var nub = 0; for dict in dictArray{ if nub == 20{ emoticons!.append(Emoticon.init(removButton: true)); nub = 0; } emoticons!.append(Emoticon(dict: dict, id: id!)) nub = nub+1; } } /// 添加删除按钮 func appendEmtyEmoticons(){ if let num = emoticons{ let count = num.count % 21; for _ in count ..< 20 { //添加空,不是删除按钮 emoticons!.append(Emoticon.init(removButton: false)); } //最后加上删除按钮 emoticons!.append(Emoticon.init(removButton: true)); } } /// 添加个人喜欢 func appendEmoticon(emotion : Emoticon){ //判断是不是删除按钮 if emotion.removButton { return; } let contains = emoticons?.contains(emotion); //判断里面是不是包含这个图形 if contains == false { //删除『删除按钮』 最后一个 emoticons?.removeLast(); //添加一个图标 emoticons?.append(emotion); } var result = emoticons!.sorted { (e1, e2) -> Bool in return e1.times > e2.times; } //判断里面是不是包含这个图形,包含的,把多余的图形删除,添加删除按钮 if contains == false { //删除最后一个数据 result.removeLast(); //添加删除按钮 result.append(Emoticon.init(removButton: true)); } emoticons = result; } /** 获取指定文件的全路径 :param: fileName 文件的名称 :returns: 全路径 */ func infoPath(fileName: String) -> String { return (EmoticonPackage.emoticonPath().appendingPathComponent(id!) as NSString).appendingPathComponent(fileName) } /// 获取微博表情的主路径 class func emoticonPath() -> NSString{ return (Bundle.main.bundlePath as NSString).appendingPathComponent("Emoticons.bundle") as NSString } init(id: String) { self.id = id } } class Emoticon: NSObject { /// 表情对应的文字 var chs: String? /// 表情对应的图片 var png: String?; /// emoji表情对应的十六进制字符串 var code: String?; //emoji 表情 var emojiStr: String?; /// 当前表情对应的文件夹 var id: String? /// 删除按钮 var removButton : Bool = false; /// 点击次数 var times : Int = 0; /// 表情图片的全路径 var imagePath: String? init(removButton : Bool) { super.init(); self.removButton = removButton; } init(dict: [String: String], id: String){ super.init(); self.id = id self.chs = dict["chs"]; self.png = dict["png"]; self.code = dict["code"]; self.emojiStr = dict["emojiStr"]; //setValuesForKeys(dict); if self.png != nil { self.imagePath = (EmoticonPackage.emoticonPath().appendingPathComponent(id) as NSString).appendingPathComponent(png!) } //十六进制转化 if dict["code"] != nil { // 1.从字符串中取出十六进制的数 // 创建一个扫描器, 扫描器可以从字符串中提取我们想要的数据 let scanner = Scanner(string: dict["code"]!) // 2.将十六进制转换为字符串 var result:UInt32 = 0 scanner.scanHexInt32(&result) // 3.将十六进制转换为emoji字符串 emojiStr = "\(Character(UnicodeScalar(result)!))" } } override func setValuesForKeys(_ keyedValues: [String : Any]) { } }
apache-2.0
152e7ddef4726b0307d88f0115c2d42a
24.183406
133
0.522976
4.290923
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/Zip/ZipStateMachine.swift
1
20055
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// /// State machine for zip struct ZipStateMachine< Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence >: Sendable where Base1: Sendable, Base2: Sendable, Base3: Sendable, Base1.Element: Sendable, Base2.Element: Sendable, Base3.Element: Sendable { typealias DownstreamContinuation = UnsafeContinuation<Result<( Base1.Element, Base2.Element, Base3.Element? )?, Error>, Never> private enum State: Sendable { /// Small wrapper for the state of an upstream sequence. struct Upstream<Element: Sendable>: Sendable { /// The upstream continuation. var continuation: UnsafeContinuation<Void, Error>? /// The produced upstream element. var element: Element? } /// The initial state before a call to `next` happened. case initial(base1: Base1, base2: Base2, base3: Base3?) /// The state while we are waiting for downstream demand. case waitingForDemand( task: Task<Void, Never>, upstreams: (Upstream<Base1.Element>, Upstream<Base2.Element>, Upstream<Base3.Element>) ) /// The state while we are consuming the upstream and waiting until we get a result from all upstreams. case zipping( task: Task<Void, Never>, upstreams: (Upstream<Base1.Element>, Upstream<Base2.Element>, Upstream<Base3.Element>), downstreamContinuation: DownstreamContinuation ) /// The state once one upstream sequences finished/threw or the downstream consumer stopped, i.e. by dropping all references /// or by getting their `Task` cancelled. case finished /// Internal state to avoid CoW. case modifying } private var state: State private let numberOfUpstreamSequences: Int /// Initializes a new `StateMachine`. init( base1: Base1, base2: Base2, base3: Base3? ) { self.state = .initial( base1: base1, base2: base2, base3: base3 ) if base3 == nil { self.numberOfUpstreamSequences = 2 } else { self.numberOfUpstreamSequences = 3 } } /// Actions returned by `iteratorDeinitialized()`. enum IteratorDeinitializedAction { /// Indicates that the `Task` needs to be cancelled and /// the upstream continuations need to be resumed with a `CancellationError`. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? { switch self.state { case .initial: // Nothing to do here. No demand was signalled until now return .none case .zipping: // An iterator was deinitialized while we have a suspended continuation. preconditionFailure("Internal inconsistency current state \(self.state) and received iteratorDeinitialized()") case .waitingForDemand(let task, let upstreams): // The iterator was dropped which signals that the consumer is finished. // We can transition to finished now and need to clean everything up. self.state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // We are already finished so there is nothing left to clean up. // This is just the references dropping afterwards. return .none case .modifying: preconditionFailure("Invalid state") } } mutating func taskIsStarted( task: Task<Void, Never>, downstreamContinuation: DownstreamContinuation ) { switch self.state { case .initial: // The user called `next` and we are starting the `Task` // to consume the upstream sequences self.state = .zipping( task: task, upstreams: (.init(), .init(), .init()), downstreamContinuation: downstreamContinuation ) case .zipping, .waitingForDemand, .finished: // We only allow a single task to be created so this must never happen. preconditionFailure("Internal inconsistency current state \(self.state) and received taskStarted()") case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `childTaskSuspended()`. enum ChildTaskSuspendedAction { /// Indicates that the continuation should be resumed which will lead to calling `next` on the upstream. case resumeContinuation( upstreamContinuation: UnsafeContinuation<Void, Error> ) /// Indicates that the continuation should be resumed with an Error because another upstream sequence threw. case resumeContinuationWithError( upstreamContinuation: UnsafeContinuation<Void, Error>, error: Error ) } mutating func childTaskSuspended(baseIndex: Int, continuation: UnsafeContinuation<Void, Error>) -> ChildTaskSuspendedAction? { switch self.state { case .initial: // Child tasks are only created after we transitioned to `zipping` preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended()") case .waitingForDemand(let task, var upstreams): self.state = .modifying switch baseIndex { case 0: upstreams.0.continuation = continuation case 1: upstreams.1.continuation = continuation case 2: upstreams.2.continuation = continuation default: preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended() with base index \(baseIndex)") } self.state = .waitingForDemand( task: task, upstreams: upstreams ) return .none case .zipping(let task, var upstreams, let downstreamContinuation): // We are currently zipping. If we have a buffered element from the base // already then we store the continuation otherwise we just go ahead and resume it switch baseIndex { case 0: if upstreams.0.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.0.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } case 1: if upstreams.1.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.1.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } case 2: if upstreams.2.element == nil { return .resumeContinuation(upstreamContinuation: continuation) } else { self.state = .modifying upstreams.2.continuation = continuation self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: downstreamContinuation ) return .none } default: preconditionFailure("Internal inconsistency current state \(self.state) and received childTaskSuspended() with base index \(baseIndex)") } case .finished: // Since cancellation is cooperative it might be that child tasks are still getting // suspended even though we already cancelled them. We must tolerate this and just resume // the continuation with an error. return .resumeContinuationWithError( upstreamContinuation: continuation, error: CancellationError() ) case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `elementProduced()`. enum ElementProducedAction { /// Indicates that the downstream continuation should be resumed with the element. case resumeContinuation( downstreamContinuation: DownstreamContinuation, result: Result<(Base1.Element, Base2.Element, Base3.Element?)?, Error> ) } mutating func elementProduced(_ result: (Base1.Element?, Base2.Element?, Base3.Element?)) -> ElementProducedAction? { switch self.state { case .initial: // Child tasks that are producing elements are only created after we transitioned to `zipping` preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case .waitingForDemand: // We are only issuing demand when we get signalled by the downstream. // We should never receive an element when we are waiting for demand. preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") case .zipping(let task, var upstreams, let downstreamContinuation): self.state = .modifying switch result { case (.some(let first), .none, .none): precondition(upstreams.0.element == nil) upstreams.0.element = first case (.none, .some(let second), .none): precondition(upstreams.1.element == nil) upstreams.1.element = second case (.none, .none, .some(let third)): precondition(upstreams.2.element == nil) upstreams.2.element = third default: preconditionFailure("Internal inconsistency current state \(self.state) and received elementProduced()") } // Implementing this for the two arities without variadic generics is a bit awkward sadly. if let first = upstreams.0.element, let second = upstreams.1.element, let third = upstreams.2.element { // We got an element from each upstream so we can resume the downstream now self.state = .waitingForDemand( task: task, upstreams: ( .init(continuation: upstreams.0.continuation), .init(continuation: upstreams.1.continuation), .init(continuation: upstreams.2.continuation) ) ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, result: .success((first, second, third)) ) } else if let first = upstreams.0.element, let second = upstreams.1.element, self.numberOfUpstreamSequences == 2 { // We got an element from each upstream so we can resume the downstream now self.state = .waitingForDemand( task: task, upstreams: ( .init(continuation: upstreams.0.continuation), .init(continuation: upstreams.1.continuation), .init(continuation: upstreams.2.continuation) ) ) return .resumeContinuation( downstreamContinuation: downstreamContinuation, result: .success((first, second, nil)) ) } else { // We are still waiting for one of the upstreams to produce an element self.state = .zipping( task: task, upstreams: ( .init(continuation: upstreams.0.continuation, element: upstreams.0.element), .init(continuation: upstreams.1.continuation, element: upstreams.1.element), .init(continuation: upstreams.2.continuation, element: upstreams.2.element) ), downstreamContinuation: downstreamContinuation ) return .none } case .finished: // Since cancellation is cooperative it might be that child tasks // are still producing elements after we finished. // We are just going to drop them since there is nothing we can do return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamFinished()`. enum UpstreamFinishedAction { /// Indicates that the downstream continuation should be resumed with `nil` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func upstreamFinished() -> UpstreamFinishedAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .waitingForDemand: // This can't happen. We are only issuing demand for a single element each time. // There must never be outstanding demand to an upstream while we have no demand ourselves. preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamFinished()") case .zipping(let task, let upstreams, let downstreamContinuation): // One of our upstreams finished. We need to transition to finished ourselves now // and resume the downstream continuation with nil. Furthermore, we need to cancel all of // the upstream work. self.state = .finished return .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `upstreamThrew()`. enum UpstreamThrewAction { /// Indicates that the downstream continuation should be resumed with the `error` and /// the task and the upstream continuations should be cancelled. case resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, error: Error, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func upstreamThrew(_ error: Error) -> UpstreamThrewAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case .waitingForDemand: // This can't happen. We are only issuing demand for a single element each time. // There must never be outstanding demand to an upstream while we have no demand ourselves. preconditionFailure("Internal inconsistency current state \(self.state) and received upstreamThrew()") case .zipping(let task, let upstreams, let downstreamContinuation): // One of our upstreams threw. We need to transition to finished ourselves now // and resume the downstream continuation with the error. Furthermore, we need to cancel all of // the upstream work. self.state = .finished return .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, error: error, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // This is just everything finishing up, nothing to do here return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `cancelled()`. enum CancelledAction { /// Indicates that the downstream continuation needs to be resumed and /// task and the upstream continuations should be cancelled. case resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: DownstreamContinuation, task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) /// Indicates that the task and the upstream continuations should be cancelled. case cancelTaskAndUpstreamContinuations( task: Task<Void, Never>, upstreamContinuations: [UnsafeContinuation<Void, Error>] ) } mutating func cancelled() -> CancelledAction? { switch self.state { case .initial: preconditionFailure("Internal inconsistency current state \(self.state) and received cancelled()") case .waitingForDemand(let task, let upstreams): // The downstream task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. self.state = .finished return .cancelTaskAndUpstreamContinuations( task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .zipping(let task, let upstreams, let downstreamContinuation): // The downstream Task got cancelled so we need to cancel our upstream Task // and resume all continuations. We can also transition to finished. self.state = .finished return .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations( downstreamContinuation: downstreamContinuation, task: task, upstreamContinuations: [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } ) case .finished: // We are already finished so nothing to do here: self.state = .finished return .none case .modifying: preconditionFailure("Invalid state") } } /// Actions returned by `next()`. enum NextAction { /// Indicates that a new `Task` should be created that consumes the sequence. case startTask(Base1, Base2, Base3?) case resumeUpstreamContinuations( upstreamContinuation: [UnsafeContinuation<Void, Error>] ) /// Indicates that the downstream continuation should be resumed with `nil`. case resumeDownstreamContinuationWithNil(DownstreamContinuation) } mutating func next(for continuation: DownstreamContinuation) -> NextAction { switch self.state { case .initial(let base1, let base2, let base3): // This is the first time we get demand singalled so we have to start the task // The transition to the next state is done in the taskStarted method return .startTask(base1, base2, base3) case .zipping: // We already got demand signalled and have suspended the downstream task // Getting a second next calls means the iterator was transferred across Tasks which is not allowed preconditionFailure("Internal inconsistency current state \(self.state) and received next()") case .waitingForDemand(let task, var upstreams): // We got demand signalled now and can transition to zipping. // We also need to resume all upstream continuations now self.state = .modifying let upstreamContinuations = [upstreams.0.continuation, upstreams.1.continuation, upstreams.2.continuation].compactMap { $0 } upstreams.0.continuation = nil upstreams.1.continuation = nil upstreams.2.continuation = nil self.state = .zipping( task: task, upstreams: upstreams, downstreamContinuation: continuation ) return .resumeUpstreamContinuations( upstreamContinuation: upstreamContinuations ) case .finished: // We are already finished so we are just returning `nil` return .resumeDownstreamContinuationWithNil(continuation) case .modifying: preconditionFailure("Invalid state") } } }
apache-2.0
fc4652b805c49fc3de05753ba9ae271c
35.596715
144
0.678634
5.279021
false
false
false
false
BrunoMazzo/CocoaHeadsApp
CocoaHeadsApp/Classes/Base/Utils/NibDesignable.swift
3
2201
import UIKit /** A NibDesignable is a view wrapper tha loads a XIB with the same name of the class and add it to itself. You should use mainly in storyboards, to avoid modifying views inside the storyboard */ @IBDesignable public class NibDesignable: UIView { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib() } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib() } // MARK: - Nib loading /** Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview. */ internal func setupNib() { let view = self.loadNib() self.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let bindings = ["view": view] self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) viewDidLoad() } public func viewDidLoad() { } /** Called to load the nib in setupNib(). - returns: UIView instance loaded from a nib file. */ public func loadNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: self.nibName(), bundle: bundle) guard let view = nib.instantiateWithOwner(self, options: nil).first as? UIView else { fatalError("You're trying to load a NibDesignable without the respective nib file") } return view } /** Called in the default implementation of loadNib(). Default is class name. - returns: Name of a single view nib file. */ public func nibName() -> String { guard let name = self.dynamicType.description().componentsSeparatedByString(".").last else { fatalError("Invalid module name") } return name } }
mit
52ddc38201c75a95cc1ab3677c0a3f31
31.367647
163
0.631985
5.002273
false
false
false
false
lokinfey/MyPerfectframework
PerfectLib/MimeReader.swift
1
12166
// // MimeReader.swift // PerfectLib // // Created by Kyle Jessup on 7/6/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // #if os(Linux) import SwiftGlibc import LinuxBridge let S_IRUSR = __S_IREAD let S_IROTH = (S_IRGRP >> 3) let S_IWOTH = (S_IWGRP >> 3) #else import Darwin #endif enum MimeReadState { case StateNone case StateBoundary // next thing to be read will be a boundry case StateHeader // read header lines until data starts case StateFieldValue // read a simple value; name has already been set case StateFile // read file data until boundry case StateDone } let kMultiPartForm = "multipart/form-data" let kBoundary = "boundary" let kContentDisposition = "Content-Disposition" let kContentType = "Content-Type" let kPerfectTempPrefix = "perfect_upload_" let mime_cr = UInt8(13) let mime_lf = UInt8(10) let mime_dash = UInt8(45) /// This class is responsible for reading multi-part POST form data, including handling file uploads. /// Data can be given for parsing in little bits at a time by calling the `addTobuffer` function. /// Any file uploads which are encountered will be written to the temporary directory indicated when the `MimeReader` is created. /// Temporary files will be deleted when this object is deinitialized. public class MimeReader { /// Array of BodySpecs representing each part that was parsed. public var bodySpecs = [BodySpec]() var maxFileSize = -1 var (multi, gotFile) = (false, false) var buffer = [UInt8]() let tempDirectory: String var state: MimeReadState = .StateNone /// The boundary identifier. public var boundary = "" /// This class represents a single part of a multi-part POST submission public class BodySpec { /// The name of the form field. public var fieldName = "" /// The value for the form field. /// Having a fieldValue and a file are mutually exclusive. public var fieldValue = "" var fieldValueTempBytes: [UInt8]? /// The content-type for the form part. public var contentType = "" /// The client-side file name as submitted by the form. public var fileName = "" /// The size of the file which was submitted. public var fileSize = 0 /// The name of the temporary file which stores the file upload on the server-side. public var tmpFileName = "" /// The File object for the local temporary file. public var file: File? init() { } /// Clean up the BodySpec, possibly closing and deleting any associated temporary file. public func cleanup() { if let f = self.file { if f.exists() { f.delete() } self.file = nil } } deinit { self.cleanup() } } /// Initialize given a Content-type header line. /// - parameter contentType: The Content-type header line. /// - parameter tempDir: The path to the directory in which to store temporary files. Defaults to "/tmp/". public init(_ contentType: String, tempDir: String = "/tmp/") { self.tempDirectory = tempDir if contentType.rangeOf(kMultiPartForm) != nil { self.multi = true if let range = contentType.rangeOf(kBoundary) { var startIndex = range.startIndex.successor() for _ in 1...kBoundary.characters.count { startIndex = startIndex.successor() } let endIndex = contentType.endIndex let boundaryString = contentType.substringWith(Range(start: startIndex, end: endIndex)) self.boundary.appendContentsOf("--") self.boundary.appendContentsOf(boundaryString) self.state = .StateBoundary } } } // not implimented // public func setMaxFileSize(size: Int) { // self.maxFileSize = size // } func openTempFile(spec: BodySpec) { spec.file = File(tempFilePrefix: self.tempDirectory + kPerfectTempPrefix) spec.tmpFileName = spec.file!.path() } func isBoundaryStart(bytes: [UInt8], start: Array<UInt8>.Index) -> Bool { var gen = self.boundary.utf8.generate() var pos = start var next = gen.next() while let char = next { if pos == bytes.endIndex || char != bytes[pos] { return false } pos = pos.successor() next = gen.next() } return next == nil // got to the end is success } func isField(name: String, bytes: [UInt8], start: Array<UInt8>.Index) -> Array<UInt8>.Index { var check = start let end = bytes.endIndex var gen = name.utf8.generate() while check != end { if bytes[check] == 58 { // : return check } let gened = gen.next() if gened == nil { break } if tolower(Int32(gened!)) != tolower(Int32(bytes[check])) { break } check = check.successor() } return end } func pullValue(name: String, from: String) -> String { var accum = "" if let nameRange = from.rangeOf(name + "=", ignoreCase: true) { var start = nameRange.endIndex let end = from.endIndex if from[start] == "\"" { start = start.successor() } while start < end { if from[start] == "\"" || from[start] == ";" { break; } accum.append(from[start]) start = start.successor() } } return accum } func internalAddToBuffer(bytes: [UInt8]) -> MimeReadState { var clearBuffer = true var position = bytes.startIndex let end = bytes.endIndex while position != end { switch self.state { case .StateDone, .StateNone: return .StateNone case .StateBoundary: if position.distanceTo(end) < self.boundary.characters.count + 2 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end } else { position = position.advancedBy(self.boundary.characters.count) if bytes[position] == mime_dash && bytes[position.successor()] == mime_dash { self.state = .StateDone position = position.advancedBy(2) } else { self.state = .StateHeader self.bodySpecs.append(BodySpec()) } if self.state != .StateDone { position = position.advancedBy(2) // line end } else { position = end } } case .StateHeader: var eolPos = position while eolPos.distanceTo(end) > 1 { let b1 = bytes[eolPos] let b2 = bytes[eolPos.successor()] if b1 == mime_cr && b2 == mime_lf { break } eolPos = eolPos.successor() } if eolPos.distanceTo(end) <= 1 { // no eol self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end } else { let spec = self.bodySpecs.last! if eolPos != position { let check = isField(kContentDisposition, bytes: bytes, start: position) if check != end { // yes, content-disposition let line = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos]) let name = pullValue("name", from: line) let fileName = pullValue("filename", from: line) spec.fieldName = name spec.fileName = fileName } else { let check = isField(kContentType, bytes: bytes, start: position) if check != end { // yes, content-type spec.contentType = UTF8Encoding.encode(bytes[check.advancedBy(2)..<eolPos]) } } position = eolPos.advancedBy(2) } if (eolPos == position || position != end) && position.distanceTo(end) > 1 && bytes[position] == mime_cr && bytes[position.successor()] == mime_lf { position = position.advancedBy(2) if spec.fileName.characters.count > 0 { openTempFile(spec) self.state = .StateFile } else { self.state = .StateFieldValue spec.fieldValueTempBytes = [UInt8]() } } } case .StateFieldValue: let spec = self.bodySpecs.last! while position != end { if bytes[position] == mime_cr { if position.distanceTo(end) == 1 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } if bytes[position.successor()] == mime_lf { if isBoundaryStart(bytes, start: position.advancedBy(2)) { position = position.advancedBy(2) self.state = .StateBoundary spec.fieldValue = UTF8Encoding.encode(spec.fieldValueTempBytes!) spec.fieldValueTempBytes = nil break } else if position.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } } } } spec.fieldValueTempBytes!.append(bytes[position]) position = position.successor() } case .StateFile: let spec = self.bodySpecs.last! while position != end { if bytes[position] == mime_cr { if position.distanceTo(end) == 1 { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } if bytes[position.successor()] == mime_lf { if isBoundaryStart(bytes, start: position.advancedBy(2)) { position = position.advancedBy(2) self.state = .StateBoundary // end of file data spec.file!.close() chmod(spec.file!.path(), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)) break } else if position.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if position.distanceTo(end) < 4 || (bytes[position.advancedBy(2)] == mime_dash && bytes[position.advancedBy(3)] == mime_dash) { self.buffer = Array(bytes[position..<end]) clearBuffer = false position = end continue } } } } // write as much data as we reasonably can var writeEnd = position while writeEnd < end { if bytes[writeEnd] == mime_cr { if writeEnd.distanceTo(end) < 2 { break } if bytes[writeEnd.successor()] == mime_lf { if isBoundaryStart(bytes, start: writeEnd.advancedBy(2)) { break } else if writeEnd.distanceTo(end) - 2 < self.boundary.characters.count { // we are at the eol, but check to see if the next line may be starting a boundary if writeEnd.distanceTo(end) < 4 || (bytes[writeEnd.advancedBy(2)] == mime_dash && bytes[writeEnd.advancedBy(3)] == mime_dash) { break } } } } writeEnd = writeEnd.successor() } do { let length = position.distanceTo(writeEnd) spec.fileSize += try spec.file!.writeBytes(bytes, dataPosition: position, length: length) } catch let e { print("Exception while writing file upload data: \(e)") self.state = .StateNone break } if (writeEnd == end) { self.buffer.removeAll() } position = writeEnd self.gotFile = true } } } if clearBuffer { self.buffer.removeAll() } return self.state } /// Add data to be parsed. /// - parameter bytes: The array of UInt8 to be parsed. public func addToBuffer(bytes: [UInt8]) { if isMultiPart() { if self.buffer.count != 0 { self.buffer.appendContentsOf(bytes) internalAddToBuffer(self.buffer) } else { internalAddToBuffer(bytes) } } else { self.buffer.appendContentsOf(bytes) } } /// Returns true of the content type indicated a multi-part form. public func isMultiPart() -> Bool { return self.multi } }
apache-2.0
3bb0f3188766b1fd2de6213913d4f97f
26.776256
153
0.614664
3.674419
false
false
false
false
NghiaTranUIT/Himotoki
Himotoki/ArgumentsBuilder.swift
5
12533
// // ArgumentsBuilder.swift // Himotoki // // Created by Syo Ikeda on 5/11/15. // Copyright (c) 2015 Syo Ikeda. All rights reserved. // // MARK: Arguments builder public func build<A>(a: A?) -> (A)? { if let a = a { return (a) } return nil } public func build<A, B>(a: A?, @autoclosure b: () -> B?) -> (A, B)? { if let a = a, b = b() { return (a, b) } return nil } public func build<A, B, C>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?) -> (A, B, C)? { if let a = a, b = b(), c = c() { return (a, b, c) } return nil } public func build<A, B, C, D>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?) -> (A, B, C, D)? { if let a = a, b = b(), c = c(), d = d() { return (a, b, c, d) } return nil } public func build<A, B, C, D, E>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?) -> (A, B, C, D, E)? { if let a = a, b = b(), c = c(), d = d(), e = e() { return (a, b, c, d, e) } return nil } public func build<A, B, C, D, E, F>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?) -> (A, B, C, D, E, F)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f() { return (a, b, c, d, e, f) } return nil } public func build<A, B, C, D, E, F, G>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?) -> (A, B, C, D, E, F, G)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g() { return (a, b, c, d, e, f, g) } return nil } public func build<A, B, C, D, E, F, G, H>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?) -> (A, B, C, D, E, F, G, H)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h() { return (a, b, c, d, e, f, g, h) } return nil } public func build<A, B, C, D, E, F, G, H, I>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?) -> (A, B, C, D, E, F, G, H, I)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i() { return (a, b, c, d, e, f, g, h, i) } return nil } public func build<A, B, C, D, E, F, G, H, I, J>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?) -> (A, B, C, D, E, F, G, H, I, J)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j() { return (a, b, c, d, e, f, g, h, i, j) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?) -> (A, B, C, D, E, F, G, H, I, J, K)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k() { return (a, b, c, d, e, f, g, h, i, j, k) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?) -> (A, B, C, D, E, F, G, H, I, J, K, L)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l() { return (a, b, c, d, e, f, g, h, i, j, k, l) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m() { return (a, b, c, d, e, f, g, h, i, j, k, l, m) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?, @autoclosure u: () -> U?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t(), u = u() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) } return nil } public func build<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V>(a: A?, @autoclosure b: () -> B?, @autoclosure c: () -> C?, @autoclosure d: () -> D?, @autoclosure e: () -> E?, @autoclosure f: () -> F?, @autoclosure g: () -> G?, @autoclosure h: () -> H?, @autoclosure i: () -> I?, @autoclosure j: () -> J?, @autoclosure k: () -> K?, @autoclosure l: () -> L?, @autoclosure m: () -> M?, @autoclosure n: () -> N?, @autoclosure o: () -> O?, @autoclosure p: () -> P?, @autoclosure q: () -> Q?, @autoclosure r: () -> R?, @autoclosure s: () -> S?, @autoclosure t: () -> T?, @autoclosure u: () -> U?, @autoclosure v: () -> V?) -> (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V)? { if let a = a, b = b(), c = c(), d = d(), e = e(), f = f(), g = g(), h = h(), i = i(), j = j(), k = k(), l = l(), m = m(), n = n(), o = o(), p = p(), q = q(), r = r(), s = s(), t = t(), u = u(), v = v() { return (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v) } return nil }
mit
2d45aa6aa7d577f6038a024193b72270
75.889571
709
0.414426
2.494626
false
false
false
false
darvin/Poker-Swift
Poker/GameViewController.swift
1
2134
// // GameViewController.swift // Poker // // Created by Sergey Klimov on 4/22/15. // Copyright (c) 2015 Sergey Klimov. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { let sceneData = try! NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe) let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
8f152657b4b81a7a05a506b1f393c424
29.927536
96
0.625586
5.690667
false
false
false
false
hikelee/hotel
Sources/Common/Models/User.swift
1
1353
import Vapor import Fluent import HTTP public final class User: RestModel { public static var entity: String { return "common_user" } public var id: Node? public var name: String? public var salt:String? public var password: String? public var title: String? public var exists: Bool = false //used in fluent public convenience init(node: Node, in context: Context) throws { try self.init(node:node) } public init(node: Node) throws { id = try? node.extract("id") title = try? node.extract("title") name = try? node.extract("name") salt = try? node.extract("salt") password = try? node.extract("password") } public func makeNode() throws -> Node { return try Node.init( node:[ "id": id, "title": title, "name": name, "salt": salt, "password": password, ] ) } public func validate(isCreate: Bool) throws ->[String:String] { var result:[String:String]=[:] if name?.isEmpty ?? true {result["name"] = "必填项"} if isCreate { if password?.isEmpty ?? true {result["password"] = "必填项"} } if title?.isEmpty ?? true {result["title"] = "必填项"} return result } }
mit
05d9cb0c13619c3a96babd556dab909d
27.404255
69
0.549064
4.211356
false
false
false
false
superman-coder/pakr
pakr/pakr/WebService/Authentication/Manager/GoogleAuth.swift
1
1493
// // GoogleAuth.swift // pakr // // Created by Huynh Quang Thao on 4/17/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation import UIKit import Google class GoogleAuth: SocialAuth { class var sharedInstance : GoogleAuth { struct Static { static var token : dispatch_once_t = 0 static var instance : GoogleAuth? = nil } dispatch_once(&Static.token) { Static.instance = GoogleAuth() } return Static.instance! } static func getInstance() -> GIDSignIn { GIDSignIn.sharedInstance().shouldFetchBasicProfile = true return GIDSignIn.sharedInstance() } static func isLogin() -> Bool { return getInstance().hasAuthInKeychain() } static func signOut() { getInstance().signOut() } static func getLoginedUser(googler: GIDGoogleUser) -> User! { let user = User(userId: "", role: Role.UserAuth, email: googler.profile.email, dateCreated: NSDate(), name: googler.profile.name, avatarUrl: googler.profile.imageURLWithDimension(120).absoluteString) return user } static func loginSuccess() { NSUserDefaults.standardUserDefaults().setLoginMechanism(LoginMechanism.GOOGLE) } static func isValidatedWithUrl(url: NSURL) -> Bool { return url.scheme.hasPrefix(NSBundle.mainBundle().bundleIdentifier!) || url.scheme.hasPrefix("com.googleusercontent.apps.") } }
apache-2.0
d3e5e3240ed5e6451d9a35d3abb4cab2
28.27451
207
0.645442
4.647975
false
false
false
false
Bunn/firefox-ios
Client/Frontend/Settings/SettingsContentViewController.swift
1
6041
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SnapKit import UIKit import WebKit let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild. private var TODOPageLoadErrorString = NSLocalizedString("Could not load page.", comment: "Error message that is shown in settings when there was a problem loading") /** * A controller that manages a single web view and provides a way for * the user to navigate back to Settings. */ class SettingsContentViewController: UIViewController, WKNavigationDelegate { let interstitialBackgroundColor: UIColor var settingsTitle: NSAttributedString? var url: URL! var timer: Timer? var isLoaded: Bool = false { didSet { if isLoaded { UIView.transition(from: interstitialView, to: settingsWebView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } fileprivate var isError: Bool = false { didSet { if isError { interstitialErrorView.isHidden = false UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView, duration: 0.5, options: .transitionCrossDissolve, completion: { finished in self.interstitialSpinnerView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } // The view shown while the content is loading in the background web view. fileprivate var interstitialView: UIView! fileprivate var interstitialSpinnerView: UIActivityIndicatorView! fileprivate var interstitialErrorView: UILabel! // The web view that displays content. var settingsWebView: WKWebView! fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) { if self.isLoaded { return } if timeout > 0 { self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(didTimeOut), userInfo: nil, repeats: false) } else { self.timer = nil } self.settingsWebView.load(PrivilegedRequest(url: url) as URLRequest) self.interstitialSpinnerView.startAnimating() } init(backgroundColor: UIColor = UIColor.Photon.White100, title: NSAttributedString? = nil) { interstitialBackgroundColor = backgroundColor settingsTitle = title super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // This background agrees with the web page background. // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor self.settingsWebView = makeWebView() view.addSubview(settingsWebView) self.settingsWebView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } // Destructuring let causes problems. let ret = makeInterstitialViews() self.interstitialView = ret.0 self.interstitialSpinnerView = ret.1 self.interstitialErrorView = ret.2 view.addSubview(interstitialView) self.interstitialView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } startLoading() } func makeWebView() -> WKWebView { let config = TabManager.makeWebViewConfig(isPrivate: true, blockPopups: true) let webView = WKWebView( frame: CGRect(width: 1, height: 1), configuration: config ) webView.allowsLinkPreview = false webView.navigationDelegate = self // This is not shown full-screen, use mobile UA webView.customUserAgent = UserAgent.mobileUserAgent() return webView } fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) { let view = UIView() // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor let spinner = UIActivityIndicatorView(style: .gray) view.addSubview(spinner) let error = UILabel() if let _ = settingsTitle { error.text = TODOPageLoadErrorString error.textColor = UIColor.theme.tableView.errorText error.textAlignment = .center } error.isHidden = true view.addSubview(error) spinner.snp.makeConstraints { make in make.center.equalTo(view) return } error.snp.makeConstraints { make in make.center.equalTo(view) make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) return } return (view, spinner, error) } @objc func didTimeOut() { self.timer = nil self.isError = true } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { didTimeOut() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.timer?.invalidate() self.timer = nil self.isLoaded = true } }
mpl-2.0
96a0e16f572b38b3717ac99dfde7d6b2
33.323864
164
0.634001
5.350753
false
false
false
false
allbto/ios-swiftility
Swiftility/Sources/Type Safety/Storyboard.swift
2
1710
// // Storyboard.swift // Swiftility // // Created by Allan Barbato on 10/21/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation import UIKit // MARK: - Storyboard extension UIStoryboard { public struct Name { var name: String var bundle: Bundle? public init(name: String, bundle: Bundle? = nil) { self.name = name self.bundle = bundle } } } extension UIStoryboard { public convenience init(name: UIStoryboard.Name) { self.init(name: name.name, bundle: name.bundle) } } // MARK: - FromStoryboard public protocol FromStoryboard { static var storyboardName: UIStoryboard.Name { get } } // MARK: - Type safe instantiate view controller extension UIStoryboard { public func instantiateInitialViewController<T: UIViewController>() -> T { guard let vc = self.instantiateInitialViewController() as? T else { fatalError("\(String(describing: T.self)) could not be instantiated because it was not found in storyboard: \(self)") } return vc } public func instantiateViewController<T: UIViewController>() -> T { var vc: UIViewController? = nil do { try ObjC.catchException { vc = self.instantiateViewController(withIdentifier: String(describing: T.self)) } } catch { vc = nil } guard let typedVc = vc as? T else { fatalError("\(String(describing: T.self)) could not be instantiated because it was not found in storyboard: \(self)") } return typedVc } }
mit
d91c096f6cbeefbeaf200811da19e01e
21.786667
129
0.597425
4.644022
false
false
false
false
FengDeng/SwiftNet
SwiftNetDemo/SwiftNetDemo/User.swift
1
593
// // File.swift // SwiftNetDemo // // Created by 邓锋 on 16/3/8. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation class User : ModelJSONType{ var username = "" var avatar_url = "" required init(){} static func from(json: AnyObject?) throws -> Self { guard let json = json as? [String:AnyObject] else{ throw NSError(domain: "json 解析出错", code: -1, userInfo: nil) } let user = User() user.avatar_url = (json["avatar_url"] as? String) ?? "" return autocast(user) } }
mit
8042adef8ae3bca504b7b52d8d96f64f
21.269231
71
0.569204
3.658228
false
false
false
false
jixuhui/HJPlayArchitecture
HJDemo/Steed/Task.swift
2
856
// // Task.swift // HJDemo // // Created by Hubbert on 15/11/14. // Copyright © 2015年 Hubbert. All rights reserved. // import Foundation class SDURLTask : NSObject{ var ID:String var reqType:String var reqURLPath:String var reqParameters:Dictionary<String,String> var operation:AFHTTPRequestOperation? override init() { ID = "" reqType = "" reqURLPath = "" reqParameters = Dictionary<String,String>(minimumCapacity: 5) super.init() } } class SDURLPageTask : SDURLTask { var pageIndex:Int var pageSize:Int var hasMoreData:Bool var pageIndexKey:String var pageSizeKey:String override init() { pageIndex = 0 pageSize = 20 hasMoreData = false pageIndexKey = "" pageSizeKey = "" super.init() } }
mit
c30d0efff1c4267036a1532a82fb3831
19.309524
69
0.608441
4.042654
false
false
false
false
kirayamato1989/KYPhotoBrowser
Demo/ViewController.swift
1
1499
// // ViewController.swift // KYPhotoBrowser // // Created by 郭帅 on 2016/11/8. // Copyright © 2016年 郭帅. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func tap(_ sender: Any) { let path1 = Bundle.main.path(forResource: "1", ofType: "jpg") let path2 = Bundle.main.path(forResource: "2", ofType: "jpg") let photoItems = [path1!, path2!].map { (path) -> KYPhotoItem in let item = KYPhotoItem(url: URL(fileURLWithPath: path), placeholder: nil, image: nil, des: nil) return item } let vc = KYPhotoBrowser(photos: photoItems, initialIndex: 1) vc.eventMonitor = { let event = $1 _ = $0 switch event { case .oneTap: print("单击了\(event.index)") break case .longPress: print("长按了\(event.index)") break case .displayPageChanged: print("图片改变\(event.index)") break default: break } } DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 2), execute: { self.present(vc, animated: true, completion: nil) }) } }
mit
0937b51268fdb6209ef35c1a4ff764d2
27.784314
107
0.532016
4.435045
false
false
false
false
DarrenKong/firefox-ios
ReadingList/ReadingListClient.swift
2
10292
/* 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 Alamofire enum ReadingListDeleteRecordResult { case success(ReadingListRecordResponse) case preconditionFailed(ReadingListResponse) case notFound(ReadingListResponse) case failure(ReadingListResponse) case error(NSError) } enum ReadingListGetRecordResult { case success(ReadingListRecordResponse) case notModified(ReadingListResponse) // TODO Should really call this NotModified for clarity case notFound(ReadingListResponse) case failure(ReadingListResponse) case error(NSError) } enum ReadingListGetAllRecordsResult { case success(ReadingListRecordsResponse) case notModified(ReadingListResponse) // TODO Should really call this NotModified for clarity case failure(ReadingListResponse) case error(NSError) } enum ReadingListPatchRecordResult { } enum ReadingListAddRecordResult { case success(ReadingListRecordResponse) case failure(ReadingListResponse) case conflict(ReadingListResponse) case error(NSError) } enum ReadingListBatchAddRecordsResult { case success(ReadingListBatchRecordResponse) case failure(ReadingListResponse) case error(NSError) } private let ReadingListClientUnknownError = NSError(domain: "org.mozilla.ios.Fennec.ReadingListClient", code: -1, userInfo: nil) class ReadingListClient { var serviceURL: URL var authenticator: ReadingListAuthenticator var articlesURL: URL! var articlesBaseURL: URL! var batchURL: URL! func getRecordWithGuid(_ guid: String, ifModifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListGetRecordResult) -> Void) { if let url = URL(string: guid, relativeTo: articlesBaseURL) { SessionManager.default.request(createRequest("GET", url, ifModifiedSince: ifModifiedSince)).responseJSON(options: [], completionHandler: { response -> Void in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 304: completion(.notModified(ReadingListResponse(response: response, json: json)!)) case 404: completion(.notFound(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func getRecordWithGuid(_ guid: String, completion: @escaping (ReadingListGetRecordResult) -> Void) { getRecordWithGuid(guid, ifModifiedSince: nil, completion: completion) } func getAllRecordsWithFetchSpec(_ fetchSpec: ReadingListFetchSpec, ifModifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListGetAllRecordsResult) -> Void) { if let url = fetchSpec.getURL(serviceURL: serviceURL, path: "/v1/articles") { SessionManager.default.request(createRequest("GET", url)).responseJSON(options: [], completionHandler: { response -> Void in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordsResponse(response: response, json: json)!)) case 304: completion(.notModified(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func getAllRecordsWithFetchSpec(_ fetchSpec: ReadingListFetchSpec, completion: @escaping (ReadingListGetAllRecordsResult) -> Void) { getAllRecordsWithFetchSpec(fetchSpec, ifModifiedSince: nil, completion: completion) } func patchRecord(_ record: ReadingListClientRecord, completion: (ReadingListPatchRecordResult) -> Void) { } func addRecord(_ record: ReadingListClientRecord, completion: @escaping (ReadingListAddRecordResult) -> Void) { SessionManager.default.request(createRequest("POST", articlesURL, json: record.json)).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200, 201: // TODO Should we have different results for these? Do we care about 200 vs 201? completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 303: completion(.conflict(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } /// Build the JSON body for POST /v1/batch { defaults: {}, request: [ {body: {} } ] } fileprivate func recordsToBatchJSON(_ records: [ReadingListClientRecord]) -> AnyObject { return [ "defaults": ["method": "POST", "path": "/v1/articles", "headers": ["Content-Type": "application/json"]], "requests": records.map { ["body": $0.json] } ] as NSDictionary } func batchAddRecords(_ records: [ReadingListClientRecord], completion: @escaping (ReadingListBatchAddRecordsResult) -> Void) { SessionManager.default.request(createRequest("POST", batchURL, json: recordsToBatchJSON(records))).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListBatchRecordResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } func deleteRecordWithGuid(_ guid: String, ifUnmodifiedSince: ReadingListTimestamp?, completion: @escaping (ReadingListDeleteRecordResult) -> Void) { if let url = URL(string: guid, relativeTo: articlesBaseURL) { SessionManager.default.request(createRequest("DELETE", url, ifUnmodifiedSince: ifUnmodifiedSince)).responseJSON(options: [], completionHandler: { response in if let json = response.result.value as? [String: Any], let response = response.response { switch response.statusCode { case 200: completion(.success(ReadingListRecordResponse(response: response, json: json)!)) case 412: completion(.preconditionFailed(ReadingListResponse(response: response, json: json)!)) case 404: completion(.notFound(ReadingListResponse(response: response, json: json)!)) default: completion(.failure(ReadingListResponse(response: response, json: json)!)) } } else { completion(.error(response.result.error as NSError? ?? ReadingListClientUnknownError)) } }) } else { // TODO ??? } } func deleteRecordWithGuid(_ guid: String, completion: @escaping (ReadingListDeleteRecordResult) -> Void) { deleteRecordWithGuid(guid, ifUnmodifiedSince: nil, completion: completion) } func createRequest(_ method: String, _ url: URL, ifUnmodifiedSince: ReadingListTimestamp? = nil, ifModifiedSince: ReadingListTimestamp? = nil, json: AnyObject? = nil) -> URLRequest { let request = NSMutableURLRequest(url: url) request.httpMethod = method if let ifUnmodifiedSince = ifUnmodifiedSince { request.setValue(String(ifUnmodifiedSince), forHTTPHeaderField: "If-Unmodified-Since") } if let ifModifiedSince = ifModifiedSince { request.setValue(String(ifModifiedSince), forHTTPHeaderField: "If-Modified-Since") } for (headerField, value) in authenticator.headers { request.setValue(value, forHTTPHeaderField: headerField) } request.addValue("application/json", forHTTPHeaderField: "Accept") if let json = json { request.addValue("application/json", forHTTPHeaderField: "Content-Type") do { request.httpBody = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) } catch _ { request.httpBody = nil } // TODO Handle errors here } return request as URLRequest } init(serviceURL: URL, authenticator: ReadingListAuthenticator) { self.serviceURL = serviceURL self.authenticator = authenticator self.articlesURL = URL(string: "/v1/articles", relativeTo: self.serviceURL) self.articlesBaseURL = URL(string: "/v1/articles/", relativeTo: self.serviceURL) self.batchURL = URL(string: "/v1/batch", relativeTo: self.serviceURL) } }
mpl-2.0
4eed3cb9d987754954b6c591d37481b8
47.777251
186
0.634376
5.587405
false
false
false
false
gokselkoksal/Lightning
Lightning/Sources/Components/StringMask.swift
1
1416
// // StringMask.swift // Lightning // // Created by Göksel Köksal on 20/12/2016. // Copyright © 2016 GK. All rights reserved. // import Foundation public final class StringMask { public let ranges: [NSRange] public let character: Character public init(ranges: [NSRange], character: Character = "*") { self.ranges = ranges self.character = character } public func mask(_ string: String) -> String { guard string.count > 0 else { return string } let stringRanges = ranges.compactMap { string.zap_rangeIntersection(with: $0) } func shouldMaskIndex(_ index: String.Index) -> Bool { for range in stringRanges { if range.contains(index) { return true } } return false } var result = "" var index = string.startIndex for char in string { result += String(shouldMaskIndex(index) ? character : char) index = string.index(after: index) } return result } } public struct StringMaskStorage { public var mask: StringMask { didSet { update() } } public var original: String? { didSet { update() } } public private(set) var masked: String? public init(mask: StringMask) { self.mask = mask } private mutating func update() { if let original = original { masked = mask.mask(original) } else { masked = nil } } }
mit
193ac5113cc1bf0858b323d3bfd68361
19.478261
83
0.611465
3.991525
false
false
false
false
wscqs/FMDemo-
FMDemo/Classes/Model/SaveMaterialsModel.swift
1
1411
// // SaveMaterialsModel.swift // // Created by mba on 17/2/23 // Copyright (c) . All rights reserved. // import Foundation import ObjectMapper public class SaveMaterialsModel: BaseModel { // MARK: Declaration for string constants to be used to decode and also serialize. private let kSaveMaterialsModelStateKey: String = "state" private let kSaveMaterialsModelMidKey: String = "mid" // MARK: Properties public var state: String? public var mid: String? // MARK: ObjectMapper Initalizers /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public required init?(map: Map) { super.init(map: map) } /** Map a JSON object to this class using ObjectMapper - parameter map: A mapping from ObjectMapper */ public override func mapping(map: Map) { super.mapping(map: map) state <- map[kSaveMaterialsModelStateKey] mid <- map[kSaveMaterialsModelMidKey] } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String: Any] { var dictionary: [String: Any] = [:] if let value = state { dictionary[kSaveMaterialsModelStateKey] = value } if let value = mid { dictionary[kSaveMaterialsModelMidKey] = value } return dictionary } }
apache-2.0
9a54c8db24055691e1afc00f6217978f
26.666667
84
0.700213
4.314985
false
false
false
false
mxcl/swift-package-manager
Sources/PackageLoading/ModuleMapGenerator.swift
1
7304
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Utility import PackageModel public let moduleMapFilename = "module.modulemap" /// A protocol for modules which might have a modulemap. protocol ModuleMapProtocol { var moduleMapPath: AbsolutePath { get } var moduleMapDirectory: AbsolutePath { get } } extension CModule: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return path } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } extension ClangModule: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return includeDir } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } /// A modulemap generator for clang modules. /// /// Modulemap is generated under the following rules provided it is not already present in include directory: /// /// * "include/foo/foo.h" exists and `foo` is the only directory under include directory. /// Generates: `umbrella header "/path/to/include/foo/foo.h"` /// * "include/foo.h" exists and include contains no other directory. /// Generates: `umbrella header "/path/to/include/foo.h"` /// * Otherwise in all other cases. /// Generates: `umbrella "path/to/include"` public struct ModuleMapGenerator { /// The clang module to operate on. private let module: ClangModule /// The file system to be used. private var fileSystem: FileSystem /// Stream on which warnings will be emitted. private let warningStream: OutputByteStream public init(for module: ClangModule, fileSystem: FileSystem = localFileSystem, warningStream: OutputByteStream = stdoutStream) { self.module = module self.fileSystem = fileSystem self.warningStream = warningStream } /// A link-declaration specifies a library or framework /// against which a program should be linked. /// More info: http://clang.llvm.org/docs/Modules.html#link-declaration /// A `library` modulemap style uses `link` flag for link-declaration where /// as a `framework` uses `link framework` flag and a framework module. public enum ModuleMapStyle { case library case framework /// Link declaration flag to be used in modulemap. var linkDeclFlag: String { switch self { case .library: return "link" case .framework: return "link framework" } } var moduleDeclQualifier: String? { switch self { case .library: return nil case .framework: return "framework" } } } public enum ModuleMapError: Swift.Error { case unsupportedIncludeLayoutForModule(String) } /// Create the synthesized module map, if necessary. /// Note: modulemap is not generated for test modules. // // FIXME: We recompute the generated modulemap's path when building swift // modules in `XccFlags(prefix: String)` there shouldn't be need to redo // this there but is difficult in current architecture. public mutating func generateModuleMap(inDir wd: AbsolutePath, modulemapStyle: ModuleMapStyle = .library) throws { // Don't generate modulemap for a Test module. guard !module.isTest else { return } ///Return if module map is already present guard !fileSystem.isFile(module.moduleMapPath) else { return } let includeDir = module.includeDir // Warn and return if no include directory. guard fileSystem.isDirectory(includeDir) else { warningStream <<< "warning: No include directory found for module '\(module.name)'. A library can not be imported without any public headers." warningStream.flush() return } let walked = try fileSystem.getDirectoryContents(includeDir).map{ includeDir.appending(component: $0) } let files = walked.filter{ fileSystem.isFile($0) && $0.suffix == ".h" } let dirs = walked.filter{ fileSystem.isDirectory($0) } let umbrellaHeaderFlat = includeDir.appending(component: module.c99name + ".h") if fileSystem.isFile(umbrellaHeaderFlat) { guard dirs.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule(module.name) } try createModuleMap(inDir: wd, type: .header(umbrellaHeaderFlat), modulemapStyle: modulemapStyle) return } diagnoseInvalidUmbrellaHeader(includeDir) let umbrellaHeader = includeDir.appending(components: module.c99name, module.c99name + ".h") if fileSystem.isFile(umbrellaHeader) { guard dirs.count == 1 && files.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule(module.name) } try createModuleMap(inDir: wd, type: .header(umbrellaHeader), modulemapStyle: modulemapStyle) return } diagnoseInvalidUmbrellaHeader(includeDir.appending(component: module.c99name)) try createModuleMap(inDir: wd, type: .directory(includeDir), modulemapStyle: modulemapStyle) } /// Warn user if in case module name and c99name are different and there is a /// `name.h` umbrella header. private func diagnoseInvalidUmbrellaHeader(_ path: AbsolutePath) { let umbrellaHeader = path.appending(component: module.c99name + ".h") let invalidUmbrellaHeader = path.appending(component: module.name + ".h") if module.c99name != module.name && fileSystem.isFile(invalidUmbrellaHeader) { warningStream <<< "warning: \(invalidUmbrellaHeader.asString) should be renamed to \(umbrellaHeader.asString) to be used as an umbrella header" warningStream.flush() } } private enum UmbrellaType { case header(AbsolutePath) case directory(AbsolutePath) } private mutating func createModuleMap(inDir wd: AbsolutePath, type: UmbrellaType, modulemapStyle: ModuleMapStyle) throws { let stream = BufferedOutputByteStream() if let qualifier = modulemapStyle.moduleDeclQualifier { stream <<< qualifier <<< " " } stream <<< "module \(module.c99name) {\n" switch type { case .header(let header): stream <<< " umbrella header \"\(header.asString)\"\n" case .directory(let path): stream <<< " umbrella \"\(path.asString)\"\n" } stream <<< " \(modulemapStyle.linkDeclFlag) \"\(module.c99name)\"\n" stream <<< " export *\n" stream <<< "}\n" // FIXME: This doesn't belong here. try fileSystem.createDirectory(wd, recursive: true) let file = wd.appending(component: moduleMapFilename) try fileSystem.writeFileContents(file, bytes: stream.bytes) } }
apache-2.0
03a7bdfd19eaa778afeacfdcdb1cd640
37.041667
155
0.662651
4.869333
false
false
false
false
benzguo/MusicKit
MusicKit/Accidental.swift
1
784
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation public enum Accidental: Float, CustomStringConvertible { case doubleFlat = -2 case flat = -1 case natural = 0 case sharp = 1 case doubleSharp = 2 public func description(_ stripNatural: Bool) -> String { switch self { case .natural: return stripNatural ? "" : description default: return description } } public var description: String { switch self { case .doubleFlat: return "𝄫" case .flat: return "♭" case .natural: return "♮" case .sharp: return "♯" case .doubleSharp: return "𝄪" } } }
mit
76224e9b0c5fffec751009b921601f5b
21.057143
61
0.522021
4.541176
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Views/FormerInputAccessoryView.swift
1
6225
// // FormerInputAccessoryView.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 8/30/17. // import UIKit import Former final class FormerInputAccessoryView: UIToolbar { private weak var former: Former? private weak var leftArrow: UIBarButtonItem! private weak var rightArrow: UIBarButtonItem! init(former: Former) { super.init(frame: CGRect(origin: CGPoint(), size: CGSize(width: 0, height: 44))) self.former = former configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update() { leftArrow.isEnabled = former?.canBecomeEditingPrevious() ?? false rightArrow.isEnabled = former?.canBecomeEditingNext() ?? false } private func configure() { barTintColor = .white tintColor = .logoTint clipsToBounds = true isUserInteractionEnabled = true let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let leftArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 105)!, target: self, action: #selector(FormerInputAccessoryView.handleBackButton)) let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) space.width = 20 let rightArrow = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem(rawValue: 106)!, target: self, action: #selector(FormerInputAccessoryView.handleForwardButton)) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FormerInputAccessoryView.handleDoneButton)) let rightSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) setItems([leftArrow, space, rightArrow, flexible, doneButton, rightSpace], animated: false) self.leftArrow = leftArrow self.rightArrow = rightArrow let topLineView = UIView() topLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) topLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(topLineView) let bottomLineView = UIView() bottomLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) bottomLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomLineView) let leftLineView = UIView() leftLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) leftLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(leftLineView) let rightLineView = UIView() rightLineView.backgroundColor = UIColor(white: 0, alpha: 0.3) rightLineView.translatesAutoresizingMaskIntoConstraints = false addSubview(rightLineView) let constraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[topLine(0.5)]", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:[bottomLine(0.5)]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-10-[leftLine]-10-|", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-10-[rightLine]-10-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[topLine]-0-|", options: [], metrics: nil, views: ["topLine": topLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[bottomLine]-0-|", options: [], metrics: nil, views: ["bottomLine": bottomLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-84-[leftLine(0.5)]", options: [], metrics: nil, views: ["leftLine": leftLineView] ), NSLayoutConstraint.constraints( withVisualFormat: "H:[rightLine(0.5)]-74-|", options: [], metrics: nil, views: ["rightLine": rightLineView] ) ] addConstraints(constraints.flatMap { $0 }) } @objc private dynamic func handleBackButton() { update() former?.becomeEditingPrevious() } @objc private dynamic func handleForwardButton() { update() former?.becomeEditingNext() } @objc private dynamic func handleDoneButton() { former?.endEditing() } }
mit
7a0bc9ccd271f7d8ecfa19fb23b0427e
39.154839
179
0.623715
5.37943
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsServices/Biometry/LabelContent/BiometryLabelContentInteractor.swift
1
947
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import PlatformUIKit import RxRelay import RxSwift final class BiometryLabelContentInteractor: LabelContentInteracting { typealias InteractionState = LabelContent.State.Interaction let stateRelay = BehaviorRelay<InteractionState>(value: .loading) var state: Observable<InteractionState> { stateRelay.asObservable() } // MARK: - Private Accessors init(biometryProviding: BiometryProviding) { var title = LocalizationConstants.Settings.enableTouchID switch biometryProviding.supportedBiometricsType { case .faceID: title = LocalizationConstants.Settings.enableFaceID case .touchID: title = LocalizationConstants.Settings.enableTouchID case .none: break } stateRelay.accept(.loaded(next: .init(text: title))) } }
lgpl-3.0
519becb56b03edf1ff1d7af35f531d3a
28.5625
69
0.712474
5.375
false
false
false
false
juliensagot/JSNavigationController
Example/Example/SecondViewController.swift
1
6594
import AppKit import JSNavigationController private extension Selector { static let pushToThirdVC = #selector(SecondViewController.pushToThirdViewController(_:)) static let popVC = #selector(SecondViewController.popVC) } class SecondViewController: NSViewController, JSNavigationBarViewControllerProvider { weak var navigationController: JSNavigationController? fileprivate let navigationBarVC = BasicNavigationBarViewController() // MARK: - Initializers init() { super.init(nibName: "SecondViewController", bundle: Bundle.main) } required init?(coder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false view.wantsLayer = true if let view = view as? NSVisualEffectView { view.material = .mediumLight } } override func viewDidAppear() { super.viewDidAppear() view.superview?.addConstraints(viewConstraints()) // NavigationBar navigationBarVC.backButton?.action = .popVC navigationBarVC.backButton?.target = self navigationBarVC.titleLabel?.stringValue = "Second VC" navigationBarVC.nextButton?.action = .pushToThirdVC navigationBarVC.nextButton?.target = self } override func viewDidDisappear() { view.superview?.removeConstraints(viewConstraints()) } // MARK: - Layout fileprivate func viewConstraints() -> [NSLayoutConstraint] { let left = NSLayoutConstraint( item: view, attribute: .left, relatedBy: .equal, toItem: view.superview, attribute: .left, multiplier: 1.0, constant: 0.0 ) let right = NSLayoutConstraint( item: view, attribute: .right, relatedBy: .equal, toItem: view.superview, attribute: .right, multiplier: 1.0, constant: 0.0 ) let top = NSLayoutConstraint( item: view, attribute: .top, relatedBy: .equal, toItem: view.superview, attribute: .top, multiplier: 1.0, constant: 0.0 ) let bottom = NSLayoutConstraint( item: view, attribute: .bottom, relatedBy: .equal, toItem: view.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0 ) return [left, right, top, bottom] } // MARK: - NavigationBar func navigationBarViewController() -> NSViewController { return navigationBarVC } // MARK: - Actions @IBAction func pushToThirdViewController(_: AnyObject?) { let thirdVC = ThirdViewController() navigationController?.push(viewController: thirdVC, animated: true) } @IBAction func pushWithCustomAnimations(_: AnyObject?) { let thirdVC = ThirdViewController() let contentAnimation: AnimationBlock = { [weak self] (_, _) in let viewBounds = self?.view.bounds ?? .zero let slideToBottomTransform = CATransform3DMakeTranslation(0, -viewBounds.height, 0) let slideToBottomAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToBottomAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToBottomAnimation.toValue = NSValue(caTransform3D: slideToBottomTransform) slideToBottomAnimation.duration = 0.25 slideToBottomAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToBottomAnimation.fillMode = CAMediaTimingFillMode.forwards slideToBottomAnimation.isRemovedOnCompletion = false let slideFromTopTransform = CATransform3DMakeTranslation(0, viewBounds.height, 0) let slideFromTopAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideFromTopAnimation.fromValue = NSValue(caTransform3D: slideFromTopTransform) slideFromTopAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideFromTopAnimation.duration = 0.25 slideFromTopAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideFromTopAnimation.fillMode = CAMediaTimingFillMode.forwards slideFromTopAnimation.isRemovedOnCompletion = false return ([slideToBottomAnimation], [slideFromTopAnimation]) } let navigationBarAnimation: AnimationBlock = { [weak self] (_, _) in let viewBounds = self?.navigationController?.navigationBarController?.contentView?.bounds ?? .zero let slideToBottomTransform = CATransform3DMakeTranslation(0, -viewBounds.height / 2, 0) let slideToBottomAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideToBottomAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) slideToBottomAnimation.toValue = NSValue(caTransform3D: slideToBottomTransform) slideToBottomAnimation.duration = 0.25 slideToBottomAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideToBottomAnimation.fillMode = CAMediaTimingFillMode.forwards slideToBottomAnimation.isRemovedOnCompletion = false let slideFromTopTransform = CATransform3DMakeTranslation(0, viewBounds.height / 2, 0) let slideFromTopAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform)) slideFromTopAnimation.fromValue = NSValue(caTransform3D: slideFromTopTransform) slideFromTopAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity) slideFromTopAnimation.duration = 0.25 slideFromTopAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) slideFromTopAnimation.fillMode = CAMediaTimingFillMode.forwards slideFromTopAnimation.isRemovedOnCompletion = false let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeInAnimation.fromValue = 0.0 fadeInAnimation.toValue = 1.0 fadeInAnimation.duration = 0.25 fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards fadeInAnimation.isRemovedOnCompletion = false let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity)) fadeOutAnimation.fromValue = 1.0 fadeOutAnimation.toValue = 0.0 fadeOutAnimation.duration = 0.25 fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards fadeOutAnimation.isRemovedOnCompletion = false return ([fadeOutAnimation, slideToBottomAnimation], [fadeInAnimation, slideFromTopAnimation]) } navigationController?.push(viewController: thirdVC, contentAnimation: contentAnimation, navigationBarAnimation: navigationBarAnimation) } @IBAction func popToRootVC(_: AnyObject?) { navigationController?.popToRootViewController(animated: true) } @objc func popVC() { navigationController?.popViewController(animated: true) } }
mit
c73b220085a2b5e5b09cdb9c56d07525
40.734177
137
0.788596
4.785196
false
false
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/View(视图和控制器)/ComposeView(发微博)/CFComposeView.swift
1
10369
// // CFComposeView.swift // 花菜微博 // // Created by 花菜Caiflower on 2017/1/7. // Copyright © 2017年 花菜ChrisCai. All rights reserved. // import UIKit import pop /// 按钮大小 fileprivate let kComposeTypeButtonSize = CGSize(width: 100, height: 100) /// 列间距 fileprivate let composeButtonColumnMargin: CGFloat = (UIScreen.main.cf_screenWidth - 3 * kComposeTypeButtonSize.width) * 0.25 /// 行间距 fileprivate let composeButtonRowMargin: CGFloat = (224 - 2 * kComposeTypeButtonSize.width) * 0.5 class CFComposeView: UIView { var completion: ((_ className: String?) -> ())? @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var scorllView: UIScrollView! @IBOutlet weak var returnButton: UIButton! /// 返回按钮中心点X约束 @IBOutlet weak var returnButtonCenterXContraint: NSLayoutConstraint! /// 关闭按钮中心点X约束 @IBOutlet weak var closeButtonCenterXContraint: NSLayoutConstraint! /// 按钮数据数组 fileprivate let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "className": "CFComposeTypeViewController"], ["imageName": "tabbar_compose_photo", "title": "照片/视频"], ["imageName": "tabbar_compose_weibo", "title": "长微博"], ["imageName": "tabbar_compose_lbs", "title": "签到"], ["imageName": "tabbar_compose_review", "title": "点评"], ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"], ["imageName": "tabbar_compose_friend", "title": "好友圈"], ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"], ["imageName": "tabbar_compose_music", "title": "音乐"], ["imageName": "tabbar_compose_shooting", "title": "拍摄"] ] class func composeView() -> CFComposeView { let nib = UINib(nibName: "CFComposeView", bundle: nil) let composeView = nib.instantiate(withOwner: nil, options: nil)[0] as! CFComposeView return composeView } override func awakeFromNib() { frame = UIScreen.main.bounds // 初始化子视图 setupOwerViews() } /// 显示发微博视图 func show(completion: @escaping (_ className: String?) -> ()) { self.completion = completion CFMainViewController.shared.view .addSubview(self) // 添加动画 showCurrentView() } /// 关闭按钮点击事件 @IBAction func dismissAction() { // 隐藏当前显示的所有按钮 hideButtons() } /// 返回按钮点击事件 @IBAction func returnButtonAction() { // 还原返回按钮和关闭按钮的位置 returnButtonCenterXContraint.constant = 0 closeButtonCenterXContraint.constant = 0 scorllView.setContentOffset(CGPoint.zero, animated: true) UIView.animate(withDuration: 0.25, animations: { self.layoutIfNeeded() self.returnButton.alpha = 0 }) } } // MARK: - 动画相关扩展 fileprivate extension CFComposeView { // MARK: - 显示动画 func showCurrentView() { // 创建动画 let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) // 设置属性 anim.fromValue = 0 anim.toValue = 1 anim.duration = 0.5 // 添加动画 pop_add(anim, forKey: nil) // 按钮动画 showButtons() } // MARK: - 显示按钮动画 func showButtons() { // 获取做动画的按钮 let v = scorllView.subviews[0] for (i , btn) in v.subviews.enumerated() { // 创建弹力动画 let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) anim.fromValue = btn.center.y + 400 anim.toValue = btn.center.y // 弹力速度 anim.springSpeed = 8 // 弹力系数 0 ~ 20 默认是4 anim.springBounciness = 8 // 动画开始时间 anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025 // 添加动画 btn.layer.pop_add(anim, forKey: nil) } } // MARK: - 隐藏按钮动画 func hideButtons() { // 获取当前显示的子视图 let page = Int(scorllView.contentOffset.x / scorllView.bounds.width) if page < scorllView.subviews.count { let v = scorllView.subviews[page] // 倒数遍历 for (i, btn) in v.subviews.enumerated().reversed() { // 创建动画 let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY) anim.fromValue = btn.center.y anim.toValue = btn.center.y + 400 anim.springBounciness = 8 anim.springSpeed = 8 anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025 btn.layer.pop_add(anim, forKey: nil) // 监听第0个动画完成 if i == 0 { anim.completionBlock = { (_ , _) in // 隐藏当前视图 self.hideCurrentView() } } } } } // MARK: - 隐藏当前视图 func hideCurrentView() { let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) anim.toValue = 0 anim.fromValue = 1 anim.duration = 0.25 pop_add(anim, forKey: nil) // 监听动画完成 anim.completionBlock = { (_, _) in // 从父视图移除 self.removeFromSuperview() } } } fileprivate extension CFComposeView { func setupOwerViews() { // 强制布局 layoutIfNeeded() let rect = scorllView.bounds // 添加子控件 for i in 0..<2 { let v = UIView() v.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0) addButtons(view: v, index: i * 6) scorllView.addSubview(v) } // 配置scorllView scorllView.contentSize = CGSize(width: rect.width * 2, height: 0) scorllView.showsVerticalScrollIndicator = false scorllView.showsHorizontalScrollIndicator = false scorllView.bounces = false scorllView.isScrollEnabled = false } func addButtons(view: UIView, index: Int) { // 添加子控件 // 每次添加按钮的个数 let onceAddCount = 6 // 每行显示的按钮个数 let numberOfCountInColumn = 3 for i in index..<index + onceAddCount { // 越界结束循环 if i >= buttonsInfo.count { break } let dict = buttonsInfo[i] guard let imageName = dict["imageName"], let title = dict["title"] else { continue } // 创建按钮 let btn = CFComposeTypeButton(imageName: imageName, title: title) // 添加父视图 view.addSubview(btn) // 添加点击事件 if let actionName = dict["actionName"] { btn.addTarget(self, action: Selector(actionName), for: .touchUpInside); } else { btn.addTarget(self, action: #selector(btnClick(selectButton:)), for: .touchUpInside) } btn.className = dict["className"] } // 设置frame for (i , btn) in view.subviews.enumerated() { // 计算行/列 let row = i / numberOfCountInColumn let col = i % 3 // 根据行列计算x/y let x = CGFloat(col + 1) * composeButtonColumnMargin + CGFloat(col) * kComposeTypeButtonSize.width let y: CGFloat = CGFloat(row) * (kComposeTypeButtonSize.height + composeButtonRowMargin) btn.frame = CGRect(origin: CGPoint(x: x, y: y), size: kComposeTypeButtonSize) } } } // MARK: - 各个按钮的点击事件 fileprivate extension CFComposeView { @objc func btnClick(selectButton:CFComposeTypeButton) { print("点击了按钮") guard let view = selectButton.superview else { return } // 被选中的放大, 未被选中的缩小 for (i, button) in view.subviews.enumerated() { // 创建缩放动画 let scaleAnim = POPBasicAnimation(propertyNamed: kPOPViewScaleXY) // 设置缩放系数 let scale = (button == selectButton) ? 1.5 : 0.2 scaleAnim?.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale)) scaleAnim?.duration = 0.5 button.pop_add(scaleAnim, forKey: nil) // 创建透明度动画 let alphaAnim = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnim?.toValue = 0.2 alphaAnim?.duration = 0.5 button.pop_add(alphaAnim, forKey: nil) // 监听动画完成 if i == 0 { alphaAnim?.completionBlock = { (_, _) in print("动画完毕,显示需要展示的控制器") self.completion?(selectButton.className) } } } } @objc func clickMore() { // 更新scorllView偏移量 scorllView.setContentOffset(CGPoint(x: scorllView.bounds.width, y: 0), animated: true) // 更新返回按钮和关闭按钮的位置 self.returnButtonCenterXContraint.constant -= UIScreen.main.cf_screenWidth / 6 self.closeButtonCenterXContraint.constant += UIScreen.main.cf_screenWidth / 6 // 添加动画效果显示返回按钮 UIView.animate(withDuration: 0.25) { self.layoutIfNeeded() self.returnButton.alpha = 1 } } }
apache-2.0
4a718ae053ca434842a1c97cdeeb7c6f
32.473684
131
0.54109
4.694882
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
Team UI/Browser/Browser/HtmlManager.swift
1
3719
// // Regex.swift // Browser // // Created by Brian Mairhörmann on 04.11.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import Foundation class RegexForSech { func findSechTags(inString string : String) -> [String]{ let pattern = "</?search-[^>]*>" let regex = makeRegEx(withPattern: pattern) for item in getStringArrayWithRegex(string, regex: regex){ print(item) } return getStringArrayWithRegex(string, regex: regex) } func isSechSectionClosing(inString string : String) -> Bool { let pattern = "</search-section" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechLinkClosing(inString string : String) -> Bool { let pattern = "</search-link" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechSection(inString string : String) -> Bool { let pattern = "<search-section" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func isSechLink(inString string : String) -> Bool { let pattern = "<search-link" let regex = makeRegEx(withPattern: pattern) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil } func getAttributes(inString string : String) -> [String: String]{ // Attributes: topic, type, mediaType, provider, licence let attributeNames = ["topic", "type", "mediaType", "provider", "licence"] var attributes = [String: String]() for attributeName in attributeNames { let regex = makeRegEx(withPattern: attributeName) let range = NSMakeRange(0, string.characters.count) if regex.firstMatchInString(string, options: NSMatchingOptions(), range: range) != nil { let regexAttribute = makeRegEx(withPattern: "(?<=\(attributeName)=\")([#-~ !§°`´äöüÄÖÜß]*)(?=\")") let match = getStringArrayWithRegex(string, regex: regexAttribute) if (match.isEmpty != true){ attributes[attributeName] = match[0] } }else{ attributes[attributeName] = "" } } return attributes } // Private Methods //################################################################################################# private func makeRegEx(withPattern pattern : String) -> NSRegularExpression{ let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) return regex } private func getStringArrayWithRegex(string : String, regex : NSRegularExpression) -> [String]{ let range = NSMakeRange(0, string.characters.count) let matches = regex.matchesInString(string, options: NSMatchingOptions(), range: range) return matches.map { let range = $0.range return (string as NSString).substringWithRange(range) } } }
mit
4cb49e852cf6cda526bc4a1b070e8781
36.08
115
0.586188
5.043537
false
false
false
false
sora0077/iTunesMusic
Demo/Views/GenresViewController.swift
1
2118
// // GenresViewController.swift // iTunesMusic // // Created by 林達也 on 2016/06/26. // Copyright © 2016年 jp.sora0077. All rights reserved. // import UIKit import iTunesMusic import RxSwift import SnapKit class GenresViewController: UIViewController { fileprivate let genres = Model.Genres() fileprivate let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = .clear tableView.tableFooterView = UIView() tableView.snp.makeConstraints { make in make.edges.equalTo(0) } genres.changes .subscribe(tableView.rx.itemUpdates()) .addDisposableTo(disposeBag) action(genres.refresh) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: true) } } } extension GenresViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return genres.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.selectionStyle = .blue cell.textLabel?.text = genres[indexPath.row].name cell.textLabel?.textColor = .white cell.textLabel?.backgroundColor = .clear cell.backgroundColor = UIColor(hex: 0x20201e, alpha: 0.95) return cell } } extension GenresViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = RssViewController(genre: genres[indexPath.row]) navigationController?.pushViewController(vc, animated: true) } }
mit
71dde619ad3d0098004195e80c970e92
27.5
100
0.682314
5.069712
false
false
false
false
stripe/stripe-ios
Tests/Tests/ConfirmButtonTests.swift
1
2845
// // ConfirmButtonTests.swift // StripeiOS Tests // // Created by Ramon Torres on 10/6/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import XCTest @testable@_spi(STP) import Stripe @testable@_spi(STP) import StripeCore @testable@_spi(STP) import StripePaymentSheet @testable@_spi(STP) import StripePayments @testable@_spi(STP) import StripePaymentsUI class ConfirmButtonTests: XCTestCase { func testBuyButtonShouldAutomaticallyAdjustItsForegroundColor() { let testCases: [(background: UIColor, foreground: UIColor)] = [ // Dark backgrounds (background: .systemBlue, foreground: .white), (background: .black, foreground: .white), // Light backgrounds ( background: UIColor(red: 1.0, green: 0.87, blue: 0.98, alpha: 1.0), foreground: .black ), ( background: UIColor(red: 1.0, green: 0.89, blue: 0.35, alpha: 1.0), foreground: .black ), ] for (backgroundColor, expectedForeground) in testCases { let button = ConfirmButton.BuyButton() button.tintColor = backgroundColor button.update( status: .enabled, callToAction: .pay(amount: 900, currency: "usd"), animated: false ) XCTAssertEqual( // Test against `.cgColor` because any color set as `.backgroundColor` // will be automatically wrapped in `UIDynamicModifiedColor` (private subclass) by iOS. button.backgroundColor?.cgColor, backgroundColor.cgColor ) XCTAssertEqual( button.foregroundColor, expectedForeground, "The foreground color should contrast with the background color" ) } } func testUpdateShouldCallTheCompletionBlock() { let sut = ConfirmButton( style: .stripe, callToAction: .pay(amount: 1000, currency: "usd"), didTap: {} ) let expectation = XCTestExpectation(description: "Should call the completion block") sut.update(state: .disabled, animated: false) { expectation.fulfill() } wait(for: [expectation], timeout: 1) } func testUpdateShouldCallTheCompletionBlockWhenAnimated() { let sut = ConfirmButton( style: .stripe, callToAction: .pay(amount: 1000, currency: "usd"), didTap: {} ) let expectation = XCTestExpectation(description: "Should call the completion block") sut.update(state: .disabled, animated: true) { expectation.fulfill() } wait(for: [expectation], timeout: 3) } }
mit
45b40ff51ec1274328aba23926227e46
30.252747
103
0.578059
4.963351
false
true
false
false
dehlen/TRexAboutWindowController
AboutWindowFramework/AboutWindowControllerConfig.swift
1
2822
import Cocoa public struct AboutWindowControllerConfig { private(set) var name: String = "" private(set) var version: String = "" private(set) var copyright: NSAttributedString = NSAttributedString() private(set) var credits: NSAttributedString = NSAttributedString() private(set) var creditsButtonTitle: String = "Acknowledgments" private(set) var eula: NSAttributedString = NSAttributedString() private(set) var eulaButtonTitle: String = "License Agreement" private(set) var url: URL? = nil private(set) var hasShadow: Bool = true private var appName: String { return Bundle.main.appName ?? "" } private var appVersion: String { let version = Bundle.main.buildVersionNumber ?? "" let shortVersion = Bundle.main.releaseVersionNumber ?? "" return "Version \(shortVersion) (Build \(version))" } private var appCopyright: String { return Bundle.main.copyright ?? "" } private var appCredits: NSAttributedString { guard let creditsRtf = Bundle.main.url(forResource: "Credits", withExtension: "rtf") else { return NSAttributedString(string: "") } guard let attributedAppCredits = try? NSMutableAttributedString(url: creditsRtf, options: [:], documentAttributes: nil) else { return NSAttributedString(string: "") } let color = NSColor.textColor attributedAppCredits.apply(color: color) return attributedAppCredits } private var appEula: NSAttributedString { guard let eulaRtf = Bundle.main.url(forResource: "EULA", withExtension: "rtf") else { return NSAttributedString(string: "") } guard let attributedAppEula = try? NSMutableAttributedString(url: eulaRtf, options: [:], documentAttributes: nil) else { return NSAttributedString(string: "") } let color = NSColor.textColor attributedAppEula.apply(color: color) return attributedAppEula } public init(name: String? = nil, version: String? = nil, copyright: NSAttributedString? = nil, credits: NSAttributedString? = nil, creditsButtonTitle: String = "Acknowledgments", eula: NSAttributedString? = nil, eulaButtonTitle: String = "License Agreement", url: URL? = nil, hasShadow: Bool = true) { self.name = name ?? appName self.version = version ?? appVersion self.copyright = copyright ?? AttributedStringHandler.copyright(with: appCopyright) self.credits = credits ?? appCredits self.creditsButtonTitle = creditsButtonTitle self.eula = eula ?? appEula self.eulaButtonTitle = eulaButtonTitle self.url = url self.hasShadow = hasShadow } }
mit
0a3d93c0ba1c0a80e2b24d612942be2a
39.898551
305
0.653437
5.021352
false
false
false
false
Fig-leaves/curation
RSSReader/RadioViewController.swift
1
9171
// // RadioViewController.swift // RSSReader // // Created by 伊藤総一郎 on 9/8/15. // Copyright (c) 2015 susieyy. All rights reserved. // import UIKit class RadioViewController: UIViewController , UITableViewDataSource, UITableViewDelegate, AdstirMraidViewDelegate { var items = NSMutableArray() var refresh: UIRefreshControl! final let API_KEY = Constants.youtube.API_KEY final let WORD:String = Constants.youtube.RADIO var loading = false var nextPageToken:NSString! @IBOutlet weak var table: UITableView! var inter: AdstirInterstitial? = nil var click_count = 0; var adView: AdstirMraidView? = nil deinit { // デリゲートを解放します。解放を忘れるとクラッシュする可能性があります。 self.adView?.delegate = nil // 広告ビューを解放します。 self.adView = nil } override func viewDidLoad() { super.viewDidLoad() self.title = "さまぁ〜ず" self.inter = AdstirInterstitial() self.inter!.media = Constants.inter_ad.id self.inter!.spot = Constants.inter_ad.spot self.inter!.load() // 広告表示位置: タブバーの下でセンタリング、広告サイズ: 320,50 の場合 let originY = self.view.frame.height let originX = (self.view.frame.size.width - kAdstirAdSize320x50.size.width) / 2 let adView = AdstirMraidView(adSize: kAdstirAdSize320x50, origin: CGPointMake(originX, originY - 100), media: Constants.ad.id, spot:Constants.ad.spot) // リフレッシュ秒数を設定します。 adView.intervalTime = 5 // デリゲートを設定します。 adView.delegate = self // 広告ビューを親ビューに追加します。 self.view.addSubview(adView) self.adView = adView // NavigationControllerのタイトルバー(NavigationBar)の色の変更 self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() // NavigationConrtollerの文字カラーの変更 self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // NavigationControllerのNavigationItemの色 self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() items = NSMutableArray() let nibName = UINib(nibName: "YoutubeTableViewCell", bundle:nil) table.registerNib(nibName, forCellReuseIdentifier: "Cell") table.delegate = self table.dataSource = self self.refresh = UIRefreshControl() self.refresh.attributedTitle = NSAttributedString(string: Constants.message.UPDATING) self.refresh.addTarget(self, action: "viewWillAppear:", forControlEvents: UIControlEvents.ValueChanged) self.table.addSubview(refresh) // NADViewクラスを生成 // nadView = NADView(frame: CGRect(x: Constants.frame.X, // y: Constants.frame.Y, // width: Constants.frame.WIDTH, // height: Constants.frame.HEIGHT)) // // 広告枠のapikey/spotidを設定(必須) // nadView.setNendID(Constants.nend_id.API_ID, spotID: Constants.nend_id.SPOT_ID) // // nendSDKログ出力の設定(任意) // nadView.isOutputLog = true // // delegateを受けるオブジェクトを指定(必須) // nadView.delegate = self // 読み込み開始(必須) // nadView.load() // self.view.addSubview(nadView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) items = NSMutableArray() request(false) self.refresh?.endRefreshing() } func request(next: Bool) { let radioWord:String! = WORD.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) var urlString:String if(next) { urlString = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&q=\(radioWord)&part=snippet&pageToken=\(self.nextPageToken)&maxResults=20&orderby=published" } else { urlString = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&q=\(radioWord)&part=snippet&maxResults=20&orderby=published" } let url:NSURL! = NSURL(string:urlString) let urlRequest:NSURLRequest = NSURLRequest(URL:url) var data:NSData var dic: NSDictionary = NSDictionary() do { data = try NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil) dic = try NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary } catch { print("ERROR") } if(dic.objectForKey("nextPageToken") != nil) { self.nextPageToken = dic.objectForKey("nextPageToken") as! String } else { self.nextPageToken = nil } let itemsArray: NSArray = dic.objectForKey("items") as! NSArray var content: Dictionary<String, String> = ["" : ""] itemsArray.enumerateObjectsUsingBlock({ object, index, stop in let snippet: NSDictionary = object.objectForKey("snippet") as! NSDictionary let ids: NSDictionary = object.objectForKey("id") as! NSDictionary let thumbnails: NSDictionary = snippet.objectForKey("thumbnails") as! NSDictionary let resolution: NSDictionary = thumbnails.objectForKey("high") as! NSDictionary let imageUrl: NSString = resolution.objectForKey("url") as! String if(ids["kind"] as! String == "youtube#video") { content[Constants.article_data.VIDEO_ID] = ids[Constants.article_data.VIDEO_ID] as? String content[Constants.article_data.TITLE] = snippet.objectForKey(Constants.article_data.TITLE) as? String content[Constants.article_data.IMAGE_URL] = imageUrl as String content[Constants.article_data.PUBLISH_AT] = snippet.objectForKey("publishedAt") as? String self.items.addObject(content) } }) self.table.reloadData() self.loading = false } func scrollViewDidScroll(scrollView: UIScrollView) { if(self.table.contentOffset.y >= (self.table.contentSize.height - self.table.bounds.size.height) && self.nextPageToken != nil && loading == false) { loading = true SVProgressHUD.showWithStatus(Constants.message.LOADING) dispatch_async(dispatch_get_main_queue(), { () -> Void in if(self.nextPageToken == nil) { } else { self.request(true) SVProgressHUD.dismiss() } }) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.table.dequeueReusableCellWithIdentifier("Cell") as! YoutubeTableViewCell let item = self.items[indexPath.row] as! NSDictionary let date = item[Constants.article_data.PUBLISH_AT] as! String let length = date.characters.count var startIndex:String.Index var endIndex:String.Index startIndex = date.startIndex.advancedBy(0) endIndex = date.startIndex.advancedBy(length - 14) let newString = date.substringWithRange(Range(start:startIndex ,end:endIndex)) cell.movieTitleLabel.text = item[Constants.article_data.TITLE] as? String cell.movieTitleLabel.numberOfLines = 0; cell.movieTitleLabel.sizeToFit() cell.dateLabel.text = newString let imgURL: NSURL? = NSURL(string: item[Constants.article_data.IMAGE_URL] as! String) cell.movieImage.setImageWithURL(imgURL) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as! NSDictionary let con = KINWebBrowserViewController() let youtube_url = "https://www.youtube.com/watch?v=" + (item[Constants.article_data.VIDEO_ID] as! String) let URL = NSURL(string: youtube_url) con.loadURL(URL) if click_count % Constants.inter_ad.click_count == 1 { self.inter!.showTypeB(self) } click_count++; self.navigationController?.pushViewController(con, animated: true) } }
mit
ae797b85f0b8f014bb2f9abbfe025f4f
38.687783
177
0.632767
4.546916
false
false
false
false
nkirby/Humber
Humber/_src/Table View Cells/EditOverviewAddCell.swift
1
999
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class EditOverviewAddCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = "" } // ======================================================= internal func render() { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let titleAttrString = NSAttributedString(string: "Add", attributes: [ NSForegroundColorAttributeName: Theme.color(type: .TintColor), NSFontAttributeName: Theme.font(type: .Bold(14.0)) ]) self.titleLabel.attributedText = titleAttrString } }
mit
96fc3d742ce51e54adf5834f6bafe3cb
25.289474
77
0.49049
6.128834
false
false
false
false
chanricle/NCKTextView
LEOTextView/Classes/LEOTextUtil.swift
3
5479
// // LEOTextUtil.swift // LEOTextView // // Created by Leonardo Hammer on 21/04/2017. // // import UIKit class LEOTextUtil: NSObject { static let markdownUnorderedListRegularExpression = try! NSRegularExpression(pattern: "^[-*••∙●] ", options: .caseInsensitive) static let markdownOrderedListRegularExpression = try! NSRegularExpression(pattern: "^\\d*\\. ", options: .caseInsensitive) static let markdownOrderedListAfterItemsRegularExpression = try! NSRegularExpression(pattern: "\\n\\d*\\. ", options: .caseInsensitive) class func isReturn(_ text: String) -> Bool { if text == "\n" { return true } else { return false } } class func isBackspace(_ text: String) -> Bool { if text == "" { return true } else { return false } } class func isSelectedTextWithTextView(_ textView: UITextView) -> Bool { let length = textView.selectedRange.length return length > 0 } class func objectLineAndIndexWithString(_ string: String, location: Int) -> (String, Int) { let ns_string = NSString(string: string) var objectIndex: Int = 0 var objectLine = ns_string.substring(to: location) let textSplits = objectLine.components(separatedBy: "\n") if textSplits.count > 0 { let currentObjectLine = textSplits[textSplits.count - 1] objectIndex = objectLine.length() - currentObjectLine.length() objectLine = currentObjectLine } return (objectLine, objectIndex) } class func objectLineWithString(_ string: String, location: Int) -> String { return objectLineAndIndexWithString(string, location: location).0 } class func lineEndIndexWithString(_ string: String, location: Int) -> Int { let remainText: NSString = NSString(string: string).substring(from: location) as NSString var nextLineBreakLocation = remainText.range(of: "\n").location nextLineBreakLocation = (nextLineBreakLocation == NSNotFound) ? string.length() : nextLineBreakLocation + location return nextLineBreakLocation } class func paragraphRangeOfString(_ string: String, location: Int) -> NSRange { let startLocation = objectLineAndIndexWithString(string, location: location).1 let endLocation = lineEndIndexWithString(string, location: location) return NSMakeRange(startLocation, endLocation - startLocation) } class func currentParagraphStringOfString(_ string: String, location: Int) -> String { return NSString(string: string).substring(with: paragraphRangeOfString(string, location: location)) } /** Just return ListTypes. */ class func paragraphTypeWithObjectLine(_ objectLine: String) -> LEOInputParagraphType { let objectLineRange = NSMakeRange(0, objectLine.length()) let unorderedListMatches = LEOTextUtil.markdownUnorderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange) if unorderedListMatches.count > 0 { let firstChar = NSString(string: objectLine).substring(to: 1) if firstChar == "-" { return .dashedList } else { return .bulletedList } } let orderedListMatches = LEOTextUtil.markdownOrderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange) if orderedListMatches.count > 0 { return .numberedList } return .body } class func isListParagraph(_ objectLine: String) -> Bool { let objectLineRange = NSMakeRange(0, objectLine.length()) let isCurrentOrderedList = LEOTextUtil.markdownOrderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange).count > 0 if isCurrentOrderedList { return true } let isCurrentUnorderedList = LEOTextUtil.markdownUnorderedListRegularExpression.matches(in: objectLine, options: [], range: objectLineRange).count > 0 if isCurrentUnorderedList { return true } return false } class func isBoldFont(_ font: UIFont, boldFontName: String) -> Bool { if font.fontName == boldFontName { return true } let keywords = ["bold", "medium"] // At chinese language: PingFangSC-Light is normal, PingFangSC-Regular is bold return isSpecialFont(font, keywords: keywords) } class func isItalicFont(_ font: UIFont, italicFontName: String) -> Bool { if font.fontName == italicFontName { return true } let keywords = ["italic"] return isSpecialFont(font, keywords: keywords) } class func isSpecialFont(_ font: UIFont, keywords: [String]) -> Bool { let fontName = NSString(string: font.fontName) for keyword in keywords { if fontName.range(of: keyword, options: .caseInsensitive).location != NSNotFound { return true } } return false } class func keyboardWindow() -> UIWindow? { var keyboardWin: UIWindow? UIApplication.shared.windows.forEach { if String(describing: type(of: $0)) == "UITextEffectsWindow" { keyboardWin = $0 return } } return keyboardWin } }
mit
cac140cf1f6bf6a948ce5e7f0f845768
32.163636
158
0.637543
5.037753
false
false
false
false
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-010/Smashtag/Smashtag/Twitter Swift 2.0/User.swift
4
2887
// // User.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // container to hold data about a Twitter user public struct User: CustomStringConvertible { public let screenName: String public let name: String public let profileImageURL: NSURL? public let verified: Bool public let id: String? public var description: String { let v = verified ? " ✅" : ""; return "@\(screenName) (\(name))\(v)" } // MARK: - Private Implementation init?(data: NSDictionary?) { if let nameFromData = data?.valueForKeyPath(TwitterKey.Name) as? String { if let screenNameFromData = data?.valueForKeyPath(TwitterKey.ScreenName) as? String { name = nameFromData screenName = screenNameFromData id = data?.valueForKeyPath(TwitterKey.ID) as? String verified = data?.valueForKeyPath(TwitterKey.Verified)?.boolValue ?? false if let urlString = data?.valueForKeyPath(TwitterKey.ProfileImageURL) as? String { profileImageURL = NSURL(string: urlString) } else { profileImageURL = nil } // failable initializers are required to initialize all properties before returning failure // (this is probably just a (temporary?) limitation of the implementation of Swift) // however, it appears that (sometimes) you can "return" in the case of success like this // and it avoids the warning (although "return" is sort of weird in an initializer) // (this seems to work even though all the properties are NOT initialized for the "return nil" below) // hopefully in future versions of Swift this will all not be an issue // because you'll be allowed to fail without initializing all properties? return } } // it is possible we will get here without all properties being initialized // hopefully that won't cause a problem even though the compiler does not complain? :) return nil } var asPropertyList: AnyObject { var dictionary = Dictionary<String,String>() dictionary[TwitterKey.Name] = self.name dictionary[TwitterKey.ScreenName] = self.screenName dictionary[TwitterKey.ID] = self.id dictionary[TwitterKey.Verified] = verified ? "YES" : "NO" dictionary[TwitterKey.ProfileImageURL] = profileImageURL?.absoluteString return dictionary } struct TwitterKey { static let Name = "name" static let ScreenName = "screen_name" static let ID = "id_str" static let Verified = "verified" static let ProfileImageURL = "profile_image_url" } }
apache-2.0
dac07b0ebd9e75c6dbcb6ccfe7b58aac
40.811594
117
0.632582
5.124334
false
false
false
false
kousun12/RxSwift
RxSwift/Subjects/BehaviorSubject.swift
4
3908
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a value that changes over time. Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , LockOwnerType , SynchronizedOnType , SynchronizedSubscribeType , SynchronizedUnsubscribeType , Disposable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType let _lock = NSRecursiveLock() // state private var _disposed = false private var _value: Element private var _observers = Bag<AnyObserver<Element>>() private var _stoppedEvent: Event<Element>? /** Indicates whether the subject has been disposed. */ public var disposed: Bool { return _disposed } /** Initializes a new instance of the subject that caches its last value and starts with the specified value. - parameter value: Initial value sent to observers when no other value has been received by the subject yet. */ public init(value: Element) { _value = value } /** Gets the current value or throws an error. - returns: Latest value. */ public func value() throws -> Element { _lock.lock(); defer { _lock.unlock() } // { if _disposed { throw RxError.DisposedError } if let error = _stoppedEvent?.error { // intentionally throw exception throw error } else { return _value } //} } /** Notifies all subscribed observers about next event. - parameter event: Event to send to the observers. */ public func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { if _stoppedEvent != nil || _disposed { return } switch event { case .Next(let value): _value = value case .Error, .Completed: _stoppedEvent = event } _observers.on(event) } /** Subscribes an observer to the subject. - parameter observer: Observer to subscribe to the subject. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable { return synchronizedSubscribe(observer) } func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { if _disposed { observer.on(.Error(RxError.DisposedError)) return NopDisposable.instance } if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return NopDisposable.instance } let key = _observers.insert(observer.asObserver()) observer.on(.Next(_value)) return SubscriptionDisposable(owner: self, key: key) } func _synchronized_unsubscribe(disposeKey: DisposeKey) { if _disposed { return } _ = _observers.removeKey(disposeKey) } /** Returns observer interface for subject. */ public func asObserver() -> BehaviorSubject<Element> { return self } /** Unsubscribe all observers and release resources. */ public func dispose() { _lock.performLocked { _disposed = true _observers.removeAll() _stoppedEvent = nil } } }
mit
3f02ad87d0f86b1613217e7e852b5f58
25.234899
112
0.591863
5.075325
false
false
false
false
karivalkama/Agricola-Scripture-Editor
TranslationEditor/NotesPost.swift
1
2088
// // NotesPost.swift // TranslationEditor // // Created by Mikko Hilpinen on 17.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // A single post is one persons contribution to a certain notes thread final class NotesPost: Storable { // ATTRIBUTES ------------ static let type = "post" static let PROPERTY_THREAD = "thread" static let PROPERTY_CREATED = "created" let threadId: String let creatorId: String let created: TimeInterval let originalCommentId: String? var content: String // COMP. PROPERTIES -------- static var idIndexMap: IdIndexMap { return NotesThread.idIndexMap.makeChildPath(parentPathName: PROPERTY_THREAD, childPath: [PROPERTY_CREATED]) } var idProperties: [Any] { return [threadId, created] } var properties: [String : PropertyValue] { return ["creator": creatorId.value, "content": content.value, "original_comment": originalCommentId.value] } var collectionId: String { return ParagraphNotes.collectionId(fromId: threadId) } var chapterIndex: Int { return ParagraphNotes.chapterIndex(fromId: threadId) } var noteId: String { return NotesThread.noteId(fromId: threadId) } var threadCreated: TimeInterval { return NotesThread.created(fromId: threadId) } // INIT -------------------- init(threadId: String, creatorId: String, content: String, created: TimeInterval = Date().timeIntervalSince1970, originalCommentId: String? = nil) { self.threadId = threadId self.creatorId = creatorId self.content = content self.created = created self.originalCommentId = originalCommentId } static func create(from properties: PropertySet, withId id: Id) -> NotesPost { return NotesPost(threadId: id[PROPERTY_THREAD].string(), creatorId: properties["creator"].string(), content: properties["content"].string(), created: id[PROPERTY_CREATED].time(), originalCommentId: properties["original_comment"].string()) } // IMPLEMENTED METHODS ---- func update(with properties: PropertySet) { if let content = properties["content"].string { self.content = content } } }
mit
ece246b5b198863a96b78aa3ee701489
27.202703
240
0.720172
3.843462
false
false
false
false
danpratt/On-the-Map
On the Map/OTMMapDataModel.swift
1
882
// // OTMMapDataModel.swift // On the Map // // Created by Daniel Pratt on 4/6/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation import MapKit // MARK: - OTMMapDataModel Class class OTMMapDataModel { // MARK: - Properties // Map Data var mapData: [OTMMapData]? = nil // Update info var mapPinDataUpdated: Bool = false var listDataUpdated: Bool = false // User specific info var userID: String? = nil var firstName: String? = nil var lastName: String? = nil var usersExistingObjectID: String? = nil var userLocation: CLLocationCoordinate2D? // MARK: Shared Instance class func mapModel() -> OTMMapDataModel { struct Singleton { static var sharedInstance = OTMMapDataModel() } return Singleton.sharedInstance } }
mit
ebb00e5a4a576935fe6f2db096b4227c
19.488372
57
0.628831
4.449495
false
false
false
false
melbrng/TrackApp
Track/Track/Footprint.swift
1
930
// // Footprint.swift // Track // // Created by Melissa Boring on 8/9/16. // Copyright © 2016 melbo. All rights reserved. // import MapKit class Footprint: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var image: UIImage? var title: String? var subtitle: String? var trackUID: String? var footprintUID: String? var imagePath: String? init(coordinate: CLLocationCoordinate2D, image: UIImage) { self.coordinate = coordinate self.image = image } init(coordinate: CLLocationCoordinate2D, trackUID: String, footUID: String, title: String, subtitle: String, image: UIImage, imagePath: String) { self.coordinate = coordinate self.trackUID = trackUID self.footprintUID = footUID self.title = title self.subtitle = subtitle self.image = image self.imagePath = imagePath } }
mit
bd2a8dcec8cced02ec0f218fef2aa96b
22.820513
149
0.649085
4.20362
false
false
false
false
niunaruto/DeDaoAppSwift
DeDaoSwift/DeDaoSwift/Home/Model/DDHomeSubjectModel.swift
1
1230
// // DDHomeSubjectModel.swift // DeDaoSwift // // Created by niuting on 2017/3/6. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit import ObjectMapper class DDHomeSubjectListModel: Mappable { var m_type = 0 var m_title = "" var m_url = "" var m_img = "" var m_isSubscribe = 0 var m_id = "" var m_from = "" required init?(map : Map) { } func mapping(map:Map) { m_type <- map["m_type"] m_id <- map["m_id"] m_from <- map["m_from"] m_title <- map["m_title"] m_url <- map["m_url"] m_img <- map["m_img"] m_isSubscribe <- map["m_isSubscribe"] } } class DDHomeSubjectModel: Mappable { var count = 0 var title = "" var rightTitle = "" var list : Array<DDHomeSubjectListModel>? required init?(map : Map) { } func mapping(map:Map) { count <- map["count"] title <- map["title"] rightTitle <- map["rightTitle"] list <- map["list"] } }
mit
eac83139af51d0b5fb25c6594398b2bc
18.790323
56
0.445803
3.846395
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift
20
6484
// // CombineLatest+Collection.swift // RxSwift // // Created by Krunoslav Zaher on 8/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - parameter resultSelector: Function to invoke whenever any of the sources produces an element. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func combineLatest<Collection: Swift.Collection>(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable<Element> where Collection.Element: ObservableType { return CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) } /** Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) - returns: An observable sequence containing the result of combining elements of the sources. */ public static func combineLatest<Collection: Swift.Collection>(_ collection: Collection) -> Observable<[Element]> where Collection.Element: ObservableType, Collection.Element.Element == Element { return CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) } } final private class CombineLatestCollectionTypeSink<Collection: Swift.Collection, Observer: ObserverType> : Sink<Observer> where Collection.Element: ObservableConvertibleType { typealias Result = Observer.Element typealias Parent = CombineLatestCollectionType<Collection, Result> typealias SourceElement = Collection.Element.Element let _parent: Parent let _lock = RecursiveLock() // state var _numberOfValues = 0 var _values: [SourceElement?] var _isDone: [Bool] var _numberOfDone = 0 var _subscriptions: [SingleAssignmentDisposable] init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent self._values = [SourceElement?](repeating: nil, count: parent._count) self._isDone = [Bool](repeating: false, count: parent._count) self._subscriptions = [SingleAssignmentDisposable]() self._subscriptions.reserveCapacity(parent._count) for _ in 0 ..< parent._count { self._subscriptions.append(SingleAssignmentDisposable()) } super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceElement>, atIndex: Int) { self._lock.lock(); defer { self._lock.unlock() } // { switch event { case .next(let element): if self._values[atIndex] == nil { self._numberOfValues += 1 } self._values[atIndex] = element if self._numberOfValues < self._parent._count { let numberOfOthersThatAreDone = self._numberOfDone - (self._isDone[atIndex] ? 1 : 0) if numberOfOthersThatAreDone == self._parent._count - 1 { self.forwardOn(.completed) self.dispose() } return } do { let result = try self._parent._resultSelector(self._values.map { $0! }) self.forwardOn(.next(result)) } catch let error { self.forwardOn(.error(error)) self.dispose() } case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: if self._isDone[atIndex] { return } self._isDone[atIndex] = true self._numberOfDone += 1 if self._numberOfDone == self._parent._count { self.forwardOn(.completed) self.dispose() } else { self._subscriptions[atIndex].dispose() } } // } } func run() -> Disposable { var j = 0 for i in self._parent._sources { let index = j let source = i.asObservable() let disposable = source.subscribe(AnyObserver { event in self.on(event, atIndex: index) }) self._subscriptions[j].setDisposable(disposable) j += 1 } if self._parent._sources.isEmpty { do { let result = try self._parent._resultSelector([]) self.forwardOn(.next(result)) self.forwardOn(.completed) self.dispose() } catch let error { self.forwardOn(.error(error)) self.dispose() } } return Disposables.create(_subscriptions) } } final private class CombineLatestCollectionType<Collection: Swift.Collection, Result>: Producer<Result> where Collection.Element: ObservableConvertibleType { typealias ResultSelector = ([Collection.Element.Element]) throws -> Result let _sources: Collection let _resultSelector: ResultSelector let _count: Int init(sources: Collection, resultSelector: @escaping ResultSelector) { self._sources = sources self._resultSelector = resultSelector self._count = self._sources.count } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
2370bf30ca4a7063e7c374a013aafda8
38.054217
191
0.595249
5.480135
false
true
false
false
gregomni/swift
test/Generics/minimal_conformances_compare_concrete.swift
3
1738
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on -disable-requirement-machine-concrete-contraction -dump-requirement-machine 2>&1 | %FileCheck %s --check-prefix=RULE protocol P {} class Base : P {} class Derived : Base {} struct G<X> {} // CHECK-LABEL: ExtensionDecl line={{.*}} base=G // CHECK-NEXT: Generic signature: <X where X == Derived> extension G where X : Base, X : P, X == Derived {} // RULE: + superclass: τ_0_0 Base // RULE: + conforms_to: τ_0_0 P // RULE: + same_type: τ_0_0 Derived // RULE: Rewrite system: { // RULE-NEXT: - [P].[P] => [P] [permanent] // RULE-NEXT: - τ_0_0.[superclass: Base] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[P] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[concrete: Derived] => τ_0_0 [explicit] // RULE-NEXT: - τ_0_0.[layout: _NativeClass] => τ_0_0 // RULE-NEXT: - τ_0_0.[superclass: Derived] => τ_0_0 // RULE-NEXT: - τ_0_0.[concrete: Derived : P] => τ_0_0 // RULE-NEXT: - τ_0_0.[concrete: Base : P] => τ_0_0 // RULE-NEXT: } // Notes: // // - concrete contraction kills the 'X : P' requirement before building the // rewrite system so this test passes trivially. // // - without concrete contraction, we used to hit a problem where the sort // in the minimal conformances algorithm would hit the unordered concrete // conformances [concrete: Derived : P] vs [concrete: Base : P].
apache-2.0
f41e9c4f8725acc5ff59f89b368d9501
43.153846
231
0.67577
3.100901
false
false
false
false
semiroot/SwiftyConstraints
Examples/iOS/iOS/MarginViewController.swift
1
2128
// // MarginViewController.swift // iOS // // Created by Hansmartin Geiser on 16/04/17. // Copyright © 2017 Hansmartin Geiser. All rights reserved. // import UIKit import SwiftyConstraints class MarginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Margin" view.backgroundColor = .white navigationController?.navigationBar.isTranslucent = false let label = UILabel() label.text = "There is no special margin functionality as of yet" label.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) label.layer.cornerRadius = 5 label.numberOfLines = 0 label.textAlignment = .center label.clipsToBounds = true let box1 = SCView(); box1.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1); box1.layer.cornerRadius = 5 let box2 = SCView(); box2.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15); box2.layer.cornerRadius = 5 let box3 = SCView(); box3.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2); box3.layer.cornerRadius = 5 let helper = SCView() swiftyConstraints() .attach(label) .top(20) .right(20) .left(20) .stackTop() // Equidistant (by fixed space) tripplets with one helper view (I know, helper views, but at least it's not html tables) .attach(helper) .top(20) .right(20).left() // You could also write left().widthOfSuperview(1, -20) .execute({ (view) in view.swiftyConstraints() .attach(box1) .top() .bottom() .widthOfSuperview(0.333, -20) .heightFromWidth() .left(20) .stackLeft() .attach(box2) .top() .bottom() .widthOfSuperview(0.333, -20) .heightFromWidth() .left(20) .stackLeft() .attach(box3) .top() .bottom() .widthOfSuperview(0.333, -20) .heightFromWidth() .left(20) }) } }
mit
d97c525ba985ef30aa149f9f9c88cb9c
26.986842
126
0.576399
4.028409
false
false
false
false
hyperoslo/Orchestra
Example/OrchestraDemo/OrchestraDemo/Sources/Models/Developer.swift
1
1043
import Foundation struct Developer { var id: Int var name: String var imageURL: NSURL var githubURL: NSURL // MARK: - Initializers init(id: Int, name: String, imageURL: NSURL, githubURL: NSURL) { self.id = id self.name = name self.imageURL = imageURL self.githubURL = githubURL } // MARK: - Factory static var developers: [Developer] { return [ Developer(id: 0, name: "Christoffer Winterkvist", imageURL: NSURL(string: "https://avatars2.githubusercontent.com/u/57446?v=3&s=460")!, githubURL: NSURL(string: "https://github.com/zenangst")!), Developer(id: 0, name: "Ramon Gilabert", imageURL: NSURL(string: "https://avatars1.githubusercontent.com/u/6138120?v=3&s=460")!, githubURL: NSURL(string: "https://github.com/RamonGilabert")!), Developer(id: 0, name: "Vadym Markov", imageURL: NSURL(string: "https://avatars2.githubusercontent.com/u/10529867?v=3&s=460")!, githubURL: NSURL(string: "https://github.com/vadymmarkov")!) ] } }
mit
5d219bb936af4ca6b1bd7cb257428a69
30.606061
96
0.651007
3.442244
false
false
false
false
yangyueguang/MyCocoaPods
CarryOn/XUIKit.swift
1
4341
// import UIKit @IBDesignable open class XButton: UIButton { private var titleSize = CGSize.zero private var imageSize = CGSize.zero @IBInspectable open var direction: Int = 0 @IBInspectable open var interval: CGFloat = 0 override open func titleRect(forContentRect contentRect: CGRect) -> CGRect { guard shouldLayout(contentRect) else { return super.titleRect(forContentRect: contentRect) } var targetRect:CGRect = CGRect.zero switch direction % 4 { case 0: targetRect = CGRect(x: (contentRect.width - titleSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2 + imageSize.height + interval, width: titleSize.width, height: titleSize.height) case 1: targetRect = CGRect(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2, y: (contentRect.height - titleSize.height)/2, width: titleSize.width, height: titleSize.height) case 2: targetRect = CGRect(x: (contentRect.width - titleSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2, width: titleSize.width, height: titleSize.height) default: targetRect = CGRect(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2 + imageSize.width + interval, y: (contentRect.height - titleSize.height)/2, width: titleSize.width, height: titleSize.height) } return targetRect } override open func imageRect(forContentRect contentRect: CGRect) -> CGRect { guard shouldLayout(contentRect) else { return super.imageRect(forContentRect: contentRect) } var targetRect:CGRect = CGRect.zero switch direction % 4 { case 0: targetRect = CGRect.init(x: (contentRect.width - imageSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2, width: imageSize.width, height: imageSize.height) case 1: targetRect = CGRect.init(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2 + titleSize.width + interval, y: (contentRect.height - imageSize.height)/2, width: imageSize.width, height: imageSize.height) case 2: targetRect = CGRect.init(x: (contentRect.width - imageSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2 + titleSize.height + interval, width: imageSize.width, height: imageSize.height) default: targetRect = CGRect.init(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2, y: (contentRect.height - imageSize.height)/2, width: imageSize.width, height: imageSize.height) } return targetRect } private func shouldLayout(_ contentRect:CGRect) -> Bool { guard subviews.count > 1, let image = currentImage,let _ = currentTitle,let titleL = titleLabel,let _ = imageView else { return false } let titleFitSize = titleL.sizeThatFits(contentRect.size) titleL.numberOfLines = 0 titleL.textAlignment = NSTextAlignment.center switch direction % 4 { case 1,3: imageSize.width = min(min(contentRect.height, contentRect.width - 20 - interval),image.size.width) imageSize.height = image.size.height * imageSize.width / image.size.width titleSize.width = max(min(contentRect.width - imageSize.width - interval, titleFitSize.width), 20) titleSize.height = contentRect.height default: titleSize.height = max(min(contentRect.height - image.size.height - interval, titleFitSize.height), 20) titleSize.width = min(contentRect.width, titleFitSize.width) imageSize.height = min(contentRect.height - titleFitSize.height, image.size.height) imageSize.width = image.size.width * imageSize.height / image.size.height } return true } } @IBDesignable open class holdLabel: UILabel { @IBInspectable open var placeholder: String = "" { didSet { text = placeholder } } override open var text: String? { didSet { if text?.isEmpty ?? true && !placeholder.isEmpty { self.text = placeholder } } } }
mit
a8f01c2ccce5df1686e202852bbf7a03
50.070588
236
0.656991
4.531315
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/NotificationCenterDetachmentRule.swift
2
3027
// // NotificationCenterDetachmentRule.swift // SwiftLint // // Created by Marcelo Fabri on 01/15/17. // Copyright © 2017 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct NotificationCenterDetachmentRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "notification_center_detachment", name: "Notification Center Detachment", description: "An object should only remove itself as an observer in `deinit`.", nonTriggeringExamples: NotificationCenterDetachmentRuleExamples.nonTriggeringExamples, triggeringExamples: NotificationCenterDetachmentRuleExamples.triggeringExamples ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .class else { return [] } return violationOffsets(file: file, dictionary: dictionary).map { offset in StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: offset)) } } func violationOffsets(file: File, dictionary: [String: SourceKitRepresentable]) -> [Int] { return dictionary.substructure.flatMap { subDict -> [Int] in guard let kindString = subDict.kind, let kind = SwiftExpressionKind(rawValue: kindString) else { return [] } // complete detachment is allowed on `deinit` if kind == .other, SwiftDeclarationKind(rawValue: kindString) == .functionMethodInstance, subDict.name == "deinit" { return [] } if kind == .call, subDict.name == methodName, parameterIsSelf(dictionary: subDict, file: file), let offset = subDict.offset { return [offset] } return violationOffsets(file: file, dictionary: subDict) } } private var methodName = "NotificationCenter.default.removeObserver" private func parameterIsSelf(dictionary: [String: SourceKitRepresentable], file: File) -> Bool { guard let bodyOffset = dictionary.bodyOffset, let bodyLength = dictionary.bodyLength else { return false } let range = NSRange(location: bodyOffset, length: bodyLength) let tokens = file.syntaxMap.tokens(inByteRange: range) let types = tokens.flatMap { SyntaxKind(rawValue: $0.type) } guard types == [.keyword], let token = tokens.first else { return false } let body = file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length) return body == "self" } }
mit
54106aed2f29322063d8238e4843c950
36.358025
107
0.630535
5.374778
false
false
false
false
nextcloud/ios
iOSClient/More/NCMore.swift
1
18979
// // NCMore.swift // Nextcloud // // Created by Marino Faggiana on 03/04/17. // Copyright © 2017 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // 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 UIKit import NextcloudKit import MarqueeLabel class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var labelQuota: UILabel! @IBOutlet weak var labelQuotaExternalSite: UILabel! @IBOutlet weak var progressQuota: UIProgressView! @IBOutlet weak var viewQuota: UIView! var functionMenu: [NKExternalSite] = [] var externalSiteMenu: [NKExternalSite] = [] var settingsMenu: [NKExternalSite] = [] var quotaMenu: [NKExternalSite] = [] let appDelegate = UIApplication.shared.delegate as! AppDelegate let defaultCornerRadius: CGFloat = 10.0 var tabAccount: tableAccount? // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = NSLocalizedString("_more_", comment: "") view.backgroundColor = .systemGroupedBackground tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = .systemGroupedBackground tableView.register(UINib(nibName: "NCMoreUserCell", bundle: nil), forCellReuseIdentifier: "userCell") // create tap gesture recognizer let tapQuota = UITapGestureRecognizer(target: self, action: #selector(tapLabelQuotaExternalSite)) labelQuotaExternalSite.isUserInteractionEnabled = true labelQuotaExternalSite.addGestureRecognizer(tapQuota) // Notification NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setGroupeAppreance() appDelegate.activeViewController = self loadItems() tableView.reloadData() } // MARK: - NotificationCenter @objc func initialize() { loadItems() } // MARK: - func loadItems() { var item = NKExternalSite() var quota: String = "" // Clear functionMenu.removeAll() externalSiteMenu.removeAll() settingsMenu.removeAll() quotaMenu.removeAll() labelQuotaExternalSite.text = "" progressQuota.progressTintColor = NCBrandColor.shared.brandElement // ITEM : Transfer item = NKExternalSite() item.name = "_transfers_" item.icon = "arrow.left.arrow.right" item.url = "segueTransfers" functionMenu.append(item) // ITEM : Recent item = NKExternalSite() item.name = "_recent_" item.icon = "recent" item.url = "segueRecent" functionMenu.append(item) // ITEM : Notification item = NKExternalSite() item.name = "_notification_" item.icon = "bell" item.url = "segueNotification" functionMenu.append(item) // ITEM : Activity item = NKExternalSite() item.name = "_activity_" item.icon = "bolt" item.url = "segueActivity" functionMenu.append(item) // ITEM : Shares let isFilesSharingEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesFileSharingApiEnabled, exists: false) if isFilesSharingEnabled { item = NKExternalSite() item.name = "_list_shares_" item.icon = "share" item.url = "segueShares" functionMenu.append(item) } // ITEM : Offline item = NKExternalSite() item.name = "_manage_file_offline_" item.icon = "tray.and.arrow.down" item.url = "segueOffline" functionMenu.append(item) // ITEM : Scan item = NKExternalSite() item.name = "_scanned_images_" item.icon = "scan" item.url = "openStoryboardNCScan" functionMenu.append(item) // ITEM : Trash let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor) if serverVersionMajor >= NCGlobal.shared.nextcloudVersion15 { item = NKExternalSite() item.name = "_trash_view_" item.icon = "trash" item.url = "segueTrash" functionMenu.append(item) } // ITEM : Settings item = NKExternalSite() item.name = "_settings_" item.icon = "gear" item.url = "segueSettings" settingsMenu.append(item) // ITEM: Test API /* if NCUtility.shared.isSimulator() { item = NKExternalSite() item.name = "Test API" item.icon = "swift" item.url = "test" settingsMenu.append(item) } */ if quotaMenu.count > 0 { let item = quotaMenu[0] labelQuotaExternalSite.text = item.name } // Display Name user & Quota if let activeAccount = NCManageDatabase.shared.getActiveAccount() { self.tabAccount = activeAccount if activeAccount.quotaRelative > 0 { progressQuota.progress = Float(activeAccount.quotaRelative) / 100 } else { progressQuota.progress = 0 } switch activeAccount.quotaTotal { case -1: quota = "0" case -2: quota = NSLocalizedString("_quota_space_unknown_", comment: "") case -3: quota = NSLocalizedString("_quota_space_unlimited_", comment: "") default: quota = CCUtility.transformedSize(activeAccount.quotaTotal) } let quotaUsed: String = CCUtility.transformedSize(activeAccount.quotaUsed) labelQuota.text = String.localizedStringWithFormat(NSLocalizedString("_quota_using_", comment: ""), quotaUsed, quota) } // ITEM : External if NCBrandOptions.shared.disable_more_external_site == false { if let externalSites = NCManageDatabase.shared.getAllExternalSites(account: appDelegate.account) { for externalSite in externalSites { if (externalSite.name != "" && externalSite.url != ""), let urlEncoded = externalSite.url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { item = NKExternalSite() item.name = externalSite.name item.url = urlEncoded item.icon = "network" if externalSite.type == "settings" { item.icon = "gear" } externalSiteMenu.append(item) } } } } } // MARK: - Action @objc func tapLabelQuotaExternalSite() { if quotaMenu.count > 0 { let item = quotaMenu[0] let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb browserWebVC.urlBase = item.url browserWebVC.isHiddenButtonExit = true self.navigationController?.pushViewController(browserWebVC, animated: true) self.navigationController?.navigationBar.isHidden = false } } @objc func tapImageLogoManageAccount() { let controller = CCManageAccount() self.navigationController?.pushViewController(controller, animated: true) } // MARK: - func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 75 } else { return NCGlobal.shared.heightCellSettings } } func numberOfSections(in tableView: UITableView) -> Int { if externalSiteMenu.count == 0 { return 3 } else { return 4 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 10 } else { return 20 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var cont = 0 if section == 0 { cont = tabAccount == nil ? 0 : 1 } else if section == 1 { // Menu Normal cont = functionMenu.count } else { switch numberOfSections(in: tableView) { case 3: // Menu Settings if section == 2 { cont = settingsMenu.count } case 4: // Menu External Site if section == 2 { cont = externalSiteMenu.count } // Menu Settings if section == 3 { cont = settingsMenu.count } default: cont = 0 } } return cont } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var item = NKExternalSite() // change color selection and disclosure indicator let selectionColor: UIView = UIView() if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! NCMoreUserCell cell.avatar.image = nil cell.icon.image = nil cell.status.text = "" cell.displayName.text = "" if let account = tabAccount { cell.avatar.image = NCUtility.shared.loadUserImage( for: account.user, displayName: account.displayName, userBaseUrl: appDelegate) if account.alias == "" { cell.displayName?.text = account.displayName } else { cell.displayName?.text = account.displayName + " (" + account.alias + ")" } cell.displayName.textColor = .label } cell.selectedBackgroundView = selectionColor cell.backgroundColor = .secondarySystemGroupedBackground cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator if NCManageDatabase.shared.getCapabilitiesServerBool(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false) { if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) { let status = NCUtility.shared.getUserStatus(userIcon: account.userStatusIcon, userStatus: account.userStatusStatus, userMessage: account.userStatusMessage) cell.icon.image = status.onlineStatus cell.status.text = status.statusMessage cell.status.textColor = .label cell.status.trailingBuffer = cell.status.frame.width if cell.status.labelShouldScroll() { cell.status.tapToScroll = true } else { cell.status.tapToScroll = false } } } cell.layer.cornerRadius = defaultCornerRadius cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner, .layerMaxXMaxYCorner, .layerMinXMaxYCorner] return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CCCellMore // Menu Normal if indexPath.section == 1 { item = functionMenu[indexPath.row] } // Menu External Site if numberOfSections(in: tableView) == 4 && indexPath.section == 2 { item = externalSiteMenu[indexPath.row] } // Menu Settings if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) { item = settingsMenu[indexPath.row] } cell.imageIcon?.image = NCUtility.shared.loadImage(named: item.icon) cell.labelText?.text = NSLocalizedString(item.name, comment: "") cell.labelText.textColor = .label cell.selectedBackgroundView = selectionColor cell.backgroundColor = .secondarySystemGroupedBackground cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator cell.separator.backgroundColor = .separator cell.separatorHeigth.constant = 0.4 cell.layer.cornerRadius = 0 let rows = tableView.numberOfRows(inSection: indexPath.section) if indexPath.row == 0 { cell.layer.cornerRadius = defaultCornerRadius if indexPath.row == rows - 1 { cell.separator.backgroundColor = .clear cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner, .layerMaxXMaxYCorner, .layerMinXMaxYCorner] } else { cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] } } else if indexPath.row == rows - 1 { cell.layer.cornerRadius = defaultCornerRadius cell.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner] cell.separator.backgroundColor = .clear } return cell } } // method to run when table view cell is tapped func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var item = NKExternalSite() if indexPath.section == 0 { tapImageLogoManageAccount() return } // Menu Function if indexPath.section == 1 { item = functionMenu[indexPath.row] } // Menu External Site if numberOfSections(in: tableView) == 4 && indexPath.section == 2 { item = externalSiteMenu[indexPath.row] } // Menu Settings if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) { item = settingsMenu[indexPath.row] } // Action if item.url.contains("segue") && !item.url.contains("//") { self.navigationController?.performSegue(withIdentifier: item.url, sender: self) } else if item.url.contains("openStoryboard") && !item.url.contains("//") { let nameStoryboard = item.url.replacingOccurrences(of: "openStoryboard", with: "") let storyboard = UIStoryboard(name: nameStoryboard, bundle: nil) if let controller = storyboard.instantiateInitialViewController() { controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet present(controller, animated: true, completion: nil) } } else if item.url.contains("//") { let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb browserWebVC.urlBase = item.url browserWebVC.isHiddenButtonExit = true browserWebVC.titleBrowser = item.name self.navigationController?.pushViewController(browserWebVC, animated: true) self.navigationController?.navigationBar.isHidden = false } else if item.url == "logout" { let alertController = UIAlertController(title: "", message: NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert) let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in let manageAccount = CCManageAccount() manageAccount.delete(self.appDelegate.account) self.appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false) } let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in print("You've pressed No button") } alertController.addAction(actionYes) alertController.addAction(actionNo) self.present(alertController, animated: true, completion: nil) } else if item.url == "test" { } } } class CCCellMore: UITableViewCell { @IBOutlet weak var labelText: UILabel! @IBOutlet weak var imageIcon: UIImageView! @IBOutlet weak var separator: UIView! @IBOutlet weak var separatorHeigth: NSLayoutConstraint! override var frame: CGRect { get { return super.frame } set (newFrame) { var frame = newFrame let newWidth = frame.width * 0.90 let space = (frame.width - newWidth) / 2 frame.size.width = newWidth frame.origin.x += space super.frame = frame } } } class NCMoreUserCell: UITableViewCell { @IBOutlet weak var displayName: UILabel! @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var status: MarqueeLabel! override var frame: CGRect { get { return super.frame } set (newFrame) { var frame = newFrame let newWidth = frame.width * 0.90 let space = (frame.width - newWidth) / 2 frame.size.width = newWidth frame.origin.x += space super.frame = frame } } }
gpl-3.0
fdd15783a48e0a58fabd0c2404c94a7a
34.539326
197
0.591316
5.271667
false
false
false
false
mabels/ipaddress
swift/Sources/IpAddress/rle.swift
1
2219
public class Last<T: Equatable&Hashable> { var val: Rle<T>?; var max_poses = [T: [Int]](); var ret: [Rle<T>] = [Rle<T>](); public init() { } func handle_last() { if (nil == val) { return; } let _last = val!; var max_rles = max_poses[_last.part]; if (max_rles == nil) { max_rles = [Int](); //print("handle_last:push:\(_last.part)") max_poses[_last.part] = max_rles; } //print("\(_last.part), \(max_rles!)"); for idx in max_rles! { let prev = ret[idx]; if (prev.cnt > _last.cnt) { //print(">>>>> last=\(_last)->\(idx)->prev=\(prev)"); _last.max = false; } else if (prev.cnt == _last.cnt) { // nothing } else if (prev.cnt < _last.cnt) { //print("<<<<< last=\(_last)->\(idx)->prev=\(prev)"); prev.max = false; } } //println!("push:{}:{:?}", self.ret.len(), _last); max_rles!.append(ret.count); _last.pos = ret.count; ret.append(_last); max_poses[_last.part] = max_rles // funky swift } } public class Rle<T: Equatable&Hashable>: Equatable, CustomStringConvertible { var part: T; var pos = 0; var cnt = 0; var max: Bool = false; public init(part: T, pos: Int, cnt: Int, max: Bool) { self.part = part; self.pos = pos; self.cnt = cnt; self.max = max; } public var description: String { return "<Rle@part:\(part),pos\(pos),cnt:\(cnt),max:\(max)>"; } public final class func ==(lhs: Rle<T>, rhs: Rle<T>) -> Bool { return lhs.eq(rhs) } public func eq(_ other: Rle<T>) -> Bool { return part == other.part && pos == other.pos && cnt == other.cnt && max == other.max; } public func ne(_ other: Rle<T>) -> Bool { return !eq(other); } public class func code<T: Equatable&Hashable>(_ parts: [T]) -> [Rle<T>] { let last = Last<T>(); //print("code"); for part in parts { // console.log(`part:${part}`); if (last.val != nil && last.val!.part == part) { last.val!.cnt += 1; } else { last.handle_last(); last.val = Rle<T>(part: part, pos: 0, cnt: 1, max: true); } } last.handle_last(); return last.ret; } }
mit
e24694586ef348d85743c78206a16e5a
23.932584
77
0.509238
3.134181
false
false
false
false
LYM-mg/DemoTest
其他功能/MGBookViews/MGBookViews/Camera/CameraBlurView.swift
1
2442
// // CameraBlurView.swift // MGBookViews // // Created by newunion on 2017/12/28. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import SnapKit class CameraBlurView: UIView { @IBOutlet weak var tipLabel1: UILabel! @IBOutlet weak var takePhotoView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var tipLabel2: UILabel! override func awakeFromNib() { super.awakeFromNib() tipLabel1.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2)) tipLabel2.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2)) let str: NSString = "请保持人像面朝上" let range = str.range(of: "人像面朝上") let attr2 = NSMutableAttributedString(string: str as String) attr2.addAttribute(NSForegroundColorAttributeName, value: UIColor.colorHex(hex: "#FA5532"), range: range) // attr2.addAttribute(NSVerticalGlyphFormAttributeName, value: 1, range: NSRange(location: 0, length: 6)) tipLabel2.attributedText = attr2 } override func layoutSubviews() { super.layoutSubviews() tipLabel1.x = takePhotoView.x-15-tipLabel1.width tipLabel1.center.y = takePhotoView.center.y tipLabel2.x = takePhotoView.frame.maxX+15 tipLabel2.center.y = takePhotoView.center.y // tipLabel1.snp.makeConstraints { (make) in // make.centerY.equalTo(takePhotoView.snp.centerY) // make.right.equalTo(takePhotoView.snp.left).offset(-15) // } // tipLabel2.snp.makeConstraints { (make) in // make.centerY.equalTo(takePhotoView.snp.centerY) // make.left.equalTo(takePhotoView.snp.right).offset(15) // } } } extension UIView { } @IBDesignable class VertricalLabel: UILabel { @IBInspectable var angle: CGFloat { get{ return super.transform.a } set { self.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)/angle) } } /** * 值为整型NSNumber,0为水平排版的字,1为垂直排版的字。注意,在iOS中, 总是以横向排版 * * In iOS, horizontal text is always used and specifying a different value is undefined. */ // @IBInspectable var vertical: String { // get{ // return super.attributedText as String // } set { // } // } }
mit
bb5454cc74732465bf9719804e40f8b0
30.32
113
0.645381
3.921536
false
false
false
false
xlexi/Textual-Inline-Media
Textual Inline Media/Inline Media Handlers/Wikipedia.swift
1
7738
/* Copyright (c) 2015, Alex S. Glomsaas All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation class Wikipedia: NSObject, InlineMediaHandler { static func name() -> String { return "Wikipedia" } static func icon() -> NSImage? { return NSImage.fromAssetCatalogue("Wikipedia") } required convenience init(url: NSURL, controller: TVCLogController, line: String) { self.init() if let query = url.pathComponents?[2] { let requestString = "format=json&action=query&exsentences=4&prop=extracts|pageimages&titles=\(query)&pithumbsize=200" .stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! let subdomain = url.host?.componentsSeparatedByString(".")[0] guard subdomain != nil else { return } let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.HTTPAdditionalHeaders = ["User-Agent": "TextualInlineMedia/1.0 (https://github.com/xlexi/Textual-Inline-Media/; [email protected])"] let session = NSURLSession(configuration: config) if let requestUrl = NSURL(string: "https://\(subdomain!).wikipedia.org/w/api.php?\(requestString)") { session.dataTaskWithURL(requestUrl, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in guard data != nil else { return } do { /* Attempt to serialise the JSON results into a dictionary. */ let root = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) guard let query = root["query"] as? Dictionary<String, AnyObject> else { return } guard let pages = query["pages"] as? Dictionary<String, AnyObject> else { WebRequest(url: response!.URL!, controller: controller, line: line).start() return } let page = pages.first! if page.0 != "-1" { guard let article = page.1 as? Dictionary<String, AnyObject> else { return } let title = article["title"] as? String let description = article["extract"] as? String var thumbnailUrl = "" if let thumbnail = article["thumbnail"] as? Dictionary<String, AnyObject> { guard let source = thumbnail["source"] as? String else { return } thumbnailUrl = source } self.performBlockOnMainThread({ let document = controller.webView.mainFrameDocument /* Create the container for the entire inline media element. */ let wikiContainer = document.createElement("a") wikiContainer.setAttribute("href", value: url.absoluteString) wikiContainer.className = "inline_media_wiki" /* If we found a preview image element, we will add it. */ if thumbnailUrl.characters.count > 0 { let previewImage = document.createElement("img") previewImage.className = "inline_media_wiki_thumbnail" previewImage.setAttribute("src", value: thumbnailUrl) wikiContainer.appendChild(previewImage) } /* Create the container that holds the title and description. */ let infoContainer = document.createElement("div") infoContainer.className = "inline_media_wiki_info" wikiContainer.appendChild(infoContainer) /* Create the title element */ let titleElement = document.createElement("div") titleElement.className = "inline_media_wiki_title" titleElement.appendChild(document.createTextNode(title)) infoContainer.appendChild(titleElement) /* If we found a description, create the description element. */ if description!.characters.count > 0 { let descriptionElement = document.createElement("div") descriptionElement.className = "inline_media_wiki_desc" descriptionElement.innerHTML = description infoContainer.appendChild(descriptionElement) } controller.insertInlineMedia(line, node: wikiContainer, url: url.absoluteString) }) } } catch { return } }).resume() } } } static func matchesServiceSchema(url: NSURL) -> Bool { if url.host?.hasSuffix(".wikipedia.org") == true && url.pathComponents?.count === 3 { return url.pathComponents![1] == "wiki" } return false } }
bsd-3-clause
84106b3350e082434d899a1d2423a2f3
53.111888
151
0.519773
6.4699
false
false
false
false
vimac/BearRemoter-iOS
BearRemoter/BearRemoterViewController.swift
1
3485
// // FirstViewController.swift // BearRemoter // // Created by Mac on 8/15/15. // Copyright (c) 2015 vifix.cn. All rights reserved. // import UIKit class BearRemoterViewController: UITableViewController { let tableData: [String] = ["我饿了😂", "我渴了😂", "我要睡觉了😂", "我要看电视了😂", "我要穿衣服了😂", "我要起床了😂", "我热了😂", "我冷了😂", "我要召唤神龙😂!"] override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellRemoter") // userInfo = BearUserInfo(cellPhone: "123456789") let data = BearCache.sharedInstance.loadData() NSLog(data.cellPhone!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row as Int let content = tableData[row] as String NSLog("pressed %@", content) let userInfo = BearCache.sharedInstance.userInfo let alert = UIAlertController(title: "将要发送", message: content, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in let urlPath: String = "http://vifix.cn/remoter/send.php" let url: NSURL = NSURL(string: urlPath)! let req: NSMutableURLRequest = NSMutableURLRequest(URL: url) req.HTTPMethod = "POST" let stringPost = "cellPhone=\(userInfo?.cellPhone as String!)&nickname=\(userInfo?.nickname as String!)&targetCellPhone=\(userInfo?.targetCellPhone as String!)&message=\(content)" let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) req.timeoutInterval = 60 req.HTTPBody = data req.HTTPShouldHandleCookies = false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in var err: NSError //var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary //println("AsSynchronous\(jsonResult)") // println(NSString(data: <#NSData#>, encoding: <#UInt#>)) }) })) alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellRemoter", forIndexPath: indexPath) let row = indexPath.row as Int cell.textLabel?.text = tableData[row] cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell; } }
mit
dc678cc6700c5f618bea6bfa64cbeeb8
42.076923
191
0.652083
4.977778
false
false
false
false
minikin/Algorithmics
Pods/PSOperations/PSOperations/LocationCondition.swift
1
5628
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ #if !os(OSX) import CoreLocation /// A condition for verifying access to the user's location. @available(*, deprecated, message="use Capability(Location...) instead") public struct LocationCondition: OperationCondition { /** Declare a new enum instead of using `CLAuthorizationStatus`, because that enum has more case values than are necessary for our purposes. */ public enum Usage { case WhenInUse #if !os(tvOS) case Always #endif } public static let name = "Location" static let locationServicesEnabledKey = "CLLocationServicesEnabled" static let authorizationStatusKey = "CLAuthorizationStatus" public static let isMutuallyExclusive = false let usage: Usage public init(usage: Usage) { self.usage = usage } public func dependencyForOperation(operation: Operation) -> NSOperation? { return LocationPermissionOperation(usage: usage) } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { let enabled = CLLocationManager.locationServicesEnabled() let actual = CLLocationManager.authorizationStatus() var error: NSError? // There are several factors to consider when evaluating this condition switch (enabled, usage, actual) { case (true, _, .AuthorizedAlways): // The service is enabled, and we have "Always" permission -> condition satisfied. break case (true, .WhenInUse, .AuthorizedWhenInUse): /* The service is enabled, and we have and need "WhenInUse" permission -> condition satisfied. */ break default: /* Anything else is an error. Maybe location services are disabled, or maybe we need "Always" permission but only have "WhenInUse", or maybe access has been restricted or denied, or maybe access hasn't been request yet. The last case would happen if this condition were wrapped in a `SilentCondition`. */ error = NSError(code: .ConditionFailed, userInfo: [ OperationConditionKey: self.dynamicType.name, self.dynamicType.locationServicesEnabledKey: enabled, self.dynamicType.authorizationStatusKey: Int(actual.rawValue) ]) } if let error = error { completion(.Failed(error)) } else { completion(.Satisfied) } } } /** A private `Operation` that will request permission to access the user's location, if permission has not already been granted. */ class LocationPermissionOperation: Operation { let usage: LocationCondition.Usage var manager: CLLocationManager? init(usage: LocationCondition.Usage) { self.usage = usage super.init() /* This is an operation that potentially presents an alert so it should be mutually exclusive with anything else that presents an alert. */ addCondition(AlertPresentation()) } override func execute() { /* Not only do we need to handle the "Not Determined" case, but we also need to handle the "upgrade" (.WhenInUse -> .Always) case. */ #if os(tvOS) switch (CLLocationManager.authorizationStatus(), usage) { case (.NotDetermined, _): dispatch_async(dispatch_get_main_queue()) { self.requestPermission() } default: finish() } #else switch (CLLocationManager.authorizationStatus(), usage) { case (.NotDetermined, _), (.AuthorizedWhenInUse, .Always): dispatch_async(dispatch_get_main_queue()) { self.requestPermission() } default: finish() } #endif } private func requestPermission() { manager = CLLocationManager() manager?.delegate = self let key: String #if os(tvOS) switch usage { case .WhenInUse: key = "NSLocationWhenInUseUsageDescription" manager?.requestWhenInUseAuthorization() } #else switch usage { case .WhenInUse: key = "NSLocationWhenInUseUsageDescription" manager?.requestWhenInUseAuthorization() case .Always: key = "NSLocationAlwaysUsageDescription" manager?.requestAlwaysAuthorization() } #endif // This is helpful when developing the app. assert(NSBundle.mainBundle().objectForInfoDictionaryKey(key) != nil, "Requesting location permission requires the \(key) key in your Info.plist") } } extension LocationPermissionOperation: CLLocationManagerDelegate { @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if manager == self.manager && executing && status != .NotDetermined { finish() } } } #endif
mit
db73e283bc3fb265589a374412eeb344
31.709302
153
0.594739
5.752556
false
false
false
false
practicalswift/swift
test/stdlib/OptionalBridge.swift
34
5791
//===--- OptionalBridge.swift - Tests of Optional bridging ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest let tests = TestSuite("OptionalBridge") // Work around bugs in the type checker preventing casts back to optional. func cast<T>(_ value: AnyObject, to: T.Type) -> T { return value as! T } // expectEqual() helpers for deeper-nested nullability than StdlibUnittest // provides. func expectEqual<T: Equatable>(_ x: T??, _ y: T??) { switch (x, y) { case (.some(let xx), .some(let yy)): expectEqual(xx, yy) case (.none, .none): return default: expectUnreachable("\(T.self)?? values don't match: \(x) vs. \(y)") } } func expectEqual<T: Equatable>(_ x: T???, _ y: T???) { switch (x, y) { case (.some(let xx), .some(let yy)): expectEqual(xx, yy) case (.none, .none): return default: expectUnreachable("\(T.self)??? values don't match: \(x) vs. \(y)") } } tests.test("wrapped value") { let unwrapped = "foo" let wrapped = Optional(unwrapped) let doubleWrapped = Optional(wrapped) let unwrappedBridged = unwrapped as AnyObject let wrappedBridged = wrapped as AnyObject let doubleWrappedBridged = doubleWrapped as AnyObject expectTrue(unwrappedBridged.isEqual(wrappedBridged) && wrappedBridged.isEqual(doubleWrappedBridged)) let unwrappedCastBack = cast(unwrappedBridged, to: String.self) let wrappedCastBack = cast(wrappedBridged, to: Optional<String>.self) let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<String?>.self) expectEqual(unwrapped, unwrappedCastBack) expectEqual(wrapped, wrappedCastBack) expectEqual(doubleWrapped, doubleWrappedCastBack) } struct NotBridged: Hashable { var x: Int func hash(into hasher: inout Hasher) { hasher.combine(x) } static func ==(x: NotBridged, y: NotBridged) -> Bool { return x.x == y.x } } tests.test("wrapped boxed value") { let unwrapped = NotBridged(x: 1738) let wrapped = Optional(unwrapped) let doubleWrapped = Optional(wrapped) let unwrappedBridged = unwrapped as AnyObject let wrappedBridged = wrapped as AnyObject let doubleWrappedBridged = doubleWrapped as AnyObject expectTrue(unwrappedBridged.isEqual(wrappedBridged)) expectTrue(wrappedBridged.isEqual(doubleWrappedBridged)) let unwrappedCastBack = cast(unwrappedBridged, to: NotBridged.self) let wrappedCastBack = cast(wrappedBridged, to: Optional<NotBridged>.self) let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<NotBridged?>.self) expectEqual(unwrapped, unwrappedCastBack) expectEqual(wrapped, wrappedCastBack) expectEqual(doubleWrapped, doubleWrappedCastBack) } tests.test("wrapped class instance") { let unwrapped = LifetimeTracked(0) let wrapped = Optional(unwrapped) expectTrue(wrapped as AnyObject === unwrapped as AnyObject) } tests.test("nil") { let null: String? = nil let wrappedNull = Optional(null) let doubleWrappedNull = Optional(wrappedNull) let nullBridged = null as AnyObject let wrappedNullBridged = wrappedNull as AnyObject let doubleWrappedNullBridged = doubleWrappedNull as AnyObject expectTrue(nullBridged === NSNull()) expectTrue(wrappedNullBridged === NSNull()) expectTrue(doubleWrappedNullBridged === NSNull()) let nullCastBack = cast(nullBridged, to: Optional<String>.self) let wrappedNullCastBack = cast(nullBridged, to: Optional<String?>.self) let doubleWrappedNullCastBack = cast(nullBridged, to: Optional<String??>.self) expectEqual(nullCastBack, null) expectEqual(wrappedNullCastBack, wrappedNull) expectEqual(doubleWrappedNullCastBack, doubleWrappedNull) } tests.test("nil in nested optional") { let doubleNull: String?? = nil let wrappedDoubleNull = Optional(doubleNull) let doubleNullBridged = doubleNull as AnyObject let wrappedDoubleNullBridged = wrappedDoubleNull as AnyObject expectTrue(doubleNullBridged === wrappedDoubleNullBridged) expectTrue(doubleNullBridged !== NSNull()) let doubleNullCastBack = cast(doubleNullBridged, to: Optional<String?>.self) let wrappedDoubleNullCastBack = cast(doubleNullBridged, to: Optional<String??>.self) expectEqual(doubleNullCastBack, doubleNull) expectEqual(wrappedDoubleNullCastBack, wrappedDoubleNull) let tripleNull: String??? = nil let tripleNullBridged = tripleNull as AnyObject expectTrue(doubleNullBridged !== tripleNullBridged) let tripleNullCastBack = cast(tripleNullBridged, to: Optional<String??>.self) expectEqual(tripleNullCastBack, tripleNull) } tests.test("collection of Optional") { let holeyArray: [LifetimeTracked?] = [LifetimeTracked(0), nil, LifetimeTracked(1)] let nsArray = holeyArray as NSArray autoreleasepool { expectTrue((nsArray[0] as AnyObject) === holeyArray[0]!) expectTrue((nsArray[1] as AnyObject) === NSNull()) expectTrue((nsArray[2] as AnyObject) === holeyArray[2]!) } } tests.test("NSArray of NSNull") { let holeyNSArray: NSArray = [LifetimeTracked(2), NSNull(), LifetimeTracked(3)] autoreleasepool { let swiftArray = holeyNSArray as! [LifetimeTracked?] expectTrue(swiftArray[0]! === holeyNSArray[0] as AnyObject) expectTrue(swiftArray[1] == nil) expectTrue(swiftArray[2]! === holeyNSArray[2] as AnyObject) } } runAllTests()
apache-2.0
eb9172ebe7da027d4da45c68d81fc0ed
31.717514
88
0.725263
4.377173
false
true
false
false
BBRick/wp
wp/Scenes/Deal/HistoryDealVC.swift
1
7017
// // HistoryDealVC.swift // wp // // Created by 木柳 on 2017/1/4. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import RealmSwift import DKNightVersion class HistoryDealCell: OEZTableViewCell{ @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var winLabel: UILabel! @IBOutlet weak var failLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var handleLabel: UILabel! // 盈亏 @IBOutlet weak var statuslb: UILabel! override func update(_ data: Any!) { if let model: PositionModel = data as! PositionModel? { print(model.description) nameLabel.text = "\(model.name)" timeLabel.text = Date.yt_convertDateToStr(Date.init(timeIntervalSince1970: TimeInterval(model.closeTime)), format: "yyyy.MM.dd HH:mm:ss") //com.yundian.trip priceLabel.text = "¥" + String(format: "%.2f", model.openCost) priceLabel.dk_textColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) statuslb.backgroundColor = model.result ? UIColor.init(hexString: "E9573F") : UIColor.init(hexString: "0EAF56") statuslb.text = model.result ? "盈" : "亏" titleLabel.text = model.buySell == 1 ? "买入" : "卖出" let handleText = [" 未操作 "," 双倍返还 "," 货运 "," 退舱 "] if model.handle < handleText.count{ handleLabel.text = handleText[model.handle] } if model.buySell == -1 && UserModel.share().currentUser?.type == 0 && model.result == false{ handleLabel.backgroundColor = UIColor.clear handleLabel.text = "" }else if model.handle == 0{ handleLabel.backgroundColor = UIColor.init(rgbHex: 0xc2cfd7) }else{ handleLabel.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main) } } } } class HistoryDealVC: BasePageListTableViewController { var historyModels: [PositionModel] = [] //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() } override func didRequest(_ pageIndex: Int) { historyModels = dataSource == nil ? [] : dataSource as! [PositionModel] let index = pageIndex == 1 ? 0: historyModels.count AppAPIHelper.deal().historyDeals(start: index, count: 10, complete: { [weak self](result) -> ()? in if let models: [PositionModel] = result as! [PositionModel]?{ if pageIndex == 1 { self?.didRequestComplete(models as AnyObject?) }else{ var moreModels: [PositionModel] = [] for model in models{ if model.closeTime < (self?.historyModels.last!.closeTime)!{ moreModels.append(model) } } self?.didRequestComplete(moreModels as AnyObject?) } } return nil }, error: errorBlockFunc()) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let model = self.dataSource?[indexPath.row] as? PositionModel{ print(model.handle) if model.handle != 0{ return } if model.buySell == -1 && UserModel.share().currentUser?.type == 0 && model.result == false{ return } let param = BenifityParam() param.tid = model.positionId let alterController = UIAlertController.init(title: "恭喜盈利", message: "请选择盈利方式", preferredStyle: .alert) let productAction = UIAlertAction.init(title: "货运", style: .default, handler: {[weak self] (resultDic) in param.handle = 2 AppAPIHelper.deal().benifity(param: param, complete: {(result) -> ()? in if let resultDic: [String: AnyObject] = result as? [String: AnyObject]{ if let id = resultDic[SocketConst.Key.id] as? Int{ if id != UserModel.share().currentUserId{ return nil } } if let handle = resultDic[SocketConst.Key.handle] as? Int{ if let selectModel = self?.dataSource?[indexPath.row] as? PositionModel{ UserModel.updateUser(info: { (info) -> ()? in selectModel.handle = handle tableView.reloadData() return nil }) } } } return nil }, error: self?.errorBlockFunc()) }) let moneyAction = UIAlertAction.init(title: "双倍返还", style: .default, handler: { [weak self](resultDic) in param.handle = 1 AppAPIHelper.deal().benifity(param: param, complete: {(result) -> ()? in if let resultDic: [String: AnyObject] = result as? [String: AnyObject]{ if let id = resultDic[SocketConst.Key.id] as? Int{ if id != UserModel.share().currentUserId{ return nil } } if let handle = resultDic[SocketConst.Key.handle] as? Int{ if let selectModel = self?.dataSource?[indexPath.row] as? PositionModel{ UserModel.updateUser(info: { (info) -> ()? in selectModel.handle = handle tableView.reloadData() return nil }) } } } return nil }, error: self?.errorBlockFunc()) }) if model.buySell == 1{ if model.result{ alterController.addAction(moneyAction) } alterController.addAction(productAction) present(alterController, animated: true, completion: nil) }else{ if UserModel.share().currentUser?.type == 0 && model.result{ alterController.addAction(moneyAction) }else{ alterController.addAction(productAction) } present(alterController, animated: true, completion: nil) } } } }
apache-2.0
eb91cece1685afbbdb83fb9d8f5a153c
43.184713
149
0.504541
5.104489
false
false
false
false
danielrcardenas/ac-course-2017
frameworks/SwarmChemistry-Swif/Demo_iOS/RecipeInputViewController.swift
1
1487
// // RecipeInputViewController.swift // SwarmChemistry // // Created by Yamazaki Mitsuyoshi on 2017/08/14. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // import UIKit import SwarmChemistry protocol RecipeInputViewControllerDelegate: class { func recipeInputViewController(_ controller: RecipeInputViewController, didInput recipe: Recipe) } class RecipeInputViewController: UIViewController { weak var delegate: RecipeInputViewControllerDelegate? var currentRecipe: Recipe? { didSet { textView?.text = currentRecipe?.description ?? "" } } @IBOutlet private weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() textView.text = currentRecipe?.description ?? "" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() } @IBAction func done(sender: AnyObject!) { guard let recipe = Recipe.init(textView.text, name: "Manual Input") else { let alertController = UIAlertController.init(title: "Error", message: "Cannot parse recipe", preferredStyle: .alert) alertController.addAction(.init(title: "OK", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) return } currentRecipe = recipe let delegate = self.delegate dismiss(animated: true) { delegate?.recipeInputViewController(self, didInput: recipe) } } }
apache-2.0
e935824e91764b7b4c2b8cc004ab1c01
26.518519
122
0.70996
4.747604
false
false
false
false
mightydeveloper/swift
test/Interpreter/SDK/Reflection_KVO.swift
9
1098
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // rdar://problem/19060227 import Foundation class ObservedValue: NSObject { dynamic var amount = 0 } class ValueObserver: NSObject { private var observeContext = 0 let observedValue: ObservedValue init(value: ObservedValue) { observedValue = value super.init() observedValue.addObserver(self, forKeyPath: "amount", options: .New, context: &observeContext) } deinit { observedValue.removeObserver(self, forKeyPath: "amount") } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &observeContext { if let change_ = change { if let amount = change_[NSKeyValueChangeNewKey as String] as? Int { print("Observed value updated to \(amount)") } } } } } let value = ObservedValue() value.amount = 42 let observer = ValueObserver(value: value) // CHECK: updated to 43 value.amount++ // CHECK: amount: 43 dump(value)
apache-2.0
c0c2652ed32514ab7536b057c1622af9
22.361702
154
0.704007
3.935484
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/Demo/Modules/Demos/Components/QDPopupContainerViewController.swift
1
10038
// // QDPopupContainerViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/5/17. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit class QDPopupContainerView: QMUIPopupContainerView { private var emotionInputManager: QMUIEmotionInputManager! override init(frame: CGRect) { super.init(frame: frame) contentEdgeInsets = .zero emotionInputManager = QMUIEmotionInputManager() emotionInputManager.emotionView.emotions = QDUIHelper.qmuiEmotions() emotionInputManager.emotionView.sendButton.isHidden = true contentView.addSubview(emotionInputManager.emotionView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeThatFitsInContentView(_ size: CGSize) -> CGSize { return CGSize(width: 300, height: 320) } override func layoutSubviews() { super.layoutSubviews() // 所有布局都参照 contentView emotionInputManager.emotionView.frame = contentView.bounds } } class QDPopupContainerViewController: QDCommonViewController { private var button1: QMUIButton! private var popupView1: QMUIPopupContainerView! private var button2: QMUIButton! private var popupView2: QMUIPopupMenuView! private var button3: QMUIButton! private var popupView3: QDPopupContainerView! private var separatorLayer1: CALayer! private var separatorLayer2: CALayer! private var popupView4: QMUIPopupMenuView! override func initSubviews() { super.initSubviews() separatorLayer1 = CALayer() separatorLayer1.qmui_removeDefaultAnimations() separatorLayer1.backgroundColor = UIColorSeparator.cgColor view.layer.addSublayer(separatorLayer1) separatorLayer2 = CALayer() separatorLayer2.qmui_removeDefaultAnimations() separatorLayer2.backgroundColor = UIColorSeparator.cgColor view.layer.addSublayer(separatorLayer2) button1 = QDUIHelper.generateLightBorderedButton() button1.addTarget(self, action: #selector(handleButtonEvent(_:)), for: .touchUpInside) button1.setTitle("显示默认浮层", for: .normal) view.addSubview(button1) // 使用方法 1,以 addSubview: 的形式显示到界面上 popupView1 = QMUIPopupContainerView() popupView1.imageView.image = UIImageMake("icon_emotion")?.qmui_imageResized(in: CGSize(width: 24, height: 24), contentMode: .scaleToFill)?.qmui_image(tintColor: QDThemeManager.shared.currentTheme?.themeTintColor) popupView1.textLabel.text = "默认自带 imageView、textLabel,可展示简单的内容" popupView1.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) popupView1.didHideClosure = { [weak self] (hidesByUserTap) in self?.button1.setTitle("显示默认浮层", for: .normal) } // 使用方法 1 时,显示浮层前需要先手动隐藏浮层,并自行添加到目标 UIView 上 popupView1.isHidden = true view.addSubview(popupView1) button2 = QDUIHelper.generateLightBorderedButton() button2.addTarget(self, action: #selector(handleButtonEvent), for: .touchUpInside) button2.setTitle("显示菜单浮层", for: .normal) view.addSubview(button2) // 使用方法 2,以 UIWindow 的形式显示到界面上,这种无需默认隐藏,也无需 add 到某个 UIView 上 popupView2 = QMUIPopupMenuView() popupView2.automaticallyHidesWhenUserTap = true // 点击空白地方消失浮层 popupView2.maskViewBackgroundColor = UIColorMaskWhite // 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下,可以修改背景遮罩的颜色 popupView2.maximumWidth = 180; popupView2.shouldShowItemSeparator = true popupView2.separatorInset = UIEdgeInsets(top: 0, left: popupView2.padding.left, bottom: 0, right: popupView2.padding.right) popupView2.items = [ QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_uikit")?.withRenderingMode(.alwaysTemplate), title: "QMUIKit", handler: { [weak self] in self?.popupView2.hide(with: true) }), QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_component")?.withRenderingMode(.alwaysTemplate), title: "Components", handler: { [weak self] in self?.popupView2.hide(with: true) }), QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_lab")?.withRenderingMode(.alwaysTemplate), title: "Lab", handler: { [weak self] in self?.popupView2.hide(with: true) })] popupView2.didHideClosure = { [weak self] (hidesByUserTap) in self?.button2.setTitle("显示菜单浮层", for: .normal) } button3 = QDUIHelper.generateLightBorderedButton() button3.addTarget(self, action: #selector(handleButtonEvent), for: .touchUpInside) button3.setTitle("显示自定义浮层", for: .normal) view.addSubview(button3) popupView3 = QDPopupContainerView() popupView3.preferLayoutDirection = .below // 默认在目标的下方,如果目标下方空间不够,会尝试放到目标上方。若上方空间也不够,则缩小自身的高度。 popupView3.didHideClosure = { [weak self] (hidesByUserTap) in self?.button3.setTitle("显示自定义浮层", for: .normal) } // 在 UIBarButtonItem 上显示 popupView4 = QMUIPopupMenuView() popupView4.automaticallyHidesWhenUserTap = true // 点击空白地方消失浮层 popupView4.maximumWidth = 180 popupView4.shouldShowItemSeparator = true popupView4.separatorInset = UIEdgeInsets(top: 0, left: popupView4.padding.left, bottom: 0, right: popupView4.padding.right) popupView4.items = [ QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_uikit")?.withRenderingMode(.alwaysTemplate), title: "QMUIKit", handler: nil), QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_component")?.withRenderingMode(.alwaysTemplate), title: "Components", handler: nil), QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_lab")?.withRenderingMode(.alwaysTemplate), title: "Lab", handler: nil), ] } override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) { super.setNavigationItems(isInEditMode, animated: animated) navigationItem.rightBarButtonItem = UIBarButtonItem.item(image: UIImageMake("icon_nav_about"), target: self, action: #selector(handleRightBarButtonItemEvent(_:))) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // popupView3 使用方法 2 显示,并且没有打开 automaticallyHidesWhenUserTap,则需要手动隐藏 if popupView3.isShowing { popupView3.hide(with: animated) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let minY = qmui_navigationBarMaxYInViewCoordinator let viewportHeight = view.bounds.height - minY let sectionHeight = viewportHeight / 3 button1.frame = button1.frame.setXY(view.bounds.width.center(button1.frame.width), minY + (sectionHeight - button1.frame.height) / 2) popupView1.safetyMarginsOfSuperview.top = qmui_navigationBarMaxYInViewCoordinator + 10 popupView1.layout(with: button1) // 相对于 button1 布局 separatorLayer1.frame = CGRectFlat(0, minY + sectionHeight, view.bounds.width, PixelOne) button2.frame = button1.frame.setY(button1.frame.maxY + sectionHeight - button2.frame.height) popupView2.layout(with: button2) // 相对于 button2 布局 separatorLayer2.frame = separatorLayer1.frame.setY(minY + sectionHeight * 2) button3.frame = button1.frame.setY(button2.frame.maxY + sectionHeight - button3.frame.height) popupView3.layoutWithTargetRectInScreenCoordinate(button3.convert(button3.bounds, to: nil)) // 将 button3 的坐标转换到相对于 UIWindow 的坐标系里,然后再传给浮层布局 // 在横竖屏旋转时,viewDidLayoutSubviews 这个时机还无法获取到正确的 navigationItem 的 frame,所以直接隐藏掉 if popupView4.isShowing { popupView4.hide(with: false) } } @objc private func handleRightBarButtonItemEvent(_ button: QMUIButton) { if popupView4.isShowing { popupView4.hide(with: true) } else { // 相对于右上角的按钮布局,显示前重新对准布局,避免横竖屏导致位置不准确 if let qmui_view = navigationItem.rightBarButtonItem?.qmui_view { popupView4.layout(with: qmui_view) popupView4.show(with: true) } } } @objc private func handleButtonEvent(_ button: QMUIButton) { if button == button1 { if popupView1.isShowing { popupView1.hide(with: true) button1.setTitle("显示默认浮层", for: .normal) } else { popupView1.show(with: true) button1.setTitle("隐藏默认浮层", for: .normal) } return } if button == button2 { popupView2.show(with: true) button2.setTitle("隐藏菜单浮层", for: .normal) return } if button == button3 { if popupView3.isShowing { popupView3.hide(with: true) } else { popupView3.show(with: true) button3.setTitle("隐藏自定义浮层", for: .normal) } return } } }
mit
f220f3fa0f699145028e3baae9005c19
42.535211
220
0.657716
4.547818
false
false
false
false
Maaimusic/BTree
Sources/BTreeIterator.swift
1
4777
// // BTreeIterator.swift // BTree // // Created by Károly Lőrentey on 2016-02-11. // Copyright © 2015–2017 Károly Lőrentey. // /// An iterator for all elements stored in a B-tree, in ascending key order. public struct BTreeIterator<Key: Comparable, Value>: IteratorProtocol { public typealias Element = (Key, Value) @usableFromInline typealias Node = BTreeNode<Key, Value> @usableFromInline typealias State = BTreeStrongPath<Key, Value> @usableFromInline var state: State @usableFromInline internal init(_ state: State) { self.state = state } /// Advance to the next element and return it, or return `nil` if no next element exists. /// /// - Complexity: Amortized O(1) @inlinable public mutating func next() -> Element? { if state.isAtEnd { return nil } let result = state.element state.moveForward() return result } } /// A dummy, zero-size key that is useful in B-trees that don't need key-based lookup. @usableFromInline internal struct EmptyKey: Comparable { @usableFromInline internal init() { } @usableFromInline internal static func ==(a: EmptyKey, b: EmptyKey) -> Bool { return true } @usableFromInline internal static func <(a: EmptyKey, b: EmptyKey) -> Bool { return false } } /// An iterator for the values stored in a B-tree with an empty key. public struct BTreeValueIterator<Value>: IteratorProtocol { @usableFromInline internal typealias Base = BTreeIterator<EmptyKey, Value> @usableFromInline internal var base: Base @usableFromInline internal init(_ base: Base) { self.base = base } /// Advance to the next element and return it, or return `nil` if no next element exists. /// /// - Complexity: Amortized O(1) @inlinable public mutating func next() -> Value? { return base.next()?.1 } } /// An iterator for the keys stored in a B-tree without a value. public struct BTreeKeyIterator<Key: Comparable>: IteratorProtocol { @usableFromInline internal typealias Base = BTreeIterator<Key, Void> @usableFromInline internal var base: Base @usableFromInline internal init(_ base: Base) { self.base = base } /// Advance to the next element and return it, or return `nil` if no next element exists. /// /// - Complexity: Amortized O(1) @inlinable public mutating func next() -> Key? { return base.next()?.0 } } /// A mutable path in a B-tree, holding strong references to nodes on the path. /// This path variant does not support modifying the tree itself; it is suitable for use in generators. @usableFromInline internal struct BTreeStrongPath<Key: Comparable, Value>: BTreePath { @usableFromInline typealias Node = BTreeNode<Key, Value> @usableFromInline var root: Node @usableFromInline var offset: Int @usableFromInline var _path: [Node] @usableFromInline var _slots: [Int] @usableFromInline var node: Node @usableFromInline var slot: Int? @usableFromInline init(root: Node) { self.root = root self.offset = root.count self._path = [] self._slots = [] self.node = root self.slot = nil } @usableFromInline var count: Int { return root.count } @usableFromInline var length: Int { return _path.count + 1 } @usableFromInline mutating func popFromSlots() { assert(self.slot != nil) offset += node.count - node.offset(ofSlot: slot!) slot = nil } @usableFromInline mutating func popFromPath() { assert(_path.count > 0 && slot == nil) node = _path.removeLast() slot = _slots.removeLast() } @usableFromInline mutating func pushToPath() { assert(slot != nil) let child = node.children[slot!] _path.append(node) node = child _slots.append(slot!) slot = nil } @usableFromInline mutating func pushToSlots(_ slot: Int, offsetOfSlot: Int) { assert(self.slot == nil) offset -= node.count - offsetOfSlot self.slot = slot } @usableFromInline func forEach(ascending: Bool, body: (Node, Int) -> Void) { if ascending { body(node, slot!) for i in (0 ..< _path.count).reversed() { body(_path[i], _slots[i]) } } else { for i in 0 ..< _path.count { body(_path[i], _slots[i]) } body(node, slot!) } } @usableFromInline func forEachSlot(ascending: Bool, body: (Int) -> Void) { if ascending { body(slot!) _slots.reversed().forEach(body) } else { _slots.forEach(body) body(slot!) } } }
mit
599b128594f7a48bbce349f4efcc2601
30.8
103
0.624109
4.332425
false
false
false
false
tkausch/swiftalgorithms
CodePuzzles/AlphabetCipher.playground/Contents.swift
1
2676
import UIKit typealias CodeMap = [Character : Character] class AlphabetCipher { var key: String static var matrix = [Character : CodeMap]() static var alphabet = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); lazy var encryptionMaps : [CodeMap] = { return pickCodeMaps(key: key) }() lazy var decryptionMaps: [CodeMap] = { return pickCodeMaps(key: key, invert: true) }() init(key: String) { // initialize class property matrix - if not yet done. if Self.matrix.isEmpty { for (shift, char) in Self.alphabet.enumerated() { // create codemap by shifting alphabet var codemap = [Character : Character]() for (idx, ch) in Self.alphabet.enumerated() { codemap[ch] = Self.alphabet[(idx + shift) % Self.alphabet.count] } Self.matrix[char] = codemap } } self.key = key } func encrypt(_ plaintText: String) -> String { return substitute(text: plaintText, codeMaps: encryptionMaps) } func decrypt(_ cipherText: String) -> String { return substitute(text: cipherText, codeMaps: decryptionMaps) } func substitute(text: String, codeMaps: [CodeMap]) -> String { var current = 0 let mappedText = text.map { (char) -> Character in if let ch = codeMaps[current][char] { current = (current + 1) % codeMaps.count return ch } return char } return String(mappedText) } func pickCodeMaps(key: String, invert: Bool = false) -> [CodeMap] { var codeMaps = [CodeMap]() for ch in key { if let codeMap = Self.matrix[ch] { if invert { codeMaps.append(inverse(codeMap)) } else { codeMaps.append(codeMap) } } else { assertionFailure("Only ASCII characters supported in encoding key") } } return codeMaps } func inverse(_ codeMap: CodeMap) -> CodeMap { var inverseMap = CodeMap() for key in codeMap.keys { if let mappedKey = codeMap[key] { inverseMap[mappedKey] = key } } return inverseMap } } var cipher = AlphabetCipher(key: "vigilance") let cipherText = cipher.encrypt("meet me😀 at tuesday evening 🎯at seven") let plainText = cipher.decrypt(cipherText) print(cipherText) print(plainText)
gpl-3.0
67a0dd8abf725f9fc2591f8b261edc9c
26.244898
88
0.542697
4.676007
false
false
false
false
auth0/Auth0.swift
Auth0Tests/Responses.swift
1
5621
import Foundation import OHHTTPStubs @testable import Auth0 let UserId = "auth0|\(UUID().uuidString.replacingOccurrences(of: "-", with: ""))" let SupportAtAuth0 = "[email protected]" let Support = "support" let Auth0Phone = "+10123456789" let Nickname = "sup" let PictureURL = URL(string: "https://auth0.com/picture")! let WebsiteURL = URL(string: "https://auth0.com/website")! let ProfileURL = URL(string: "https://auth0.com/profile")! let UpdatedAt = "2015-08-19T17:18:01.000Z" let UpdatedAtUnix = "1440004681" let UpdatedAtTimestamp = 1440004681.000 let CreatedAt = "2015-08-19T17:18:00.000Z" let CreatedAtUnix = "1440004680" let CreatedAtTimestamp = 1440004680.000 let Sub = "auth0|123456789" let Kid = "key123" let LocaleUS = "en-US" let ZoneEST = "US/Eastern" let OTP = "123456" let OOB = "654321" let BindingCode = "214365" let RecoveryCode = "162534" let MFAToken = UUID().uuidString.replacingOccurrences(of: "-", with: "") let AuthenticatorId = UUID().uuidString.replacingOccurrences(of: "-", with: "") let ChallengeTypes = ["oob", "otp"] let APISuccessStatusCode = Int32(200) let APIResponseHeaders = ["Content-Type": "application/json"] func catchAllResponse() -> HTTPStubsResponse { return HTTPStubsResponse(error: NSError(domain: "com.auth0", code: -99999, userInfo: nil)) } func apiSuccessResponse(json: [AnyHashable: Any] = [:]) -> HTTPStubsResponse { return HTTPStubsResponse(jsonObject: json, statusCode: APISuccessStatusCode, headers: APIResponseHeaders) } func apiSuccessResponse(jsonArray: [Any]) -> HTTPStubsResponse { return HTTPStubsResponse(jsonObject: jsonArray, statusCode: APISuccessStatusCode, headers: APIResponseHeaders) } func apiSuccessResponse(string: String) -> HTTPStubsResponse { return HTTPStubsResponse(data: string.data(using: .utf8)!, statusCode: APISuccessStatusCode, headers: APIResponseHeaders) } func apiFailureResponse(json: [AnyHashable: Any] = [:], statusCode: Int = 400) -> HTTPStubsResponse { return HTTPStubsResponse(jsonObject: json, statusCode: Int32(statusCode), headers: APIResponseHeaders) } func apiFailureResponse(string: String, statusCode: Int) -> HTTPStubsResponse { return HTTPStubsResponse(data: string.data(using: .utf8)!, statusCode: Int32(statusCode), headers: APIResponseHeaders) } func authResponse(accessToken: String, idToken: String? = nil, refreshToken: String? = nil, expiresIn: Double? = nil) -> HTTPStubsResponse { var json = [ "access_token": accessToken, "token_type": "bearer", ] if let idToken = idToken { json["id_token"] = idToken } if let refreshToken = refreshToken { json["refresh_token"] = refreshToken } if let expires = expiresIn { json["expires_in"] = String(expires) } return apiSuccessResponse(json: json) } func authFailure(code: String, description: String, name: String? = nil) -> HTTPStubsResponse { return apiFailureResponse(json: ["code": code, "description": description, "statusCode": 400, "name": name ?? code]) } func authFailure(error: String, description: String) -> HTTPStubsResponse { return apiFailureResponse(json: ["error": error, "error_description": description]) } func createdUser(email: String, username: String? = nil, verified: Bool = true) -> HTTPStubsResponse { var json: [String: Any] = [ "email": email, "email_verified": verified ? "true" : "false", ] if let username = username { json["username"] = username } return apiSuccessResponse(json: json) } func resetPasswordResponse() -> HTTPStubsResponse { return apiSuccessResponse(string: "We've just sent you an email to reset your password.") } func revokeTokenResponse() -> HTTPStubsResponse { return apiSuccessResponse(string: "") } func passwordless(_ email: String, verified: Bool) -> HTTPStubsResponse { return apiSuccessResponse(json: ["email": email, "verified": "\(verified)"]) } func managementErrorResponse(error: String, description: String, code: String, statusCode: Int = 400) -> HTTPStubsResponse { return apiFailureResponse(json: ["code": code, "description": description, "statusCode": statusCode, "error": error], statusCode: statusCode) } func jwksResponse(kid: String? = Kid) -> HTTPStubsResponse { var jwks: [String: Any] = ["keys": [["alg": "RS256", "kty": "RSA", "use": "sig", "n": "uGbXWiK3dQTyCbX5xdE4yCuYp0AF2d15Qq1JSXT_lx8CEcXb9RbDddl8jGDv-spi5qPa8qEHiK7FwV2KpRE983wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVsWXI9C-yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT69s7of9-I9l5lsJ9cozf1rxrXX4V1u_SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8AziMCxS-VrRPDM-zfvpIJg3JljAh3PJHDiLu902v9w-Iplu1WyoB2aPfitxEhRN0Yw", "e": "AQAB", "kid": kid]]] #if WEB_AUTH_PLATFORM let jwk = generateRSAJWK() jwks = ["keys": [["alg": jwk.algorithm, "kty": jwk.keyType, "use": jwk.usage, "n": jwk.modulus, "e": jwk.exponent, "kid": kid]]] #endif return apiSuccessResponse(json: jwks) } func multifactorChallengeResponse(challengeType: String, oobCode: String? = nil, bindingMethod: String? = nil) -> HTTPStubsResponse { var json: [String: Any] = ["challenge_type": challengeType] json["oob_code"] = oobCode json["binding_method"] = bindingMethod return apiSuccessResponse(json: json) }
mit
aa23cee5a6660183346edfbfbadd9397
39.15
391
0.681729
3.707784
false
false
false
false
jrmgx/swift
jrmgx/Classes/Helper/JrmgxAsync.swift
1
3488
import UIKit open class JrmgxAsync { /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias UIImageResultBlock = (_ image: UIImage?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias NSURLResultBlock = (_ url: URL?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias AnyObjectsResultBlock = (_ objects: [AnyObject]?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias StringResultBlock = (_ string: String?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias NumberResultBlock = (_ number: NSNumber?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias IntResultBlock = (_ number: Int?, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ public typealias BoolResultBlock = (_ success: Bool, _ error: NSError?) -> Void /** * NAME * * - parameters * - name: String * - returns: nothing */ open static let NOOPBoolResultBlock: BoolResultBlock = { success, error in } // fileprivate static var namedQueues = ["main": DispatchQueue.main] /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func GetNamedQueue(_ name: String = "main") -> DispatchQueue { if namedQueues[name] == nil { namedQueues[name] = DispatchQueue(label: name, attributes: []) } return namedQueues[name]! } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(_ block: @escaping () -> Void) { Execute(onNamedQueue: "main", block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onNamedQueue name: String, block: @escaping () -> Void) { let queue = GetNamedQueue(name) Execute(onQueue: queue, block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onNamedQueue name: String, afterSeconds delay: Double, block: @escaping () -> Void) { let queue = GetNamedQueue(name) Execute(onQueue: queue, afterSeconds: delay, block: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onQueue queue: DispatchQueue, block: @escaping () -> Void) { queue.async(execute: block) } /** * NAME * * - parameters * - name: String * - returns: nothing */ open static func Execute(onQueue queue: DispatchQueue, afterSeconds delay: Double, block: @escaping () -> Void) { let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: block) } }
mit
3feb708e80a3b55a0544a43f511af9fe
21.797386
117
0.530677
4.21256
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Widgets/SearchInputView.swift
3
6708
/* 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 SnapKit private struct SearchInputViewUX { static let horizontalSpacing: CGFloat = 16 static let titleFont: UIFont = UIFont.systemFont(ofSize: 16) static let borderLineWidth: CGFloat = 0.5 static let closeButtonSize: CGFloat = 36 } @objc protocol SearchInputViewDelegate: AnyObject { func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) func searchInputViewBeganEditing(_ searchView: SearchInputView) func searchInputViewFinishedEditing(_ searchView: SearchInputView) } class SearchInputView: UIView { weak var delegate: SearchInputViewDelegate? var showBottomBorder: Bool = true { didSet { bottomBorder.isHidden = !showBottomBorder } } lazy var inputField: UITextField = { let textField = UITextField() textField.delegate = self textField.addTarget(self, action: #selector(inputTextDidChange), for: .editingChanged) textField.accessibilityLabel = NSLocalizedString("Search Input Field", tableName: "LoginManager", comment: "Accessibility label for the search input field in the Logins list") textField.autocorrectionType = .no textField.autocapitalizationType = .none return textField }() lazy var titleLabel: UILabel = { let label = UILabel() label.text = NSLocalizedString("Search", tableName: "LoginManager", comment: "Title for the search field at the top of the Logins list screen") label.font = SearchInputViewUX.titleFont return label }() lazy var searchIcon: UIImageView = { return UIImageView(image: UIImage(named: "quickSearch")) }() fileprivate lazy var closeButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(tappedClose), for: .touchUpInside) button.setImage(UIImage(named: "clear"), for: []) button.accessibilityLabel = NSLocalizedString("Clear Search", tableName: "LoginManager", comment: "Accessibility message e.g. spoken by VoiceOver after the user taps the close button in the search field to clear the search and exit search mode") return button }() fileprivate var centerContainer = UIView() fileprivate lazy var bottomBorder: UIView = { let border = UIView() return border }() fileprivate lazy var overlay: UIView = { let view = UIView() view.backgroundColor = UIColor.Photon.White100 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedSearch))) view.isAccessibilityElement = true view.accessibilityLabel = NSLocalizedString("Enter Search Mode", tableName: "LoginManager", comment: "Accessibility label for entering search mode for logins") return view }() fileprivate(set) var isEditing = false { didSet { if isEditing { overlay.isHidden = true inputField.isHidden = false inputField.accessibilityElementsHidden = false closeButton.isHidden = false closeButton.accessibilityElementsHidden = false } else { overlay.isHidden = false inputField.isHidden = true inputField.accessibilityElementsHidden = true closeButton.isHidden = true closeButton.accessibilityElementsHidden = true } } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.Photon.White100 isUserInteractionEnabled = true addSubview(inputField) addSubview(closeButton) centerContainer.addSubview(searchIcon) centerContainer.addSubview(titleLabel) overlay.addSubview(centerContainer) addSubview(overlay) addSubview(bottomBorder) setupConstraints() setEditing(false) } fileprivate func setupConstraints() { centerContainer.snp.makeConstraints { make in make.center.equalTo(overlay) } overlay.snp.makeConstraints { make in make.edges.equalTo(self) } searchIcon.snp.makeConstraints { make in make.right.equalTo(titleLabel.snp.left).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(centerContainer) } titleLabel.snp.makeConstraints { make in make.center.equalTo(centerContainer) } inputField.snp.makeConstraints { make in make.left.equalTo(self).offset(SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.right.equalTo(closeButton.snp.left).offset(-SearchInputViewUX.horizontalSpacing) } closeButton.snp.makeConstraints { make in make.right.equalTo(self).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.size.equalTo(SearchInputViewUX.closeButtonSize) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(SearchInputViewUX.borderLineWidth) } } // didSet callbacks don't trigger when a property is being set in the init() call // but calling a method that does works fine. fileprivate func setEditing(_ editing: Bool) { isEditing = editing } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Selectors extension SearchInputView { @objc func tappedSearch() { isEditing = true inputField.becomeFirstResponder() delegate?.searchInputViewBeganEditing(self) } @objc func tappedClose() { isEditing = false delegate?.searchInputViewFinishedEditing(self) inputField.text = nil inputField.resignFirstResponder() } @objc func inputTextDidChange(_ textField: UITextField) { delegate?.searchInputView(self, didChangeTextTo: textField.text ?? "") } } // MARK: - UITextFieldDelegate extension SearchInputView: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { // If there is no text, go back to showing the title view if textField.text?.isEmpty ?? true { isEditing = false delegate?.searchInputViewFinishedEditing(self) } } }
mpl-2.0
b72ee6c4b09178048150a27a9e93633b
32.878788
183
0.66294
5.449228
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Amplitude Envelope.xcplaygroundpage/Contents.swift
1
1145
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Amplitude Envelope //: ### Enveloping an FM Oscillator with an ADSR envelope import XCPlayground import AudioKit //: Try changing the table type to triangle or another AKTableType //: or changing the number of points to a smaller number (has to be a power of 2) var fm = AKFMOscillator(waveform: AKTable(.Sine, size: 4096)) var fmWithADSR = AKAmplitudeEnvelope(fm, attackDuration: 0.1, decayDuration: 0.3, sustainLevel: 0.8, releaseDuration: 1.0) AudioKit.output = fmWithADSR AudioKit.start() fm.start() fmWithADSR.start() AKPlaygroundLoop(every:1) { if fmWithADSR.isStarted { fmWithADSR.stop() } else { fm.baseFrequency = random(220, 880) fmWithADSR.attackDuration = random(0.01, 0.5) fmWithADSR.decayDuration = random(0.01, 0.2) fmWithADSR.sustainLevel = random(0.01, 1) fmWithADSR.releaseDuration = random(0.01, 1) fmWithADSR.start() } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
830ccb2b4f59574852753932a0b29ff4
30.805556
122
0.689956
3.74183
false
false
false
false
catloafsoft/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Convolution.xcplaygroundpage/Contents.swift
1
1396
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Convolution //: ### Allows you to create a large variety of effects, usually reverbs or environments, but it could also be for modeling. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true let stairwell = bundle.URLForResource("Impulse Responses/stairwell", withExtension: "wav")! let dish = bundle.URLForResource("Impulse Responses/dish", withExtension: "wav")! var stairwellConvolution = AKConvolution.init(player, impulseResponseFileURL: stairwell, partitionLength: 8192) var dishConvolution = AKConvolution.init(player, impulseResponseFileURL: dish, partitionLength: 8192) var mixer = AKDryWetMixer(stairwellConvolution, dishConvolution, balance: 1) AudioKit.output = mixer AudioKit.start() stairwellConvolution.start() dishConvolution.start() player.play() var increment = 0.01 AKPlaygroundLoop(every: 3.428/100.0) { () -> () in mixer.balance += increment if mixer.balance >= 1 && increment > 0 { increment = -0.01 } if mixer.balance <= 0 && increment < 0 { increment = 0.01 } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
d8484dd45a0efc5117c42dcc9d7e0ead
30.727273
124
0.722779
3.888579
false
false
false
false
hectr/swift-idioms
Sources/Idioms/StringProtocol+Subscript.swift
1
3144
// Copyright (c) 2019 Hèctor Marquès Ranea // // 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 // Source: https://stackoverflow.com/a/38215613 extension StringProtocol { public subscript(offset: Int) -> Element? { guard offset >= 0 else { return nil } guard let index = index(startIndex, offsetBy: offset, limitedBy: index(before: endIndex)) else { return nil } return self[index] } public subscript(_ range: Range<Int>) -> SubSequence? { guard range.lowerBound >= 0 else { return nil } let prefixLength = range.lowerBound + range.count guard prefixLength >= 0 else { return nil } guard prefixLength <= count else { return nil } return prefix(prefixLength).suffix(range.count) } public subscript(range: ClosedRange<Int>) -> SubSequence? { guard range.lowerBound >= 0 else { return nil } let prefixLength = range.lowerBound + range.count guard prefixLength >= 0 else { return nil } guard prefixLength <= count else { return nil } return prefix(prefixLength).suffix(range.count) } public subscript(range: PartialRangeThrough<Int>) -> SubSequence? { guard range.upperBound >= 0 else { return nil } let prefixLength = range.upperBound.advanced(by: 1) guard prefixLength >= 0 else { return nil } guard prefixLength <= count else { return nil } return prefix(prefixLength) } public subscript(range: PartialRangeUpTo<Int>) -> SubSequence? { guard range.upperBound >= 0 else { return nil } let prefixLength = range.upperBound guard prefixLength >= 0 else { return nil } guard prefixLength <= count else { return nil } return prefix(prefixLength) } public subscript(range: PartialRangeFrom<Int>) -> SubSequence? { guard range.lowerBound >= 0 else { return nil } let suffixLength = count - range.lowerBound guard suffixLength >= 0 else { return nil } guard suffixLength <= count else { return nil } return suffix(suffixLength) } }
mit
28cea6066f45a5477b3966276430ce88
43.253521
117
0.688097
4.717718
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
ObjectMapperGuideRead_Jeff/ObjectGuide/ObjectGuide/ObjectMapper/ObjectMapperDemo.swift
2
3178
/* Swift - 使用ObjectMapper实现模型转换1 http://www.hangge.com/blog/cache/detail_1673.html */ import Foundation class User: Mappable { var username: String? var age: Int? var weight: Double! var bestFriend: User? // User对象 var friends: [User]? // Users数组 var birthday: Date? var array: [AnyObject]? var dictionary: [String : AnyObject] = [:] init(){ } required init?(map: Map) { // 在对象序列化之前验证 JSON 合法性。在不符合的条件时,返回 nil 阻止映射发生。 if map.JSON["username"] == nil { return nil } /* let json = "[{\"age\":18,\"username\":\"李雷\"},{\"age\":17}]" let users:[User] = Mapper<User>().mapArray(JSONString: json)! print(users.count) // 1 */ } // Mappable func mapping(map: Map) { username <- map["username"] age <- map["age"] weight <- map["weight"] bestFriend <- map["best_friend"] friends <- map["friends"] birthday <- (map["birthday"], DateTransform()) array <- map["arr"] dictionary <- map["dict"] } //MARK: Model -> Dictionary class func modelWithDict() { let lilei = User() lilei.username = "李雷" lilei.age = 18 let meimei = User() meimei.username = "梅梅" meimei.age = 17 meimei.bestFriend = lilei // // model -> dict // let meimeiDic:[String: Any] = meimei.toJSON() // print("meimeiDic\n \(meimeiDic)") // // // [model] -> [dict] // let users = [lilei, meimei] // let usersArray:[[String: Any]] = users.toJSON() // print("usersArray\n \(usersArray)") let dic = ["age": 17, "best_friend": ["dict": [:], "age": 18, "username": "李雷"], "username": "梅梅", "dict": [:]] as [String : Any] // dict -> model let meimeiModel = User(JSON: dic) print("meimeiModel\n \(String(describing: meimeiModel))") // [dict] -> [model] // let usersArray2:[User] = Mapper<User>().mapArray(JSONArray: usersArray) // print("usersArray2\n \(String(describing: usersArray2))") } //MARK: Model -> JSONString class func modelWithJSONString() { let lilei = User() lilei.username = "李雷" lilei.age = 18 let meimei = User() meimei.username = "梅梅" meimei.age = 17 meimei.bestFriend = lilei // model to json string let meimeiJSON:String = meimei.toJSONString()! print(meimeiJSON) // [model] to json string let users = [lilei, meimei] let json:String = users.toJSONString()! print(json) // json string to model let meimei2 = User(JSONString: meimeiJSON) print(meimei2) // json string to [model] let users2:[User] = Mapper<User>().mapArray(JSONString: json)! print(users2) } }
mit
4e94596879622d35ee8a7b0e02517a4f
27.091743
137
0.507185
4.050265
false
false
false
false
alblue/swift-corelibs-foundation
Foundation/Data.swift
1
82686
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif public final class _DataStorage { public enum Backing { // A mirror of the Objective-C implementation that is suitable to inline in Swift case swift // these two storage points for immutable and mutable data are reserved for references that are returned by "known" // cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that // the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok // to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be // dynamically dispatched out to the reference. case immutable(NSData) // This will most often (perhaps always) be NSConcreteData case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData // These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong // to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes, // and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the // backing reference. case customReference(NSData) // tracks data references that are only known to be immutable case customMutableReference(NSMutableData) // tracks data references that are known to be mutable } public static let maxSize = Int.max >> 1 public static let vmOpsThreshold = NSPageSize() * 4 public static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } public static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } public static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } public var _bytes: UnsafeMutableRawPointer? public var _length: Int public var _capacity: Int public var _needToZero: Bool public var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? public var _backing: Backing = .swift public var _offset: Int public var bytes: UnsafeRawPointer? { @inline(__always) get { switch _backing { case .swift: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .immutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .mutable: return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) case .customReference(let d): return d.bytes.advanced(by: -_offset) case .customMutableReference(let d): return d.bytes.advanced(by: -_offset) } } } @discardableResult public func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } case .customMutableReference(let d): if __NSDataIsCompact(d) { let len = d.length guard len > 0 else { return try apply(UnsafeRawBufferPointer(start: nil, count: 0)) } return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len))) } else { var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment) defer { buffer.deallocate() } let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count) var enumerated = 0 d.enumerateBytes { (ptr, byteRange, stop) in if byteRange.upperBound - _offset < range.lowerBound { // before the range that we are looking for... } else if byteRange.lowerBound - _offset > range.upperBound { stop.pointee = true // we are past the range in question so we need to stop } else { // the byteRange somehow intersects the range in question that we are looking for... let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound) let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound) let len = upper - lower memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len) enumerated += len if upper == range.upperBound { stop.pointee = true } } } return try apply(UnsafeRawBufferPointer(buffer)) } } } @discardableResult public func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch _backing { case .swift: fallthrough case .mutable: return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customMutableReference(let d): let len = d.length return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData _backing = .mutable(data) _bytes = data.mutableBytes return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length))) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData _backing = .customMutableReference(data) let len = data.length return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len))) } } public var mutableBytes: UnsafeMutableRawPointer? { @inline(__always) get { switch _backing { case .swift: return _bytes?.advanced(by: -_offset) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _bytes = data.mutableBytes return _bytes?.advanced(by: -_offset) case .mutable: return _bytes?.advanced(by: -_offset) case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) return data.mutableBytes.advanced(by: -_offset) case .customMutableReference(let d): return d.mutableBytes.advanced(by: -_offset) } } } public var length: Int { @inline(__always) get { switch _backing { case .swift: return _length case .immutable: return _length case .mutable: return _length case .customReference(let d): return d.length case .customMutableReference(let d): return d.length } } @inline(__always) set { setLength(newValue) } } public func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } } public func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false var data: NSData switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv) return case .customReference(let d): data = d break case .customMutableReference(let d): data = d break } data.enumerateBytes { (ptr, region, stop) in // any region that is not in the range should be skipped guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return } var regionAdjustment = 0 if region.lowerBound < range.lowerBound { regionAdjustment = range.lowerBound - (region.lowerBound - _offset) } let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self) let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset) block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv) if stopv { stop.pointee = true } } } @inline(never) public func _grow(_ newLength: Int, _ clear: Bool) { let cap = _capacity var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = Swift.max(cap, newLength + additionalCapacity) let origLength = _length var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = _DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength) newBytes = _DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() _deallocator = nil } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = newLength allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { _DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } @inline(__always) public func setLength(_ length: Int) { switch _backing { case .swift: let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _length = length _bytes = data.mutableBytes case .mutable(let d): d.length = length _length = length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) case .customMutableReference(let d): d.length = length } } @inline(__always) public func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") switch _backing { case .swift: let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { _grow(newLength, false) } _length = newLength _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.append(bytes, length: length) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .customMutableReference(data) case .customMutableReference(let d): d.append(bytes, length: length) } } // fast-path for appending directly from another data storage @inline(__always) public func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) { let otherLength = otherData.length if otherLength == 0 { return } if let bytes = otherData.bytes { append(bytes.advanced(by: start), length: end - start) } } @inline(__always) public func append(_ otherData: Data) { otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in append(buffer.baseAddress!, length: buffer.count) } } @inline(__always) public func increaseLength(by extraLength: Int) { if extraLength == 0 { return } switch _backing { case .swift: let origLength = _length let newLength = origLength + extraLength if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if _needToZero { memset(_bytes!.advanced(by: origLength), 0, extraLength) } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .mutable(data) _length += extraLength _bytes = data.mutableBytes case .mutable(let d): d.increaseLength(by: extraLength) _length += extraLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .customReference(data) case .customMutableReference(let d): d.increaseLength(by: extraLength) } } public func get(_ index: Int) -> UInt8 { switch _backing { case .swift: fallthrough case .immutable: fallthrough case .mutable: return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee case .customReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } case .customMutableReference(let d): if __NSDataIsCompact(d) { return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } else { var byte: UInt8 = 0 d.enumerateBytes { (ptr, range, stop) in if NSLocationInRange(index, range) { let offset = index - range.location - _offset byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee stop.pointee = true } } return byte } } } @inline(__always) public func set(_ index: Int, to value: UInt8) { switch _backing { case .swift: fallthrough case .mutable: _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value default: var theByte = value let range = NSRange(location: index, length: 1) replaceBytes(in: range, with: &theByte, length: 1) } } @inline(__always) public func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } _DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!) } } @inline(__always) public func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength switch _backing { case .swift: let shift = resultingLength - currentLength var mutableBytes = _bytes if resultingLength > currentLength { setLength(resultingLength) mutableBytes = _bytes! } /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes! + start, replacementBytes, replacementLength) } else { memset(mutableBytes! + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(d) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) } } @inline(__always) public func resetBytes(in range_: NSRange) { let range = NSRange(location: range_.location - _offset, length: range_.length) if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } memset(_bytes!.advanced(by: range.location), 0, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.resetBytes(in: range) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .customMutableReference(data) case .customMutableReference(let d): d.resetBytes(in: range) } } public convenience init() { self.init(capacity: 0) } public init(length: Int) { precondition(length < _DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = _DataStorage.shouldAllocateCleared(length) _bytes = _DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } public init(capacity capacity_: Int) { var capacity = capacity_ precondition(capacity < _DataStorage.maxSize) if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } public init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < _DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) } } public init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < _DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } public init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _backing = .immutable(immutableReference) } public init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _backing = .mutable(mutableReference) } public init(customReference: NSData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customReference(customReference) } public init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customMutableReference(customMutableReference) } deinit { switch _backing { case .swift: _freeBytes() default: break } } @inline(__always) public func mutableCopy(_ range: Range<Int>) -> _DataStorage { switch _backing { case .swift: return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound) } } } public func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } switch _backing { case .swift: return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false)) } return try work(d) case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false)) } return try work(d) } } public func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } switch _backing { case .swift: return _NSSwiftData(backing: self, range: range) case .immutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .mutable(let d): guard range.lowerBound == 0 && range.upperBound == _length else { return _NSSwiftData(backing: self, range: range) } return d case .customReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return _NSSwiftData(backing: self, range: range) } return d case .customMutableReference(let d): guard range.lowerBound == 0 && range.upperBound == d.length else { return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC() } return d.copy() as! NSData } } public func subdata(in range: Range<Data.Index>) -> Data { switch _backing { case .customReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) case .customMutableReference(let d): return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count)) default: return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count) } } } internal class _NSSwiftData : NSData { var _backing: _DataStorage! var _range: Range<Data.Index>! convenience init(backing: _DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } override var length: Int { return _range.count } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } override func copy(with zone: NSZone? = nil) -> Any { return self } override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> @usableFromInline internal var _backing : _DataStorage @usableFromInline internal var _sliceRange: Range<Index> // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes: UnsafeRawPointer, count: Int) { _backing = _DataStorage(bytes: bytes, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of an Array. /// /// - parameter bytes: An array of bytes to copy. public init(bytes: Array<UInt8>) { let count = bytes.count _backing = bytes.withUnsafeBufferPointer { return _DataStorage(bytes: $0.baseAddress, length: count) } _sliceRange = 0..<count } /// Initialize a `Data` with the contents of an Array. /// /// - parameter bytes: An array of bytes to copy. public init(bytes: ArraySlice<UInt8>) { let count = bytes.count _backing = bytes.withUnsafeBufferPointer { return _DataStorage(bytes: $0.baseAddress, length: count) } _sliceRange = 0..<count } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in memset(bytes, Int32(repeatedValue), count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. public init(capacity: Int) { _backing = _DataStorage(capacity: capacity) _sliceRange = 0..<0 } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. public init(count: Int) { _backing = _DataStorage(length: count) _sliceRange = 0..<count } /// Initialize an empty `Data`. public init() { _backing = _DataStorage(length: 0) _sliceRange = 0..<0 } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d, offset: 0) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: NSData) { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } else { _backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0) _sliceRange = 0..<reference.length } } // slightly faster paths for common sequences public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 { if elements is Array<UInt8> { self.init(bytes: _identityCast(elements, to: Array<UInt8>.self)) } else if elements is ArraySlice<UInt8> { self.init(bytes: _identityCast(elements, to: ArraySlice<UInt8>.self)) } else if elements is UnsafeBufferPointer<UInt8> { self.init(buffer: _identityCast(elements, to: UnsafeBufferPointer<UInt8>.self)) } else if let buffer = elements as? UnsafeMutableBufferPointer<UInt8> { self.init(buffer: buffer) } else if let data = elements as? Data { let len = data.count let backing = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in return _DataStorage(bytes: bytes, length: len) } self.init(backing: backing, range: 0..<len) } else { let underestimatedCount = elements.underestimatedCount self.init(count: underestimatedCount) let (endIterator, _) = UnsafeMutableBufferPointer(start: _backing._bytes?.assumingMemoryBound(to: UInt8.self), count: underestimatedCount).initialize(from: elements) var iter = endIterator while let byte = iter.next() { self.append(byte) } } } @usableFromInline internal init(backing: _DataStorage, range: Range<Index>) { _backing = backing _sliceRange = range } @usableFromInline internal func _validateIndex(_ index: Int, message: String? = nil) { precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)") } @usableFromInline internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let r = range.relative(to: lower..<upper) precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)") } // ----------------------------------- // MARK: - Properties and Functions /// The number of bytes in the data. public var count: Int { @inline(__always) get { return _sliceRange.count } @inline(__always) set { precondition(count >= 0, "count must not be negative") if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.length = newValue _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue) } } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @inline(__always) public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _backing.withUnsafeBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @inline(__always) public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } return try _backing.withUnsafeMutableBytes(in: _sliceRange) { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @inline(__always) public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _backing.withUnsafeBytes(in: _sliceRange) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count)) } } @inline(__always) private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { if range.length == 0 { return } _backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) { memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count)) } } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: NSRange(range)) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } _validateRange(copyRange) guard !copyRange.isEmpty else { return 0 } let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound) _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT @inline(__always) private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { try _backing.withInteriorPointerReference(_sliceRange) { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { _validateRange(r) nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _backing.withInteriorPointerReference(_sliceRange) { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _backing.enumerateBytes(in: _sliceRange, block) } @inline(__always) public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } append(UnsafeBufferPointer(start: bytes, count: count)) } @inline(__always) public mutating func append(_ other: Data) { other.enumerateBytes { (buffer, _, _) in append(buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. @inline(__always) public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride) } @inline(__always) public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element { let estimatedCount = newElements.underestimatedCount guard estimatedCount > 0 else { for byte in newElements { append(byte) } return } _withStackOrHeapBuffer(estimatedCount) { allocation in let buffer = UnsafeMutableBufferPointer(start: allocation.pointee.memory.assumingMemoryBound(to: UInt8.self), count: estimatedCount) var (iterator, endPoint) = newElements._copyContents(initializing: buffer) append(buffer.baseAddress!, count: endPoint - buffer.startIndex) while let byte = iterator.next() { append(byte) } } } @inline(__always) public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in append(buffer) } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. @inline(__always) public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.resetBytes(in: range) if _sliceRange.upperBound < range.upperBound { _sliceRange = _sliceRange.lowerBound..<range.upperBound } } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. @inline(__always) public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { let cnt = data.count data.withUnsafeBytes { replaceSubrange(subrange, with: $0, count: cnt) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. @inline(__always) public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. @inline(__always) public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { _validateRange(subrange) let totalCount: Int = numericCast(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } @inline(__always) public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _validateRange(subrange) let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let upper = _sliceRange.upperBound _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt _sliceRange = _sliceRange.lowerBound..<resultingUpper } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. @inline(__always) public func subdata(in range: Range<Index>) -> Data { _validateRange(range) if isEmpty { return Data() } return _backing.subdata(in: range) } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. public var hashValue: Int { var hashValue = 0 let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound) _withStackOrHeapBuffer(hashRange.count + 1) { buffer in if !hashRange.isEmpty { _backing.withUnsafeBytes(in: hashRange) { memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count) } } hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count)) } return hashValue } @inline(__always) public func advanced(by amount: Int) -> Data { _validateIndex(startIndex + amount) let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in return Data(bytes: ptr.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { @inline(__always) get { _validateIndex(index) return _backing.get(index) } @inline(__always) set { _validateIndex(index) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.set(index, to: newValue) } } public subscript(bounds: Range<Index>) -> Data { @inline(__always) get { _validateRange(bounds) return Data(backing: _backing, range: bounds) } @inline(__always) set { replaceSubrange(bounds, with: newValue) } } public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger { @inline(__always) get { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) return Data(backing: _backing, range: r) } @inline(__always) set { let lower = R.Bound(_sliceRange.lowerBound) let upper = R.Bound(_sliceRange.upperBound) let range = rangeExpression.relative(to: lower..<upper) let start: Int = numericCast(range.lowerBound) let end: Int = numericCast(range.upperBound) let r: Range<Int> = start..<end _validateRange(r) replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. public var startIndex: Index { @inline(__always) get { return _sliceRange.lowerBound } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { @inline(__always) get { return _sliceRange.upperBound } } @inline(__always) public func index(before i: Index) -> Index { return i - 1 } @inline(__always) public func index(after i: Index) -> Index { return i + 1 } public var indices: Range<Int> { @inline(__always) get { return startIndex..<endIndex } } public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } guard let p = buffer.baseAddress else { preconditionFailure("Attempt to copy contents into nil buffer pointer") } let cnt = count precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents") withUnsafeBytes { p.initialize(from: $0, count: cnt) } return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> Data.Iterator { return Iterator(self) } public struct Iterator : IteratorProtocol { // Both _data and _endIdx should be 'let' rather than 'var'. // They are 'var' so that the stored properties can be read // independently of the other contents of the struct. This prevents // an exclusivity violation when reading '_endIdx' and '_data' // while simultaneously mutating '_buffer' with the call to // withUnsafeMutablePointer(). Once we support accessing struct // let properties independently we should make these variables // 'let' again. private var _data: Data private var _buffer: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) private var _idx: Data.Index private var _endIdx: Data.Index fileprivate init(_ data: Data) { _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.startIndex _endIdx = data.endIndex } fileprivate init(endOf data: Data) { self._data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = data.endIndex _endIdx = data.endIndex } public mutating func next() -> UInt8? { guard _idx < _endIdx else { return nil } defer { _idx += 1 } let bufferSize = MemoryLayout.size(ofValue: _buffer) return withUnsafeMutablePointer(to: &_buffer) { ptr_ in let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self) let bufferIdx = (_idx - _data.startIndex) % bufferSize if bufferIdx == 0 { // populate the buffer _data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx)) } return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. public static func ==(d1 : Data, d2 : Data) -> Bool { let backing1 = d1._backing let backing2 = d2._backing if backing1 === backing2 { if d1._sliceRange == d2._sliceRange { return true } } let length1 = d1.count if length1 != d2.count { return false } if backing1.bytes == backing2.bytes { if d1._sliceRange == d2._sliceRange { return true } } if length1 > 0 { return d1.withUnsafeBytes { (b1) in return d2.withUnsafeBytes { (b2) in return memcmp(b1, b2, length1) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in children.append((label: "pointer", value: bytes)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: .struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _backing.bridgedReference(_sliceRange) } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() // Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped. var caughtError: Error? = nil self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in do { try container.encode(contentsOf: buffer) } catch { caughtError = error stop = true } } if let error = caughtError { throw error } } }
apache-2.0
1d8cfe40ef57deef57ea34b0349d26e5
40.612481
352
0.591058
4.915522
false
false
false
false
grgcombs/PlayingCards-Swift
Pod/Classes/CardGlyphs.swift
1
2700
// // CardGlyphs.swift // Pods // // Created by Gregory Combs on 7/23/15. // Copyright (c) 2015 PlayingCards (Swift). All rights reserved. // import Foundation internal typealias CardGlyphMap = [CardType : String]; internal typealias SuitGlyphMap = [SuitType : CardGlyphMap]; internal class CardGlyphs { static func glyphForSuit(suiteType:SuitType, cardType:CardType) -> String? { if let glyphs = SharedCardGlyphs.cardGlyphs[suiteType] ?? nil { return glyphs[cardType] ?? nil; } return nil; } } /** * The singleton ensures the (expensive) setup is completed only once, * no matter how many times you need to access the card glyphs. */ private let SharedCardGlyphs : CardGlyphsPrivate = CardGlyphsPrivate(); private class CardGlyphsPrivate { init() { var emptyMap : SuitGlyphMap = [:]; cardGlyphs = SuitType.allValues.map({ ($0, $0.cardGlyphMap) }).reduce(emptyMap, combine: { var map : SuitGlyphMap = $0; let tuple : GlyphTuple = $1; map[tuple.suiteType] = tuple.cardGlyphs; return map; }); } private typealias GlyphTuple = (suiteType: SuitType, cardGlyphs: CardGlyphMap); private let cardGlyphs : SuitGlyphMap; } private extension SuitType { private typealias IndexedCardTypeTuple = (index: Int, element: CardType); private typealias RangeWithExclusion = (range: Range<Int>, exclude: Int); private var cardGlyphRange : RangeWithExclusion { get { switch self { case .Spades: return (0x1F0A1...0x1F0AE, 0x1F0AC); case .Hearts: return (0x1F0B1...0x1F0BE, 0x1F0BC); case .Diamonds: return (0x1F0C1...0x1F0CE, 0x1F0CC); case .Clubs: return (0x1F0D1...0x1F0DE, 0x1F0DC); } } } private var cardGlyphMap : CardGlyphMap { get { var cardTypes = EnumerateGenerator(CardType.allValues.generate()) let range = cardGlyphRange; var glyphs : CardGlyphMap = [:]; for code in range.range { if code == range.exclude { continue; } let scalar = UnicodeScalar(code); let char = Character(scalar); if let tuple : IndexedCardTypeTuple = cardTypes.next() { let cardType = tuple.element; glyphs[cardType] = "\(char)"; continue; } break; // no more next()'s, time to quit } return glyphs; } } }
mit
e2afa20a06e539a2f63842e431651cb6
27.723404
83
0.566667
4.272152
false
false
false
false
abunur/quran-ios
UIKitExtension/ActivityIndicator.swift
1
2215
// // ActivityIndicator.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift import RxCocoa #endif private struct ActivityToken<E> : ObservableConvertibleType, Disposable { private let _source: Observable<E> private let _dispose: Cancelable init(source: Observable<E>, disposeAction: @escaping () -> ()) { _source = source _dispose = Disposables.create(with: disposeAction) } func dispose() { _dispose.dispose() } func asObservable() -> Observable<E> { return _source } } /** Enables monitoring of sequence computation. If there is at least one sequence computation in progress, `true` will be sent. When all activities complete `false` will be sent. */ public class ActivityIndicator : SharedSequenceConvertibleType { public typealias E = Bool public typealias SharingStrategy = DriverSharingStrategy private let _lock = NSRecursiveLock() private let _variable = Variable(0) private let _loading: SharedSequence<SharingStrategy, Bool> public init() { _loading = _variable.asDriver() .map { $0 > 0 } .distinctUntilChanged() } fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> { return Observable.using({ () -> ActivityToken<O.E> in self.increment() return ActivityToken(source: source.asObservable(), disposeAction: self.decrement) }) { t in return t.asObservable() } } private func increment() { _lock.lock() _variable.value = _variable.value + 1 _lock.unlock() } private func decrement() { _lock.lock() _variable.value = _variable.value - 1 _lock.unlock() } public func asSharedSequence() -> SharedSequence<SharingStrategy, E> { return _loading } } extension ObservableConvertibleType { public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> { return activityIndicator.trackActivityOfObservable(self) } }
gpl-3.0
ead6b534ba631d98a7b6f844d143be71
26
110
0.6486
4.690678
false
false
false
false
rice-apps/wellbeing-app
app/Pods/Socket.IO-Client-Swift/Source/SocketEngineSpec.swift
2
6919
// // SocketEngineSpec.swift // Socket.IO-Client-Swift // // Created by Erik Little on 10/7/15. // // 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 /// Specifies a SocketEngine. @objc public protocol SocketEngineSpec { /// The client for this engine. weak var client: SocketEngineClient? { get set } /// `true` if this engine is closed. var closed: Bool { get } /// `true` if this engine is connected. Connected means that the initial poll connect has succeeded. var connected: Bool { get } /// The connect parameters sent during a connect. var connectParams: [String: Any]? { get set } /// Set to `true` if using the node.js version of socket.io. The node.js version of socket.io /// handles utf8 incorrectly. var doubleEncodeUTF8: Bool { get } /// An array of HTTPCookies that are sent during the connection. var cookies: [HTTPCookie]? { get } /// The queue that all engine actions take place on. var engineQueue: DispatchQueue { get } /// A dictionary of extra http headers that will be set during connection. var extraHeaders: [String: String]? { get } /// When `true`, the engine is in the process of switching to WebSockets. var fastUpgrade: Bool { get } /// When `true`, the engine will only use HTTP long-polling as a transport. var forcePolling: Bool { get } /// When `true`, the engine will only use WebSockets as a transport. var forceWebsockets: Bool { get } /// If `true`, the engine is currently in HTTP long-polling mode. var polling: Bool { get } /// If `true`, the engine is currently seeing whether it can upgrade to WebSockets. var probing: Bool { get } /// The session id for this engine. var sid: String { get } /// The path to engine.io. var socketPath: String { get } /// The url for polling. var urlPolling: URL { get } /// The url for WebSockets. var urlWebSocket: URL { get } /// If `true`, then the engine is currently in WebSockets mode. var websocket: Bool { get } /// The WebSocket for this engine. var ws: WebSocket? { get } /// Creates a new engine. /// /// - parameter client: The client for this engine. /// - parameter url: The url for this engine. /// - parameter options: The options for this engine. init(client: SocketEngineClient, url: URL, options: NSDictionary?) /// Starts the connection to the server. func connect() /// Called when an error happens during execution. Causes a disconnection. func didError(reason: String) /// Disconnects from the server. /// /// - parameter reason: The reason for the disconnection. This is communicated up to the client. func disconnect(reason: String) /// Called to switch from HTTP long-polling to WebSockets. After calling this method the engine will be in /// WebSocket mode. /// /// **You shouldn't call this directly** func doFastUpgrade() /// Causes any packets that were waiting for POSTing to be sent through the WebSocket. This happens because when /// the engine is attempting to upgrade to WebSocket it does not do any POSTing. /// /// **You shouldn't call this directly** func flushWaitingForPostToWebSocket() /// Parses raw binary received from engine.io. /// /// - parameter data: The data to parse. func parseEngineData(_ data: Data) /// Parses a raw engine.io packet. /// /// - parameter message: The message to parse. /// - parameter fromPolling: Whether this message is from long-polling. /// If `true` we might have to fix utf8 encoding. func parseEngineMessage(_ message: String, fromPolling: Bool) /// Writes a message to engine.io, independent of transport. /// /// - parameter msg: The message to send. /// - parameter withType: The type of this message. /// - parameter withData: Any data that this message has. func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) } extension SocketEngineSpec { var urlPollingWithSid: URL { var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)! com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)" return com.url! } var urlWebSocketWithSid: URL { var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)! com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)") return com.url! } func createBinaryDataForSend(using data: Data) -> Either<Data, String> { if websocket { var byteArray = [UInt8](repeating: 0x4, count: 1) let mutData = NSMutableData(bytes: &byteArray, length: 1) mutData.append(data) return .left(mutData as Data) } else { let str = "b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) return .right(str) } } func doubleEncodeUTF8(_ string: String) -> String { if let latin1 = string.data(using: String.Encoding.utf8), let utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) { return utf8 as String } else { return string } } func fixDoubleUTF8(_ string: String) -> String { if let utf8 = string.data(using: String.Encoding.isoLatin1), let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) { return latin1 as String } else { return string } } /// Send an engine message (4) func send(_ msg: String, withData datas: [Data]) { write(msg, withType: .message, withData: datas) } }
mit
f5486f25616f5cece0f410d1e45c53ad
35.415789
116
0.658332
4.449518
false
false
false
false
sora0077/iTunesMusicKit
src/Endpoint/GetPreviewUrl.swift
1
1555
// // GetPreviewUrl.swift // iTunesMusicKit // // Created by 林達也 on 2015/10/16. // Copyright © 2015年 jp.sora0077. All rights reserved. // import Foundation import APIKit public struct GetPreviewUrl { public let id: String public let url: String init(id: String, url: String) { self.id = id self.url = url } } public extension GetPreviewUrl { init(track: Track) { self.init(id: track.id, url: track.url) } } extension GetPreviewUrl: iTunesRequestToken { public typealias Response = String public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .GET } public var path: String { return url } public var headers: [String : String]? { return [ "X-Apple-Store-Front": "143462-9,4", ] } public var serializer: Serializer { return .PropertyList(.Immutable) } public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { let items = object["items"] as! [[String: AnyObject]] // print(items as NSArray) for item in items { let id = String(item["item-id"] as! Int) if self.id == id { let previewUrl = item["store-offers"]!["PLUS"]!!["preview-url"] as! String return previewUrl } } throw Error.Unknown } }
mit
de3fbab258de63d668aeb702e7eb22cc
20.774648
126
0.562743
4.330532
false
false
false
false
xxxAIRINxxx/Cmg
Sources/Generator.swift
1
14212
// // Generator.swift // Cmg // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit import CoreImage public struct AztecCodeGenerator: InputImageUnusable, FilterInputCollectionType, InputMessageAvailable, InputCorrectionLevelAvailable, InputLayersAvailable, InputCompactStyleAvailable { public let filter: CIFilter = CIFilter(name: "CIAztecCodeGenerator")! public let inputMessage: StringInput public let inputCorrectionLevel: ScalarInput public let inputLayers: ScalarInput public let inputCompactStyle: BooleanInput public init(message: String) { self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message) self.inputCorrectionLevel = ScalarInput(filter: self.filter, key: "inputCorrectionLevel") self.inputLayers = ScalarInput(filter: self.filter, key: "inputLayers") self.inputCompactStyle = BooleanInput(filter: self.filter, key: "inputCompactStyle") } public func inputs() -> [FilterInputable] { return [ self.inputMessage, self.inputCorrectionLevel, self.inputLayers, self.inputCompactStyle ] } } public struct CheckerboardGenerator: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputColor0Available, InputColor1Available, InputWidthAvailable, InputSharpnessAvailable { public let filter: CIFilter = CIFilter(name: "CICheckerboardGenerator")! public let inputCenter: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public let inputWidth: ScalarInput public let inputSharpness: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey) self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey) } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor0, self.inputColor1, self.inputWidth, self.inputSharpness ] } } public struct Code128BarcodeGenerator: InputImageUnusable, FilterInputCollectionType, InputMessageAvailable, InputQuietSpaceAvailable { public let filter: CIFilter = CIFilter(name: "CICode128BarcodeGenerator")! public let inputMessage: StringInput public let inputQuietSpace: ScalarInput public init(message: String) { self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message, true, String.Encoding.ascii.rawValue) self.inputQuietSpace = ScalarInput(filter: self.filter, key: "inputQuietSpace") } public func inputs() -> [FilterInputable] { return [ self.inputMessage, self.inputQuietSpace ] } } public struct ConstantColorGenerator: InputImageUnusable, FilterInputCollectionType, InputColorAvailable { public let filter: CIFilter = CIFilter(name: "CIConstantColorGenerator")! public let inputColor: ColorInput public init() { self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey) } public func inputs() -> [FilterInputable] { return [ self.inputColor ] } } @available(iOS 9.0, *) public struct LenticularHaloGenerator: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputColorAvailable, InputHaloRadiusAvailable, InputHaloWidthAvailable, InputHaloOverlapAvailable, InputStriationStrengthAvailable, InputStriationContrastAvailable, InputTimeAvailable { public let filter: CIFilter = CIFilter(name: "CILenticularHaloGenerator")! public let inputCenter: VectorInput public let inputColor: ColorInput public let inputHaloRadius: ScalarInput public let inputHaloWidth: ScalarInput public let inputHaloOverlap: ScalarInput public let inputStriationStrength: ScalarInput public let inputStriationContrast: ScalarInput public let inputTime: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey) self.inputHaloRadius = ScalarInput(filter: self.filter, key: "inputHaloRadius") self.inputHaloWidth = ScalarInput(filter: self.filter, key: "inputHaloWidth") self.inputHaloOverlap = ScalarInput(filter: self.filter, key: "inputHaloOverlap") self.inputStriationStrength = ScalarInput(filter: self.filter, key: "inputStriationStrength") self.inputStriationContrast = ScalarInput(filter: self.filter, key: "inputStriationContrast") self.inputTime = ScalarInput(filter: self.filter, key: "inputTime") } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor, self.inputHaloRadius, self.inputHaloWidth, self.inputHaloOverlap, self.inputStriationStrength, self.inputStriationContrast, self.inputTime ] } } @available(iOS 9.0, *) public struct PDF417BarcodeGenerator: InputImageUnusable, FilterInputCollectionType, InputMessageAvailable, InputMinWidthAvailable, InputMaxWidthAvailable, InputMinHeightAvailable, InputMaxHeightAvailable, InputDataColumnsAvailable, InputRowsAvailable, InputPreferredAspectRatioAvailable, InputCompactionModeAvailable, InputCompactStyleAvailable, InputCorrectionLevelAvailable, InputAlwaysSpecifyCompactionAvailable { public let filter: CIFilter = CIFilter(name: "CIPDF417BarcodeGenerator")! public let inputMessage: StringInput public let inputMinWidth: VectorInput public let inputMaxWidth: VectorInput public let inputMinHeight: VectorInput public let inputMaxHeight: VectorInput public let inputDataColumns: ScalarInput public let inputRows: ScalarInput public let inputPreferredAspectRatio: ScalarInput public let inputCompactionMode: ScalarInput public let inputCompactStyle: BooleanInput public let inputCorrectionLevel: ScalarInput public let inputAlwaysSpecifyCompaction: ScalarInput public init(inputMessage: String, imageSize: CGSize) { self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", inputMessage, true, String.Encoding.isoLatin1.rawValue) self.inputMinWidth = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMinWidth") self.inputMaxWidth = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMaxWidth") self.inputMinHeight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMinHeight") self.inputMaxHeight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMaxHeight") self.inputDataColumns = ScalarInput(filter: self.filter, key: "inputDataColumns") self.inputRows = ScalarInput(filter: self.filter, key: "inputRows", 45.0) self.inputPreferredAspectRatio = ScalarInput(filter: self.filter, key: "inputPreferredAspectRatio") self.inputCompactionMode = ScalarInput(filter: self.filter, key: "inputCompactionMode") self.inputCompactStyle = BooleanInput(filter: self.filter, key: "inputCompactStyle") self.inputCorrectionLevel = ScalarInput(filter: self.filter, key: "inputCorrectionLevel") self.inputAlwaysSpecifyCompaction = ScalarInput(filter: self.filter, key: "inputAlwaysSpecifyCompaction") } public func inputs() -> [FilterInputable] { return [ self.inputMessage, self.inputMinWidth, self.inputMaxWidth, self.inputMinHeight, self.inputMaxHeight, self.inputDataColumns, self.inputRows, self.inputPreferredAspectRatio, self.inputCompactionMode, self.inputCompactStyle, self.inputCorrectionLevel, self.inputAlwaysSpecifyCompaction ] } } public struct QRCodeGenerator: InputImageUnusable, FilterInputCollectionType, InputMessageAvailable, InputStringCorrectionLevelAvailable { public let filter: CIFilter = CIFilter(name: "CIQRCodeGenerator")! public let inputMessage: StringInput public let inputStringCorrectionLevel: StringInput public init(message: String) { self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message) self.inputStringCorrectionLevel = StringInput(filter: self.filter, key: "inputCorrectionLevel", nil, false) } public func inputs() -> [FilterInputable] { return [ self.inputMessage, self.inputStringCorrectionLevel ] } } public struct RandomGenerator: InputImageUnusable { public let filter: CIFilter = CIFilter(name: "CIRandomGenerator")! public init() {} } public struct StarShineGenerator: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputColorAvailable, InputRadiusAvailable, InputCrossScaleAvailable, InputCrossAngleAvailable, InputCrossOpacityAvailable, InputCrossWidthAvailable, InputEpsilonAvailable { public let filter: CIFilter = CIFilter(name: "CIStarShineGenerator")! public let inputCenter: VectorInput public let inputColor: ColorInput public let inputRadius: ScalarInput public let inputCrossScale: ScalarInput public let inputCrossAngle: ScalarInput public let inputCrossOpacity: ScalarInput public let inputCrossWidth: ScalarInput public let inputEpsilon: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey) self.inputRadius = ScalarInput(filter: self.filter, key: kCIInputRadiusKey) self.inputCrossScale = ScalarInput(filter: self.filter, key: "inputCrossScale") self.inputCrossAngle = ScalarInput(filter: self.filter, key: "inputCrossAngle") self.inputCrossOpacity = ScalarInput(filter: self.filter, key: "inputCrossOpacity") self.inputCrossWidth = ScalarInput(filter: self.filter, key: "inputCrossWidth") self.inputEpsilon = ScalarInput(filter: self.filter, key: "inputEpsilon") } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor, self.inputRadius, self.inputCrossScale, self.inputCrossAngle, self.inputCrossOpacity, self.inputCrossWidth, self.inputEpsilon ] } } public struct StripesGenerator: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputColor0Available, InputColor1Available, InputWidthAvailable, InputSharpnessAvailable { public let filter: CIFilter = CIFilter(name: "CIStripesGenerator")! public let inputCenter: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public let inputWidth: ScalarInput public let inputSharpness: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey) self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey) } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor0, self.inputColor1, self.inputWidth, self.inputSharpness ] } } @available(iOS 9.0, *) public struct SunbeamsGenerator: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputColorAvailable, InputSunRadiusAvailable, InputMaxStriationRadiusAvailable, InputStriationStrengthAvailable, InputStriationContrastAvailable, InputTimeAvailable { public let filter: CIFilter = CIFilter(name: "CISunbeamsGenerator")! public let inputCenter: VectorInput public let inputColor: ColorInput public let inputSunRadius: ScalarInput public let inputMaxStriationRadius: ScalarInput public let inputStriationStrength: ScalarInput public let inputStriationContrast: ScalarInput public let inputTime: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey) self.inputSunRadius = ScalarInput(filter: self.filter, key: "inputSunRadius") self.inputMaxStriationRadius = ScalarInput(filter: self.filter, key: "inputMaxStriationRadius") self.inputStriationStrength = ScalarInput(filter: self.filter, key: "inputStriationStrength") self.inputStriationContrast = ScalarInput(filter: self.filter, key: "inputStriationContrast") self.inputTime = ScalarInput(filter: self.filter, key: "inputTime") } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor, self.inputSunRadius, self.inputMaxStriationRadius, self.inputStriationStrength, self.inputStriationContrast, self.inputTime ] } }
mit
d2344270191033d258dffa8c5322e7fc
40.191304
137
0.717402
5.171397
false
false
false
false
Rahulclaritaz/rahul
ixprez/ixprez/RegistrationViewController.swift
1
23684
// // RegistrationViewController.swift // ixprez // // Created by Claritaz Techlabs on 27/04/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit import CoreTelephony import FirebaseAuth import UserNotifications import CloudKit class RegistrationViewController: UIViewController,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource{ @IBOutlet weak var btnTerm: UIButton! @IBOutlet weak var btnPrivacy: UIButton! @IBOutlet weak var viewScrollView: UIView! // @IBOutlet weak var countryPickerView: UIPickerView! // @IBOutlet weak var languagePickerView: UIPickerView! @IBOutlet weak var nameTextField : UITextField? @IBOutlet weak var emailTextField : UITextField? @IBOutlet weak var mobileNumberTextField : UITextField? @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var countryTextField : UITextField! @IBOutlet weak var languageTextField : UITextField! @IBOutlet weak var countryTableView : UITableView! @IBOutlet weak var languageTableView : UITableView! var countryData = [[String : Any]]() var languageData = [[String : Any]]() var filterCountryData = [[String : Any]]() var filterLanguageData = [[String:Any]]() var autoCompleteCountryPossibilities : [NSArray] = [] var autoCompleteLanguagePossibilities : [NSArray] = [] var autoCountryComplete : [NSArray] = [] var autoLanguageComplete : [NSArray] = [] var isCountryTextField : Bool = false var tap = UITapGestureRecognizer() var defaults = UserDefaults.standard var countrySelectedValue = UILabel() var languageSelectedValue = UILabel() var countrySelectedPhoneCode = UILabel() var jsonArrayData = [String]() var pickerData: [String] = [String]() var dictValue = NSDictionary() var countryArrayData = [NSArray]() var languageArrayData = [NSArray]() var countryPhoneCode = [NSArray]() var listData = [String: AnyObject]() let appdelegate = UIApplication.shared.delegate as! AppDelegate let getOTPClass = XPWebService() let getOTPUrl = URLDirectory.RegistrationData() let getCountryUrl = URLDirectory.Country() let getLanguageUrl = URLDirectory.Language() var myCountry : String! var translated = String() var country : String! var countryCode : String! override func awakeFromNib() { let languages = NSLocale.preferredLanguages for lang in languages { let locale = NSLocale(localeIdentifier: lang) translated = locale.displayName(forKey: NSLocale.Key.identifier, value: lang)! print("\(lang), \(translated)") } // This will set the device country code let countryLocale : NSLocale = NSLocale.current as NSLocale let countryCode = countryLocale.object(forKey: NSLocale.Key.countryCode)// as! String country = countryLocale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode!) myCountry = String(describing: country!) print("myCountry", myCountry) print("Country Locale:\(countryLocale) Code:\(String(describing: countryCode)) Name:\(String(describing: country))") } override func viewDidLoad() { super.viewDidLoad() // This will set the device language languageTextField.text = translated // This will set the country Mobile prefix code countryTextField.text = country! countryTableView.layer.cornerRadius = 10 languageTableView.layer.cornerRadius = 10 self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg_reg.png")!) self.viewScrollView.backgroundColor = UIColor(patternImage: UIImage(named:"bg_reg.png")!) getCountryDataFromTheWebService() getLanguageNameFromWebService() UserDefaults.standard.set(true, forKey: "isAppFirstTime") // This gesture will use to hide the keyboard (tap anywhere inside the screen) // tap = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard(rec:))) //view.addGestureRecognizer(tap) nameTextField?.delegate = self saveButton.layer.cornerRadius = 20.0 countryTextField.delegate = self languageTextField.delegate = self mobileNumberTextField?.delegate = self emailTextField?.delegate = self self.btnTerm.addTarget(self, action: #selector(termsAndCondition(sender:)), for: .touchUpInside) self.btnPrivacy.addTarget(self, action: #selector(privacyPolicy(sender:)), for: .touchUpInside) } override func viewWillAppear(_ animated: Bool) { countryTableView.isHidden = true languageTableView.isHidden = true } // This will open the browser for term and Conditions. @IBAction func termsAndCondition (sender : UIButton) { UIApplication.shared.openURL(NSURL(string: "http://www.quadrupleindia.com/ixprez/page/terms_conditions.html")! as URL) } // This will open the browser for Privacy. @IBAction func privacyPolicy (sender : UIButton) { UIApplication.shared.openURL(NSURL(string: "http://www.quadrupleindia.com/ixprez/page/privacy_policy.html")! as URL) } // TextField Delegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // tap.cancelsTouchesInView = false var subString = String() if (textField.tag == 1) { subString = (countryTextField.text! as NSString).replacingCharacters(in: range, with: string) searchAutocompleteCountryEntriesWithSubstring(substring: subString) if (subString.isEmpty) { countryTableView.isHidden = true }else { countryTableView.isHidden = false languageTableView.isHidden = true isCountryTextField = true } } else if (textField.tag == 2) { subString = (languageTextField.text! as NSString).replacingCharacters(in: range, with: string) searchAutocompleteLanguageEntriesWithSubstring(substring: subString) if (subString.isEmpty) { languageTableView.isHidden = true }else { languageTableView.isHidden = false countryTableView.isHidden = true isCountryTextField = false } } return true } func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { countryTableView.isHidden = true languageTableView.isHidden = true } // This method will serach the autocompleted country name func searchAutocompleteCountryEntriesWithSubstring (substring : String) { filterCountryData.removeAll() filterCountryData = countryData.filter({ let string = $0["country_name"] as! String return string.lowercased().range(of : substring.lowercased()) != nil }) DispatchQueue.main.async { self.countryTableView.reloadData() } } // This method will serach the autocompleted language name func searchAutocompleteLanguageEntriesWithSubstring(substring: String) { // autoLanguageComplete.removeAll(keepingCapacity: false) filterLanguageData.removeAll() filterLanguageData = languageData.filter({ let string = $0["name"] as! String return string.lowercased().range(of: substring.lowercased()) != nil }) DispatchQueue.main.async { self.languageTableView.reloadData() } } // tableview Delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == countryTableView { return filterCountryData.count } else { return filterLanguageData.count } } // tableview Delegate func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell if (tableView == countryTableView) { // countryTableView.isHidden = false let cellIdentifier = "XPCountryTableViewCell" let countDic = self.filterCountryData[indexPath.row] cell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? XPCountryTableViewCell)! cell.textLabel?.font = UIFont(name: "Mosk", size: 20) cell.textLabel?.text = countDic["country_name"] as? String } else { //languageTableView.isHidden = false let cellIdentifier = "XPLanguageTableViewCell" cell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? XPLanguageTableViewCell)! let lanDic = self.filterLanguageData[indexPath.row] cell.textLabel?.font = UIFont(name: "Mosk", size: 20) cell.textLabel?.text = lanDic["name"] as? String } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (tableView == countryTableView) { let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)! countryTextField.text = selectedCell.textLabel!.text! let autoCountryCompleteDic = filterCountryData[indexPath.row] print("mathan check data",autoCountryCompleteDic) for i in 0...filterCountryData.count { if indexPath.row == i { print( autoCountryCompleteDic["ph_code"] as! String) self.mobileNumberTextField?.text = String(format: "+%@", (autoCountryCompleteDic["ph_code"] as? String)!) } } countryTableView.isHidden = true } if tableView == languageTableView { let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)! languageTextField.text = selectedCell.textLabel!.text! } languageTableView.isHidden = true } // This method will dismiss the keyboard func dismissKeyboard(rec: UIGestureRecognizer) { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) countryTableView.isHidden = true languageTableView.isHidden = true } // This method Will call the Web Service to get the country name and passing parameter func getCountryDataFromTheWebService() { /* self.countryPhoneCode = (countryData.value(forKey: "ph_code") as! NSArray) as! [String] self.countryArrayData = (countryData.value(forKey: "country_name") as! NSArray) as! [String] // let delayInSeconds = 1.0 self.autoCompleteCountryPossibilities = self.countryArrayData */ let paramsCountry = ["list":"country"] as Dictionary<String, String> getOTPClass.getCountryDataWebService(urlString: getCountryUrl.url(), dicData: paramsCountry as NSDictionary, callback: { ( countryData,needData, error ) in print("data") print(countryData) // self.countryPhoneCode = (countryData.value(forKey: "ph_code") as! NSArray) as! [String] self.countryArrayData = (needData.value(forKey: "country_name") as! NSArray) as! [NSArray] self.autoCompleteCountryPossibilities = self.countryArrayData self.countryData = countryData DispatchQueue.global(qos: .background).async { let myData :[[String:Any]] = self.countryData.filter({ let string = $0["country_name"] as? String let subString = self.myCountry! print ( "my data",string!) return string?.lowercased().range(of: subString.lowercased()) != nil }) for arrData in myData { self.mobileNumberTextField?.text = String(format: "+%@", arrData["ph_code"] as! String) self.countryCode = "+" + (arrData["ph_code"] as! String) print("The country code for this country is \(self.countryCode)") self.defaults.set(self.countryCode, forKey: "countryCode") } DispatchQueue.main.async { self.countryTableView.reloadData() } } }) } // This method Will call the Web Service to get the language and passing parameter func getLanguageNameFromWebService() -> Void { let paramsLanguage = ["list" : "language"] as Dictionary<String,String> getOTPClass.getLanguageDataWebService(urlString: getLanguageUrl.url(), dicData: paramsLanguage as NSDictionary, callBack:{(languageData ,needData, error) in self.languageArrayData = (needData.value(forKey: "name") as! NSArray) as! [NSArray] self.autoCompleteLanguagePossibilities = self.languageArrayData self.languageData = languageData DispatchQueue.main.async { self.languageTableView.reloadData() } }) } // This textfield method will hide the keyboard when click on done button. func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // This method will store the data into the NSUSerDefaults. @IBAction func saveButtonAction(_ sender: Any) { if (nameTextField?.text == "") { let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Name.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else if (emailTextField?.text == "") { let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Email.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else if (!(emailTextField?.text?.isValidEmail())!) { let alertController = UIAlertController(title: "Alert", message: "This is not a Valid Email.", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } else if (countryTextField.text == "") { let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please select your Country from the list only.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else if (languageTextField.text == "") { let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please select your language from the list only.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else if (mobileNumberTextField?.text == "") { let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Mobile Number.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else if (!(mobileNumberTextField?.text?.isValidPhono())!) { let alertController = UIAlertController(title: "Alert", message: "This is not a Valid Phone Number. Use only Numeric with your Country Code", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } else { print("Good YOU given all the details in Registration Field.") if (!(countryTextField.text == "")) { var countryTextFieldString : String = countryTextField.text! var CountryTextFieldValidate = String () for coun in self.countryData { let countryName : String = coun["country_name"] as! String print(countryName) if (countryName == countryTextFieldString) { CountryTextFieldValidate = countryTextFieldString break } } if (countryTextFieldString == CountryTextFieldValidate) { print("The country name is available in the web") languageFieldValidation() } else { let alertView = UIAlertController(title: "Alert", message: "This country is not available, please select from the country list.", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertView.addAction(alertAction) present(alertView, animated: true, completion: nil) } } } }// end save function // This function will validate that language is available in the Server or not func languageFieldValidation() { if (!(languageTextField.text == "")) { let languageTextFieldString : String = languageTextField.text! var languageTextFieldValidate = String () for lang in self.languageData { let languageName: String = lang["name"] as! String if (languageName == languageTextFieldString) { languageTextFieldValidate = languageTextFieldString break } } if (languageTextFieldString == languageTextFieldValidate) { print("This Language is available in List") smsFieldVarification() } else { let alertView = UIAlertController(title: "Alert", message: "This language is not available, please select from the language list.", preferredStyle: .alert) let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertView.addAction(alertAction) present(alertView, animated: true, completion: nil) } } } // This method will send the OTP from FCM server. func smsFieldVarification () { defaults.set(nameTextField?.text, forKey: "userName") defaults.set(emailTextField?.text, forKey: "emailAddress") defaults.set(countryTextField.text, forKey: "countryName") defaults.set(languageTextField.text, forKey: "languageName") defaults.set(mobileNumberTextField?.text, forKey: "mobileNumber") PhoneAuthProvider.provider().verifyPhoneNumber((self.mobileNumberTextField?.text)!, completion: { (verificationID, error) in print("First time verification Id is \(verificationID)") if error != nil { print("error \(error?.localizedDescription)") self.alertViewControllerWithCancel(headerTile: "Error", bodyMessage: (error?.localizedDescription)! + " Add country code with + symbole if not added. ") } else { let defaults = UserDefaults.standard.set(verificationID, forKey: "OTPVerificationID") // print("OTP is \(verificationID)") let verifyOTPView = self.storyboard?.instantiateViewController(withIdentifier: "OTPVerificationViewController") as! OTPVerificationViewController self.present(verifyOTPView, animated: true, completion: nil) } }) } } // end class
mit
764475afc9ba661d19af86889262db3b
35.473101
190
0.563907
5.882514
false
false
false
false
nameghino/swift-algorithm-club
Singly Linked List/SinglyLinkedList.swift
1
1734
/* Singly Linked List Provides O(n) for storage and lookup. */ class Node<T> { var key: T? var next: Node? init() {} init(key: T?) { self.key = key } init(key: T?, next: Node?) { self.key = key self.next = next } } class SinglyLinkedList<T: Equatable> { var head = Node<T>() func addLink(key: T) { guard head.key != nil else { return head.key = key } var current: Node? = head FindEmptySpot: while current != nil { if current?.next == nil { current?.next = Node<T>(key: key) break FindEmptySpot } else { current = current?.next } } } func removeLinkAtIndex(index: Int) { guard index >= 0 && index <= self.count - 1 && head.key != nil else { return } var current: Node<T>? = head var trailer: Node<T>? var listIndex = 0 if index == 0 { current = current?.next head = current?.next ?? Node<T>() return } while current != nil { if listIndex == index { trailer?.next = current?.next current = nil break } trailer = current current = current?.next listIndex += 1 } } var count: Int { guard head.key != nil else { return 0 } var current = head var x = 1 while let next = current.next { current = next x += 1 } return x } var isEmpty: Bool { return head.key == nil } }
mit
2bb5ee950ce3c88ae0a9fd2f2ef98e29
20.949367
88
0.440023
4.423469
false
false
false
false
p0dee/PDAlertView
PDAlertView/AlertSelectionControl.swift
1
5506
// // AlertSelectionControl.swift // AlertViewMock // // Created by Takeshi Tanaka on 12/23/15. // Copyright © 2015 Takeshi Tanaka. All rights reserved. // import UIKit internal class AlertSelectionControl: UIControl { private let stackView = UIStackView() internal var components = [AlertSelectionComponentView]() internal var axis: UILayoutConstraintAxis { return stackView.axis } var selectedIndex: Int? { didSet { if (selectedIndex != oldValue) { sendActions(for: .valueChanged) } } } override var isHighlighted: Bool { didSet { selectedIndex = nil } } override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() stackView.distribution = .fillEqually stackView.spacing = CGFloat(actionButtonLineWidth()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { stackView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(stackView) } private func setupConstraints() { let cstrs = NSLayoutConstraint.constraintsToFillSuperview(stackView) NSLayoutConstraint.activate(cstrs) } func addButton(with title: String, style: AlertActionStyle) { let component = AlertSelectionComponentView(title: title, style: style) component.isUserInteractionEnabled = false stackView.addArrangedSubview(component) components.append(component) if stackView.axis == .vertical { //Do nothing. } else if components.count > 2 || component.preferredLayoutAxis == .vertical { stackView.axis = .vertical } } private func selectedIndex(with point: CGPoint) -> Int? { for view in stackView.arrangedSubviews { if let view = view as? AlertSelectionComponentView, view.frame.contains(point) { return components.index(of: view) } } return nil } //MARK: override internal override func tintColorDidChange() { for comp in components { switch comp.style { case .default: comp.tintColor = tintColor default: break } } } internal override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let point = touch.location(in: self) selectedIndex = selectedIndex(with: point) } } internal override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let point = touch.location(in: self) selectedIndex = selectedIndex(with: point) } } internal override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let point = touch.location(in: self) if self.bounds.contains(point) { sendActions(for: .touchUpInside) } } selectedIndex = nil } } internal class AlertSelectionComponentView: UIView { private var label = UILabel() fileprivate var style: AlertActionStyle = .default fileprivate var preferredLayoutAxis: UILayoutConstraintAxis { guard let text = label.text else { return .vertical } let attrs = [NSFontAttributeName : label.font] let size = NSString(string: text).size(attributes: attrs) return size.width > 115 ? .vertical : .horizontal } override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(title: String, style: AlertActionStyle) { self.init() self.style = style if style == .destructive { self.tintColor = UIColor(red: 255/255.0, green: 0, blue: 33/255.0, alpha: 1.0) } label.text = title switch style { case .cancel: label.font = UIFont.boldSystemFont(ofSize: 17.0) default: label.font = UIFont.systemFont(ofSize: 17.0) } } private func setupViews() { self.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 10) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = tintColor label.textAlignment = .center label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.6 label.lineBreakMode = .byTruncatingMiddle label.baselineAdjustment = .alignCenters label.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal) self.addSubview(label) } private func setupConstraints() { let cstrs = NSLayoutConstraint.constraintsToFillSuperviewMarginsGuide(label) NSLayoutConstraint.activate(cstrs) } //MARK: override internal override var intrinsicContentSize: CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: 44) } internal override func tintColorDidChange() { label.textColor = tintColor } }
gpl-2.0
48d56ba92941e420e1b052824b1177d1
29.414365
99
0.610173
5.203214
false
false
false
false
roambotics/swift
test/SILOptimizer/return.swift
2
7244
// RUN: %target-swift-frontend %s -emit-sil -verify func singleBlock() -> Int { _ = 0 } // expected-error {{missing return in global function expected to return 'Int'}} func singleBlock2() -> Int { var y = 0 y += 1 } // expected-error {{missing return in global function expected to return 'Int'}} enum NoCasesButNotNever {} func diagnoseNoCaseEnumMissingReturn() -> NoCasesButNotNever { } // expected-error {{function with uninhabited return type 'NoCasesButNotNever' is missing call to another never-returning function on all paths}} func diagnoseNeverMissingBody() -> Never { } // expected-error {{function with uninhabited return type 'Never' is missing call to another never-returning function on all paths}} _ = { () -> Never in }() // expected-error {{closure with uninhabited return type 'Never' is missing call to another never-returning function on all paths}}- func diagnoseNeverWithBody(i : Int) -> Never { if (i == -1) { print("Oh no!") } else { switch i { case 0: exit() case 1: fatalError() default: repeat { } while true } } } // expected-error {{function with uninhabited return type 'Never' is missing call to another never-returning function on all paths}} class MyClassWithClosure { var f : (_ s: String) -> String = { (_ s: String) -> String in } // expected-error {{missing return in closure expected to return 'String'}} } func multipleBlocksSingleMissing(b: Bool) -> (String, Int) { var y = 0 if b { return ("a", 1) } else if (y == 0) { y += 1 } } // expected-error {{missing return in global function expected to return '(String, Int)'}} func multipleBlocksAllMissing(x: Int) -> Int { var y : Int = x + 1 while (y > 0 ) { y -= 1 break } var x = 0 x += 1 } // expected-error {{missing return in global function expected to return 'Int'}} @_silgen_name("exit") func exit () -> Never func diagnose_missing_return_in_the_else_branch(i: Bool) -> Int { if (i) { exit() } } // expected-error {{missing return in global function expected to return 'Int'}} func diagnose_missing_return_no_error_after_noreturn(i: Bool) -> Int { if (i) { exit() } else { exit() } } // no error class TuringMachine { func halt() -> Never { repeat { } while true } } func diagnose_missing_return_no_error_after_noreturn_method() -> Int { TuringMachine().halt() } // no error func whileLoop(flag: Bool) -> Int { var b = 1 while (flag) { if b == 3 { return 3 } b += 1 } } //expected-error {{missing return in global function expected to return 'Int'}} struct S {} extension S:ExpressibleByStringLiteral { init!(stringLiteral:String) { } // no error } func whileTrueLoop() -> Int { var b = 1 while (true) { if b == 3 { return 3 } b += 1 } // no-error } func testUnreachableAfterNoReturn(x: Int) -> Int { exit(); // expected-note{{a call to a never-returning function}} return x; // expected-warning {{will never be executed}} } func testUnreachableAfterNoReturnInADifferentBlock() -> Int { let x:Int = 5 if true { // expected-note {{condition always evaluates to true}} exit(); } return x; // expected-warning {{will never be executed}} } func testReachableAfterNoReturnInADifferentBlock(x: Int) -> Int { if x == 5 { exit(); } return x; // no warning } func testUnreachableAfterNoReturnFollowedByACall() -> Int { let x:Int = 5 exit(); // expected-note{{a call to a never-returning function}} exit(); // expected-warning {{will never be executed}} return x } func testUnreachableAfterNoReturnMethod() -> Int { TuringMachine().halt(); // expected-note{{a call to a never-returning function}} return 0; // expected-warning {{will never be executed}} } func testCleanupCodeEmptyTuple(fn: @autoclosure () -> Bool = false, message: String = "", file: String = #file, line: Int = #line) { if true { exit() } } // no warning protocol InitProtocol { init(_ x: Int) } struct StructWithIUOinit : InitProtocol { init!(_ x: Int) { } // no missing-return error } // https://github.com/apple/swift/issues/56150 func f_56150() { let _ : () -> Int = { var x : Int { get { 0 } set { } } x // expected-error {{missing return in closure expected to return 'Int'}} // expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }} // expected-warning@-2 {{setter argument 'newValue' was never used, but the property was accessed}} // expected-note@-3 {{did you mean to use 'newValue' instead of accessing the property's current value?}} // expected-warning@-4 {{variable is unused}} } func f() -> Int { var x : Int { get { 0 } set { } } x // expected-error {{missing return in local function expected to return 'Int'}} // expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }} // expected-warning@-2 {{setter argument 'newValue' was never used, but the property was accessed}} // expected-note@-3 {{did you mean to use 'newValue' instead of accessing the property's current value?}} // expected-warning@-4 {{variable is unused}} } let _ : () -> Int = { var x : UInt { get { 0 } set { } } x // expected-warning@-1 {{setter argument 'newValue' was never used, but the property was accessed}} // expected-note@-2 {{did you mean to use 'newValue' instead of accessing the property's current value?}} // expected-warning@-3 {{variable is unused}} } // expected-error {{missing return in closure expected to return 'Int'}} func f1() -> Int { var x : UInt { get { 0 } set { } } x // expected-warning@-1 {{setter argument 'newValue' was never used, but the property was accessed}} // expected-note@-2 {{did you mean to use 'newValue' instead of accessing the property's current value?}} // expected-warning@-3 {{variable is unused}} } // expected-error {{missing return in local function expected to return 'Int'}} let _ : () -> Int = { var x : Int = 0 // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}} var _ : Int = 0 x // expected-error{{missing return in closure expected to return 'Int'}} // expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }} //expected-warning@-2{{variable is unused}} } } // https://github.com/apple/swift/issues/56857 struct S_56857 { let b = true var x: Int { if b { return 0 } } // expected-error {{missing return in getter expected to return 'Int'}} var y: Int { get { if b { return 0 } } // expected-error {{missing return in getter expected to return 'Int'}} set {} } } class C_56857 { static let a = false let b = true func method() -> Int { if b { return 0 } } // expected-error {{missing return in instance method expected to return 'Int'}} class func method1() -> Int { if a { return 0 } } // expected-error {{missing return in class method expected to return 'Int'}} }
apache-2.0
7d961a892815cdd6091dba0e0b61069c
27.407843
148
0.622722
3.786722
false
false
false
false
xedin/swift
test/stmt/statements.swift
1
20255
// RUN: %target-typecheck-verify-swift /* block comments */ /* /* nested too */ */ func markUsed<T>(_ t: T) {} func f1(_ a: Int, _ y: Int) {} func f2() {} func f3() -> Int {} func invalid_semi() { ; // expected-error {{';' statements are not allowed}} {{3-5=}} } func nested1(_ x: Int) { var y : Int func nested2(_ z: Int) -> Int { return x+y+z } _ = nested2(1) } func funcdecl5(_ a: Int, y: Int) { var x : Int // a few statements if (x != 0) { if (x != 0 || f3() != 0) { // while with and without a space after it. while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} } } // Assignment statement. x = y (x) = y 1 = x // expected-error {{cannot assign to a literal value}} (1) = x // expected-error {{cannot assign to a literal value}} "string" = "other" // expected-error {{cannot assign to a literal value}} [1, 1, 1, 1] = [1, 1] // expected-error {{cannot assign to immutable expression of type '[Int]}} 1.0 = x // expected-error {{cannot assign to a literal value}} nil = 1 // expected-error {{cannot assign to a literal value}} (x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}} var tup : (x:Int, y:Int) tup.x = 1 _ = tup let B : Bool // if/then/else. if (B) { } else if (y == 2) { } // This diagnostic is terrible - rdar://12939553 if x {} // expected-error {{'Int' is not convertible to 'Bool'}} if true { if (B) { } else { } } if (B) { f1(1,2) } else { f2() } if (B) { if (B) { f1(1,2) } else { f2() } } else { f2() } // while statement. while (B) { } // It's okay to leave out the spaces in these. while(B) {} if(B) {} } struct infloopbool { var boolValue: infloopbool { return self } } func infloopbooltest() { if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}} } // test "builder" API style extension Int { static func builder() -> Int { } var builderProp: Int { return 0 } func builder2() {} } Int .builder() .builderProp .builder2() struct SomeGeneric<T> { static func builder() -> SomeGeneric<T> { } var builderProp: SomeGeneric<T> { return .builder() } func builder2() {} } SomeGeneric<Int> .builder() .builderProp .builder2() break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} continue // expected-error {{'continue' is only allowed inside a loop}} while true { func f() { break // expected-error {{'break' is only allowed inside a loop}} continue // expected-error {{'continue' is only allowed inside a loop}} } // Labeled if MyIf: if 1 != 2 { break MyIf continue MyIf // expected-error {{'continue' cannot be used with if statements}} break // break the while continue // continue the while. } } // Labeled if MyOtherIf: if 1 != 2 { break MyOtherIf continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}} break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}} continue // expected-error {{'continue' is only allowed inside a loop}} } do { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } func tuple_assign() { var a,b,c,d : Int (a,b) = (1,2) func f() -> (Int,Int) { return (1,2) } ((a,b), (c,d)) = (f(), f()) } func missing_semicolons() { var w = 321 func g() {} g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}} var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}} class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}} struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}} func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}} } //===--- Return statement. return 42 // expected-error {{return invalid outside of a func}} return // expected-error {{return invalid outside of a func}} func NonVoidReturn1() -> Int { _ = 0 return // expected-error {{non-void function should return a value}} } func NonVoidReturn2() -> Int { return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}} } func VoidReturn1() { if true { return } // Semicolon should be accepted -- rdar://11344875 return; // no-error } func VoidReturn2() { return () // no-error } func VoidReturn3() { return VoidReturn2() // no-error } //===--- If statement. func IfStmt1() { if 1 > 0 // expected-error {{expected '{' after 'if' condition}} _ = 42 } func IfStmt2() { if 1 > 0 { } else // expected-error {{expected '{' or 'if' after 'else'}} _ = 42 } func IfStmt3() { if 1 > 0 { } else 1 < 0 { // expected-error {{expected '{' or 'if' after 'else'; did you mean to write 'if'?}} {{9-9= if}} _ = 42 } else { } } //===--- While statement. func WhileStmt1() { while 1 > 0 // expected-error {{expected '{' after 'while' condition}} _ = 42 } //===-- Do statement. func DoStmt() { // This is just a 'do' statement now. do { } } func DoWhileStmt() { do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}} } while true } //===--- Repeat-while statement. func RepeatWhileStmt1() { repeat {} while true repeat {} while false repeat { break } while true repeat { continue } while true } func RepeatWhileStmt2() { repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}} } func RepeatWhileStmt4() { repeat { } while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}} } func brokenSwitch(_ x: Int) -> Int { switch x { case .Blah(var rep): // expected-error{{pattern cannot match values of type 'Int'}} return rep } } func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int { switch (x,y,z) { case (let a, 0, _), (0, let a, _): // OK return a case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} return a } } func breakContinue(_ x : Int) -> Int { Outer: for _ in 0...1000 { Switch: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} switch x { case 42: break Outer case 97: continue Outer case 102: break Switch case 13: continue case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements } } // <rdar://problem/16692437> shadowing loop labels should be an error Loop: // expected-note {{previously declared here}} for _ in 0...2 { Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}} for _ in 0...2 { } } // <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it switch 5 { case 5: markUsed("before the break") break markUsed("after the break") // 'markUsed' is not a label for the break. default: markUsed("") } let x : Int? = 42 // <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals switch x { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.some(_)'}} case .some(42): break case nil: break } } enum MyEnumWithCaseLabels { case Case(one: String, two: Int) } func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) { // <rdar://problem/20135489> Enum case labels are ignored in "case let" statements switch a { case let .Case(one: _, two: x): break // ok case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}} // TODO: In principle, reordering like this could be supported. case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}} } } // "defer" func test_defer(_ a : Int) { defer { VoidReturn1() } defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}} // Ok: defer { while false { break } } // Not ok. while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}} // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{17-22=do}} defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}} // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{3-8=do}} } class SomeTestClass { var x = 42 func method() { defer { x = 97 } // self. not required here! // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{5-10=do}} } } enum DeferThrowError: Error { case someError } func throwInDefer() { defer { throw DeferThrowError.someError } // expected-error {{'throw' cannot transfer control out of a defer statement}} print("Foo") } func throwingFuncInDefer1() throws { defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer2() throws { defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer3() { defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer4() { defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFunctionCalledInDefer() throws { throw DeferThrowError.someError } class SomeDerivedClass: SomeTestClass { override init() { defer { super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } } } func test_guard(_ x : Int, y : Int??, cond : Bool) { // These are all ok. guard let a = y else {} markUsed(a) guard let b = y, cond else {} guard case let c = x, cond else {} guard case let Optional.some(d) = y else {} guard x != 4, case _ = x else { } guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard let g = y else { markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }} guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}} // SR-7567 guard let outer = y else { guard true else { print(outer) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } } } func test_is_as_patterns() { switch 4 { case is Int: break // expected-warning {{'is' test is always true}} case _ as Int: break // expected-warning {{'as' test is always true}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } } // <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...) func matching_pattern_recursion() { switch 42 { case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}} for i in zs { } }: break } } // <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors func r18776073(_ a : Int?) { switch a { case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}} case _?: break } } // <rdar://problem/22491782> unhelpful error message from "throw nil" func testThrowNil() throws { throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}} } // rdar://problem/23684220 // Even if the condition fails to typecheck, save it in the AST anyway; the old // condition may have contained a SequenceExpr. func r23684220(_ b: Any) { if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}} // expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type 'Any', so the right side is never used}} } // <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics func f21080671() { try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} } catch { } try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} f21080671() } catch let x as Int { } catch { } } // <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma // https://twitter.com/radexp/status/694561060230184960 func f(_ x : Int, y : Int) { if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}} // https://twitter.com/radexp/status/694790631881883648 if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}} } // <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause enum Type { case Foo case Bar } func r25178926(_ a : Type) { switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo, .Bar where 1 != 100: // expected-warning @-1 {{'where' only applies to the second pattern match in this case}} // expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }} // expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}} break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo: break case .Bar where 1 != 100: break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo, // no warn .Bar where 1 != 100: break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Foo'}} // expected-note@-2 {{missing case: '.Bar'}} case .Foo where 1 != 100, .Bar where 1 != 100: break } } do { guard 1 == 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } } func fn(a: Int) { guard a < 1 else { break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} } } func fn(x: Int) { if x >= 0 { guard x < 1 else { guard x < 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } return } } } func bad_if() { if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}} if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}} if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}} } // Typo correction for loop labels for _ in [1] { break outerloop // expected-error {{use of unresolved label 'outerloop'}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } while true { break outerloop // expected-error {{use of unresolved label 'outerloop'}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } repeat { break outerloop // expected-error {{use of unresolved label 'outerloop'}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } while true outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } outerLoop: while true { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } outerLoop: while true { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } outerLoop: repeat { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } while true outerLoop: repeat { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } while true outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{use of unresolved label 'outerloop'}} } } outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } } outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{use of unresolved label 'outerloop'}} } } outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } } outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{use of unresolved label 'outerloop'}} } while true } while true outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{use of unresolved label 'outerloop'}} } while true } while true // Errors in case syntax class case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}} case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}} // NOTE: EOF is important here to properly test a code path that used to crash the parser
apache-2.0
24549d833dc9bf4b792c08733e1fefb1
30.648438
253
0.642113
3.658779
false
false
false
false
soapyigu/LeetCode_Swift
Stack/PreorderTraversal.swift
1
968
/** * Question Link: https://leetcode.com/problems/binary-tree-preorder-traversal/ * Primary idea: Use a stack to help iterate the tree * Time Complexity: O(n), Space Complexity: O(n) * * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class PreorderTraversal { func preorderTraversal(root: TreeNode?) -> [Int] { var res = [Int]() var stack = [TreeNode]() var node = root while !stack.isEmpty || node != nil { if node != nil { res.append(node!.val) stack.append(node!) node = node!.left } else { node = stack.removeLast().right } } return res } }
mit
a7eb48f004835b16407a84da33f8ab42
25.189189
79
0.51343
4.016598
false
false
false
false
OpenStack-mobile/aerogear-ios-oauth2
AeroGearOAuth2Tests/TimeZone.swift
1
731
// // TimeZone.swift // OpenStackSummit // // Created by Alsey Coleman Miller on 6/1/16. // Copyright © 2016 OpenStack. All rights reserved. // public struct TimeZone: Equatable { public var name: String public var countryCode: String public var latitude: Double public var longitude: Double public var comments: String public var offset: Int } // MARK: - Equatable public func == (lhs: TimeZone, rhs: TimeZone) -> Bool { return lhs.name == rhs.name && lhs.countryCode == rhs.countryCode && lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude && lhs.comments == rhs.comments && lhs.offset == rhs.offset }
apache-2.0
0c81a09c71b8f8bc19d0ee7ae1d9d6e8
20.470588
55
0.609589
4.219653
false
false
false
false
johnno1962d/swift
benchmark/single-source/StringInterpolation.swift
3
1426
//===--- StringInterpolation.swift ----------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import TestsUtils class RefTypePrintable : CustomStringConvertible { var description: String { return "01234567890123456789012345678901234567890123456789" } } @inline(never) public func run_StringInterpolation(_ N: Int) { let reps = 100 let refResult = reps let anInt: Int64 = 0x1234567812345678 let aRefCountedObject = RefTypePrintable() for _ in 1...100*N { var result = 0 for _ in 1...reps { let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}" // FIXME: if String is not stored as UTF-16 on this platform, then the // following operation has a non-trivial cost and needs to be replaced // with an operation on the native storage type. result = result &+ Int(s.utf16[s.utf16.endIndex.predecessor()]) } CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)") } }
apache-2.0
95cff30ba948109de09523e7485ca3bc
33.780488
107
0.645863
4.470219
false
false
false
false
dduan/swift
stdlib/public/core/Reflection.swift
1
16910
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Customizes the result of `_reflect(x)`, where `x` is a conforming /// type. public protocol _Reflectable { // The runtime has inappropriate knowledge of this protocol and how its // witness tables are laid out. Changing this protocol requires a // corresponding change to Reflection.cpp. /// Returns a mirror that reflects `self`. @warn_unused_result func _getMirror() -> _Mirror } /// A unique identifier for a class instance or metatype. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. public struct ObjectIdentifier : Hashable, Comparable { internal let _value: Builtin.RawPointer // FIXME: Better hashing algorithm /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_value)) } /// Construct an instance that uniquely identifies the class instance `x`. public init(_ x: AnyObject) { self._value = Builtin.bridgeToRawPointer(x) } /// Construct an instance that uniquely identifies the metatype `x`. public init(_ x: Any.Type) { self._value = unsafeBitCast(x, to: Builtin.RawPointer.self) } } @warn_unused_result public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return UInt(lhs) < UInt(rhs) } @warn_unused_result public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value)) } extension UInt { /// Create a `UInt` that captures the full value of `objectID`. public init(_ objectID: ObjectIdentifier) { self.init(Builtin.ptrtoint_Word(objectID._value)) } } extension Int { /// Create an `Int` that captures the full value of `objectID`. public init(_ objectID: ObjectIdentifier) { self.init(bitPattern: UInt(objectID)) } } /// How children of this value should be presented in the IDE. public enum _MirrorDisposition { /// As a struct. case `struct` /// As a class. case `class` /// As an enum. case `enum` /// As a tuple. case tuple /// As a miscellaneous aggregate with a fixed set of children. case aggregate /// As a container that is accessed by index. case indexContainer /// As a container that is accessed by key. case keyContainer /// As a container that represents membership of its values. case membershipContainer /// As a miscellaneous container with a variable number of children. case container /// An Optional which can have either zero or one children. case optional /// An Objective-C object imported in Swift. case objCObject } /// The type returned by `_reflect(x)`; supplies an API for runtime /// reflection on `x`. public protocol _Mirror { /// The instance being reflected. var value: Any { get } /// Identical to `value.dynamicType`. var valueType: Any.Type { get } /// A unique identifier for `value` if it is a class instance; `nil` /// otherwise. var objectIdentifier: ObjectIdentifier? { get } /// The count of `value`'s logical children. var count: Int { get } /// Get a name and mirror for the `i`th logical child. subscript(i: Int) -> (String, _Mirror) { get } /// A string description of `value`. var summary: String { get } /// A rich representation of `value` for an IDE, or `nil` if none is supplied. var quickLookObject: PlaygroundQuickLook? { get } /// How `value` should be presented in an IDE. var disposition: _MirrorDisposition { get } } /// An entry point that can be called from C++ code to get the summary string /// for an arbitrary object. The memory pointed to by "out" is initialized with /// the summary string. @warn_unused_result @_silgen_name("swift_getSummary") public // COMPILER_INTRINSIC func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) { out.initialize(with: String(reflecting: x)) } /// Produce a mirror for any value. If the value's type conforms to /// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back /// to an implementation in the runtime that structurally reflects values /// of any type. @warn_unused_result @_silgen_name("swift_reflectAny") public func _reflect<T>(x: T) -> _Mirror /// Dump an object's contents using its mirror to the specified output stream. public func dump<T, TargetStream : OutputStream>( value: T, to target: inout TargetStream, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max ) -> T { var maxItemCounter = maxItems var visitedItems = [ObjectIdentifier : Int]() target._lock() defer { target._unlock() } _dump_unlocked( value, to: &target, name: name, indent: indent, maxDepth: maxDepth, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) return value } /// Dump an object's contents using its mirror to standard output. public func dump<T>( value: T, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max ) -> T { var stdoutStream = _Stdout() return dump( value, to: &stdoutStream, name: name, indent: indent, maxDepth: maxDepth, maxItems: maxItems) } /// Dump an object's contents. User code should use dump(). internal func _dump_unlocked<TargetStream : OutputStream>( value: Any, to target: inout TargetStream, name: String?, indent: Int, maxDepth: Int, maxItemCounter: inout Int, visitedItems: inout [ObjectIdentifier : Int] ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { target.write(" ") } let mirror = Mirror(reflecting: value) let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" target.write(bullet) target.write(" ") if let nam = name { target.write(nam) target.write(": ") } // This takes the place of the old mirror API's 'summary' property _dumpPrint_unlocked(value, mirror, &target) let id: ObjectIdentifier? if let classInstance = value as? AnyObject where value.dynamicType is AnyObject.Type { // Object is a class (but not an ObjC-bridged struct) id = ObjectIdentifier(classInstance) } else if let metatypeInstance = value as? Any.Type { // Object is a metatype id = ObjectIdentifier(metatypeInstance) } else { id = nil } if let theId = id { if let previous = visitedItems[theId] { target.write(" #") _print_unlocked(previous, &target) target.write("\n") return } let identifier = visitedItems.count visitedItems[theId] = identifier target.write(" #") _print_unlocked(identifier, &target) } target.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror { _dumpSuperclass_unlocked( mirror: superclassMirror, to: &target, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { _print_unlocked(" ", &target) } let remainder = count - i target.write("(") _print_unlocked(remainder, &target) if i > 0 { target.write(" more") } if remainder == 1 { target.write(" child)\n") } else { target.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] currentIndex = currentIndex.successor() _dump_unlocked( child, to: &target, name: name, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } } /// Dump information about an object's superclass, given a mirror reflecting /// that superclass. internal func _dumpSuperclass_unlocked<TargetStream : OutputStream>( mirror mirror: Mirror, to target: inout TargetStream, indent: Int, maxDepth: Int, maxItemCounter: inout Int, visitedItems: inout [ObjectIdentifier : Int] ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { target.write(" ") } let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" target.write(bullet) target.write(" super: ") _debugPrint_unlocked(mirror.subjectType, &target) target.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror { _dumpSuperclass_unlocked( mirror: superclassMirror, to: &target, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { target.write(" ") } let remainder = count - i target.write("(") _print_unlocked(remainder, &target) if i > 0 { target.write(" more") } if remainder == 1 { target.write(" child)\n") } else { target.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] currentIndex = currentIndex.successor() _dump_unlocked( child, to: &target, name: name, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } } // -- Implementation details for the runtime's _Mirror implementation @_silgen_name("swift_MagicMirrorData_summary") func _swift_MagicMirrorData_summaryImpl( metadata: Any.Type, _ result: UnsafeMutablePointer<String> ) public struct _MagicMirrorData { let owner: Builtin.NativeObject let ptr: Builtin.RawPointer let metadata: Any.Type var value: Any { @_silgen_name("swift_MagicMirrorData_value")get } var valueType: Any.Type { @_silgen_name("swift_MagicMirrorData_valueType")get } public var objcValue: Any { @_silgen_name("swift_MagicMirrorData_objcValue")get } public var objcValueType: Any.Type { @_silgen_name("swift_MagicMirrorData_objcValueType")get } var summary: String { let (_, result) = _withUninitializedString { _swift_MagicMirrorData_summaryImpl(self.metadata, $0) } return result } public func _loadValue<T>() -> T { return Builtin.load(ptr) as T } } struct _OpaqueMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { return 0 } subscript(i: Int) -> (String, _Mirror) { _preconditionFailure("no children") } var summary: String { return data.summary } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .aggregate } } internal struct _TupleMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_TupleMirror_count")get } subscript(i: Int) -> (String, _Mirror) { return _subscript_get(i) } @_silgen_name("swift_TupleMirror_subscript") func _subscript_get<T>(i: Int) -> (T, _Mirror) var summary: String { return "(\(count) elements)" } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .tuple } } struct _StructMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_StructMirror_count")get } subscript(i: Int) -> (String, _Mirror) { return _subscript_get(i) } @_silgen_name("swift_StructMirror_subscript") func _subscript_get<T>(i: Int) -> (T, _Mirror) var summary: String { return _typeName(valueType) } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .`struct` } } struct _EnumMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_EnumMirror_count")get } var caseName: UnsafePointer<CChar> { @_silgen_name("swift_EnumMirror_caseName")get } subscript(i: Int) -> (String, _Mirror) { return _subscript_get(i) } @_silgen_name("swift_EnumMirror_subscript") func _subscript_get<T>(i: Int) -> (T, _Mirror) var summary: String { let maybeCaseName = String(validatingUTF8: self.caseName) let typeName = _typeName(valueType) if let caseName = maybeCaseName { return typeName + "." + caseName } return typeName } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .`enum` } } @warn_unused_result @_silgen_name("swift_ClassMirror_count") func _getClassCount(_: _MagicMirrorData) -> Int // Like the other swift_*Mirror_subscript functions declared here and // elsewhere, this is implemented in the runtime. The Swift CC would // normally require the String to be returned directly and the _Mirror // indirectly. However, Clang isn't currently capable of doing that // reliably because the size of String exceeds the normal direct-return // ABI rules on most platforms. Therefore, we make this function generic, // which has the disadvantage of passing the String type metadata as an // extra argument, but does force the string to be returned indirectly. @warn_unused_result @_silgen_name("swift_ClassMirror_subscript") func _getClassChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror) #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_ClassMirror_quickLookObject") public func _getClassPlaygroundQuickLook( data: _MagicMirrorData ) -> PlaygroundQuickLook? #endif struct _ClassMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return data._loadValue() as ObjectIdentifier } var count: Int { return _getClassCount(data) } subscript(i: Int) -> (String, _Mirror) { return _getClassChild(i, data) } var summary: String { return _typeName(valueType) } var quickLookObject: PlaygroundQuickLook? { #if _runtime(_ObjC) return _getClassPlaygroundQuickLook(data) #else return nil #endif } var disposition: _MirrorDisposition { return .`class` } } struct _ClassSuperMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } // Suppress the value identifier for super mirrors. var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { return _getClassCount(data) } subscript(i: Int) -> (String, _Mirror) { return _getClassChild(i, data) } var summary: String { return _typeName(data.metadata) } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .`class` } } struct _MetatypeMirror : _Mirror { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return data._loadValue() as ObjectIdentifier } var count: Int { return 0 } subscript(i: Int) -> (String, _Mirror) { _preconditionFailure("no children") } var summary: String { return _typeName(data._loadValue() as Any.Type) } var quickLookObject: PlaygroundQuickLook? { return nil } // Special disposition for types? var disposition: _MirrorDisposition { return .aggregate } } extension ObjectIdentifier { @available(*, unavailable, message: "use the 'UInt(_:)' initializer") public var uintValue: UInt { fatalError("unavailable function can't be called") } }
apache-2.0
875775997e51f00c7d029329eea29a62
27.843003
88
0.670749
4.110409
false
false
false
false
vakoc/particle-swift
Examples/TVExample/TVExample/DevicesCollectionViewController.swift
1
4510
// This source file is part of the vakoc.com open source project(s) // // Copyright © 2018 Mark Vakoc. All rights reserved. // Licensed under Apache License v2.0 // // See http://www.vakoc.com/LICENSE.txt for license information import UIKit import ParticleSwift private let reuseIdentifier = "device" class DeviceCollectionViewCell: UICollectionViewCell { @IBOutlet weak var nameLabel: UILabel! } class DevicesCollectionViewController: UICollectionViewController { var deviceListResult = [DeviceInformation]() { didSet { collectionView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes collectionView!.register(UINib(nibName: "DeviceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshDevices(nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshDevices(_ sender: Any?) { (UIApplication.shared.delegate as! AppDelegate).particleCloud.devices { [weak self] (result) in /// If we are still around save the results of the call on the main thread if let this = self { DispatchQueue.main.async { switch result { case .success(let devices): this.deviceListResult = devices.sorted(by: { (a, b) -> Bool in return a.name < b.name }) case .failure( _): // Handle the error this.deviceListResult = [] } } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return deviceListResult.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DeviceCollectionViewCell cell.nameLabel.text = deviceListResult[indexPath.row].name return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
apache-2.0
5fdc2fa90fa74b656c6a42c7390a2f01
33.159091
170
0.655578
5.803089
false
false
false
false
joshua-d-miller/macOSLAPS
macOSLAPS/main.swift
1
11200
/// ------------------------ /// LAPS for macOS Devices /// ------------------------ /// Command line executable that handles automatic /// generation and rotation of the local administrator /// password. /// /// Current Usage: /// - Active Directory (Similar to Windows functionality) /// - Local (Password stored in Keychain Only) /// ------------------------- /// Joshua D. Miller - [email protected] /// /// Last Updated June 20, 2022 /// ------------------------- import Foundation struct Constants { // Begin by tying date_formatter() to a variable static let dateFormatter = date_formatter() // Read Command Line Arugments into array to use later static let arguments : Array = CommandLine.arguments // Retrieve our configuration for the application or use the // default values static let local_admin = GetPreference(preference_key: "LocalAdminAccount") as! String static let password_length = GetPreference(preference_key: "PasswordLength") as! Int static let days_till_expiration = GetPreference(preference_key: "DaysTillExpiration") as! Int static let remove_keychain = GetPreference(preference_key: "RemoveKeychain") as! Bool static let characters_to_remove = GetPreference(preference_key: "RemovePassChars") as! String static let character_exclusion_sets = GetPreference(preference_key: "ExclusionSets") as? Array<String> static let preferred_domain_controller = GetPreference(preference_key: "PreferredDC") as! String static var first_password = GetPreference(preference_key: "FirstPass") as! String static let method = GetPreference(preference_key: "Method") as! String static let passwordrequirements = GetPreference(preference_key: "PasswordRequirements") as! Dictionary<String, Any> // Constant values if triggering a password reset / specifying a First Password static var pw_reset : Bool = false static var use_firstpass : Bool = false } func macOSLAPS() { // Check if running as root let current_running_User = NSUserName() if current_running_User != "root" { laps_log.print("macOSLAPS needs to be run as root to ensure the password change for \(Constants.local_admin) if needed.", .error) exit(77) } let output_dir = "/var/root/Library/Application Support" // Remove files from extracting password if they exist if FileManager.default.fileExists(atPath: "\(output_dir)/macOSLAPS-password") { do { try FileManager.default.removeItem(atPath: "/var/root/Library/Application Support/macOSLAPS-password") try FileManager.default.removeItem(atPath: "/var/root/Library/Application Support/macOSLAPS-expiration") } catch { laps_log.print("Unable to remove files used for extraction of password for MDM. Please delete manually", .warn) } } // Iterate through supported Arguments for argument in Constants.arguments { switch argument { case "-version": let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String print(appVersion) exit(0) case "-getPassword": if Constants.method == "Local" { let (current_password, keychain_item_check) = KeychainService.loadPassword(service: "macOSLAPS") if current_password == nil && keychain_item_check == nil { laps_log.print("Unable to retrieve password from macOSLAPS Keychain entry.", .error) exit(1) } else if current_password == nil && keychain_item_check == "Not Found" { laps_log.print("There does not appear to be a macOSLAPS Keychain Entry. Most likely, a password change has never been performed or the first password change has failed due to an incorrect password", .error) exit(1) } else { do { // Verify Password let password_verify_status = Shell.run(launchPath: "/usr/bin/dscl", arguments: [".", "-authonly", Constants.local_admin, current_password!]) if password_verify_status == "" { laps_log.print("Password has been verified to work. Extracting...", .info) } else { laps_log.print("Password cannot be verified. The password is out of sync. Please run sysadminctl to perform a reset to restart rottation", .error) exit(1) } let current_expiration_date = LocalTools.get_expiration_date() let current_expiration_string = Constants.dateFormatter.string(for: current_expiration_date) // Verify our output Directory exists and if not create it var isDir:ObjCBool = true // Write contents to file if !FileManager.default.fileExists(atPath: output_dir, isDirectory: &isDir) { do { laps_log.print("Creating directory \(output_dir) as it does not currently exist. This issue was first present in macOS 12.2.1 on Apple Silicon", .warn) try FileManager.default.createDirectory(atPath: output_dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o755, .ownerAccountID: 0, .groupOwnerAccountID: 0]) laps_log.print("Directory \(output_dir) has been created. Continuing...") } catch { laps_log.print("An error occured attempting to create the directory \(output_dir). Unable to extract password. Exiting...") exit(0) } } try current_password!.write(toFile: "/var/root/Library/Application Support/macOSLAPS-password", atomically: true, encoding: String.Encoding.utf8) try current_expiration_string!.write(toFile: "/var/root/Library/Application Support/macOSLAPS-expiration", atomically: true, encoding: String.Encoding.utf8) exit(0) } catch let error as NSError { laps_log.print("Unable to extract password from keychain. Error: \(error)", .error) } exit(1) } } else { laps_log.print("Will not display password as our current method is Active Directory", .warn) exit(0) } case "-resetPassword": Constants.pw_reset = true case "-help": print(""" macOSLAPS Help ============== These are the arguments that you can use with macOSLAPS. You may only use one argument at a time. -version Prints Current Version of macOSLAPS and gracefully exits -getPassword If using the Local method, the password will be outputted to the filesystem temporarily. Password is deleted upon next automated or manual run -resetPassword Forces a password reset no matter the expiration date -firstPass Performs a password reset using the FirstPass Configuration Profile key or the password you specify after this flag. The password of the admin MUST be this password or the change WILL FAIL. -help Displays this screen """) exit(0) case "-firstPass": Constants.pw_reset = true Constants.use_firstpass = true if Constants.first_password == "" { Constants.first_password = CommandLine.arguments[2] } if Constants.first_password == "" { laps_log.print("No password is specified via the FirstPass key OR in the command line. Exiting...", .error) exit(1) } laps_log.print("the -firstPass argument was invoked. Using the Configuration Profile specified password or the argument password that was specified.", .info) default: continue } } switch Constants.method { case "AD": // Active Directory Password Change Function let ad_computer_record = ADTools.connect() // Get Expiration Time from Active Directory var ad_exp_time = "" if Constants.pw_reset == true { ad_exp_time = "126227988000000000" } else { ad_exp_time = ADTools.check_pw_expiration(computer_record: ad_computer_record)! } // Convert that time into a date let exp_date = TimeConversion.epoch(exp_time: ad_exp_time) // Compare that newly calculated date against now to see if a change is required if exp_date! < Date() { // Check if the domain controller that we are connected to is writable ADTools.verify_dc_writability(computer_record: ad_computer_record) // Performs Password Change for local admin account laps_log.print("Password Change is required as the LAPS password for \(Constants.local_admin), has expired", .info) ADTools.password_change(computer_record: ad_computer_record) } else { let actual_exp_date = Constants.dateFormatter.string(from: exp_date!) laps_log.print("Password change is not required as the password for \(Constants.local_admin) does not expire until \(actual_exp_date)", .info) exit(0) } case "Local": // Local method to perform passwords changes locally vs relying on Active Directory. // It is assumed that users will be using either an MDM or some reporting method to store // the password somewhere // Load the Keychain Item and compare the date var exp_date : Date? if Constants.pw_reset == true { exp_date = Calendar.current.date(byAdding: .day, value: -7, to: Date()) } else { exp_date = LocalTools.get_expiration_date() } if exp_date! < Date() { LocalTools.password_change() let new_exp_date = LocalTools.get_expiration_date() laps_log.print("Password change has been completed for the local admin \(Constants.local_admin). New expiration date is \(Constants.dateFormatter.string(from: new_exp_date!))", .info) exit(0) } else { laps_log.print("Password change is not required as the password for \(Constants.local_admin) does not expire until \(Constants.dateFormatter.string(from: exp_date!))", .info) exit(0) } default: exit(0) } } macOSLAPS()
mit
b5c61965c69471a24cd24105729c4fd4
53.901961
226
0.588125
5.02017
false
false
false
false
benlangmuir/swift
test/Concurrency/Runtime/async_initializer.swift
7
3914
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.1, *) actor NameGenerator { private var counter = 0 private var prefix : String init(_ title: String) { self.prefix = title } func getName() -> String { counter += 1 return "\(prefix) \(counter)" } } @available(SwiftStdlib 5.1, *) protocol Person { init() async var name : String { get set } } @available(SwiftStdlib 5.1, *) class EarthPerson : Person { private static let oracle = NameGenerator("Earthling") var name : String required init() async { self.name = await EarthPerson.oracle.getName() } init(name: String) async { self.name = await (detach { name }).get() } } @available(SwiftStdlib 5.1, *) class NorthAmericaPerson : EarthPerson { private static let oracle = NameGenerator("NorthAmerican") required init() async { await super.init() self.name = await NorthAmericaPerson.oracle.getName() } override init(name: String) async { await super.init(name: name) } } @available(SwiftStdlib 5.1, *) class PrecariousClass { init?(nilIt : Int) async { let _ : Optional<Int> = await (detach { nil }).get() return nil } init(throwIt : Double) async throws { if await (detach { 0 }).get() != 1 { throw Something.bogus } } init?(nilOrThrowIt shouldThrow: Bool) async throws { let flag = await (detach { shouldThrow }).get() if flag { throw Something.bogus } return nil } init!(crashOrThrowIt shouldThrow: Bool) async throws { let flag = await (detach { shouldThrow }).get() if flag { throw Something.bogus } return nil } } enum Something : Error { case bogus } @available(SwiftStdlib 5.1, *) struct PrecariousStruct { init?(nilIt : Int) async { let _ : Optional<Int> = await (detach { nil }).get() return nil } init(throwIt : Double) async throws { if await (detach { 0 }).get() != 1 { throw Something.bogus } } } // CHECK: Earthling 1 // CHECK-NEXT: Alice // CHECK-NEXT: Earthling 2 // CHECK-NEXT: Bob // CHECK-NEXT: Earthling 3 // CHECK-NEXT: Alex // CHECK-NEXT: NorthAmerican 1 // CHECK-NEXT: NorthAmerican 2 // CHECK-NEXT: Earthling 6 // CHECK-NEXT: class was nil // CHECK-NEXT: class threw // CHECK-NEXT: nilOrThrowIt init was nil // CHECK-NEXT: nilOrThrowIt init threw // CHECK-NEXT: crashOrThrowIt init threw // CHECK-NEXT: struct was nil // CHECK-NEXT: struct threw // CHECK: done @available(SwiftStdlib 5.1, *) @main struct RunIt { static func main() async { let people : [Person] = [ await EarthPerson(), await NorthAmericaPerson(name: "Alice"), await EarthPerson(), await NorthAmericaPerson(name: "Bob"), await EarthPerson(), await NorthAmericaPerson(name: "Alex"), await NorthAmericaPerson(), await NorthAmericaPerson(), await EarthPerson() ] for p in people { print(p.name) } // ---- if await PrecariousClass(nilIt: 0) == nil { print("class was nil") } do { let _ = try await PrecariousClass(throwIt: 0.0) } catch { print("class threw") } if try! await PrecariousClass(nilOrThrowIt: false) == nil { print("nilOrThrowIt init was nil") } do { let _ = try await PrecariousClass(nilOrThrowIt: true) } catch { print("nilOrThrowIt init threw") } do { let _ = try await PrecariousClass(crashOrThrowIt: true) } catch { print("crashOrThrowIt init threw") } if await PrecariousStruct(nilIt: 0) == nil { print("struct was nil") } do { let _ = try await PrecariousStruct(throwIt: 0.0) } catch { print("struct threw") } print("done") } }
apache-2.0
16435c4d8b012f60e97edb9a8cee9811
21.365714
110
0.637966
3.921844
false
false
false
false
bitjammer/swift
test/SILGen/dynamic_lookup.swift
3
15622
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // REQUIRES: objc_interop class X { @objc func f() { } @objc class func staticF() { } @objc var value: Int { return 17 } @objc subscript (i: Int) -> Int { get { return i } set {} } } @objc protocol P { func g() } // CHECK-LABEL: sil hidden @_T014dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F func direct_to_class(_ obj: AnyObject) { // CHECK: bb0([[ARG:%.*]] : $AnyObject): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[BORROWED_ARG]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: destroy_value [[OPENED_ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] obj.f!() } // CHECK: } // end sil function '_T014dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T014dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F func direct_to_protocol(_ obj: AnyObject) { // CHECK: bb0([[ARG:%.*]] : $AnyObject): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[BORROWED_ARG]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: destroy_value [[OPENED_ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] obj.g!() } // CHECK: } // end sil function '_T014dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T014dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F func direct_to_static_method(_ obj: AnyObject) { // CHECK: bb0([[ARG:%.*]] : $AnyObject): var obj = obj // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load_borrow [[PBOBJ]] : $*AnyObject // CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type // CHECK-NEXT: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () // CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> () // CHECK: destroy_value [[OBJBOX]] // CHECK: destroy_value [[ARG]] type(of: obj).staticF!() } // } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}' // CHECK-LABEL: sil hidden @_T014dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F func opt_to_class(_ obj: AnyObject) { // CHECK: bb0([[ARG:%.*]] : $AnyObject): var obj = obj // CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned () -> ()> } // CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]] // CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject // CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]] // CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_owned () -> ()> // CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]] // Has method BB: // CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()): // CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]] // CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> () // CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]] // CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]] // CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_owned () -> ()>, #Optional.some!enumelt.1 // CHECK: br [[CONTBB:[a-zA-Z0-9]+]] // No method BB: // CHECK: [[NOBB]]: // CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt // CHECK: br [[CONTBB]] // Continuation block // CHECK: [[CONTBB]]: // CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]] // CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_owned () -> ()> // CHECK: dealloc_stack [[OPT_TMP]] var of: (() -> ())! = obj.f // Exit // CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject // CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_owned () -> ()> } // CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject } // CHECK: destroy_value %0 // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } // CHECK-LABEL: sil hidden @_T014dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F func forced_without_outer(_ obj: AnyObject) { // CHECK: dynamic_method_br var f = obj.f! } // CHECK-LABEL: sil hidden @_T014dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F func opt_to_static_method(_ obj: AnyObject) { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]] // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]] // CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]] // CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned () -> ()> } // CHECK: [[PBO:%.*]] = project_box [[OPTBOX]] // CHECK: [[OBJCOPY:%[0-9]+]] = load_borrow [[PBOBJ]] : $*AnyObject // CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject // CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened // CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]] // CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_owned () -> ()> // CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]] var optF: (() -> ())! = type(of: obj).staticF } // CHECK-LABEL: sil hidden @_T014dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F func opt_to_property(_ obj: AnyObject) { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]] // CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]] // CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: project_box [[INT_BOX]] // CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject // CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject // CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int): // CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]] // CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int // CHECK: [[VALUE:%[0-9]+]] = apply [[BOUND_METHOD]]() : $@callee_owned () -> Int // CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]] // CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some // CHECK: br bb3 var i: Int = obj.value! } // CHECK: } // end sil function '_T014dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T014dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F func direct_to_subscript(_ obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]] // CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]] // CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK: store [[I]] to [trivial] [[PBI]] : $*Int // CHECK: alloc_box ${ var Int } // CHECK: project_box // CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject // CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[I:%[0-9]+]] = load [trivial] [[PBI]] : $*Int // CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]] // CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]] // CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some // CHECK: br bb3 var x: Int = obj[i]! } // CHECK: } // end sil function '_T014dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @_T014dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F func opt_to_subscript(_ obj: AnyObject, i: Int) { var obj = obj var i = i // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]] // CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]] // CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBI:%.*]] = project_box [[I_BOX]] // CHECK: store [[I]] to [trivial] [[PBI]] : $*Int // CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject // CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject // CHECK: [[I:%[0-9]+]] = load [trivial] [[PBI]] : $*Int // CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2 // CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]] // CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int // CHECK: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int // CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]] // CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]] // CHECK: inject_enum_addr [[OPTTEMP]] // CHECK: br bb3 obj[i] } // CHECK-LABEL: sil hidden @_T014dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F func downcast(_ obj: AnyObject) -> X { var obj = obj // CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject): // CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject } // CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]] // CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]] // CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]] // CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject // CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]] // CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject // CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X // CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject } // CHECK: destroy_value %0 // CHECK: return [[X]] : $X return obj as! X } @objc class Juice { } @objc protocol Fruit { @objc optional var juice: Juice { get } } // CHECK-LABEL: sil hidden @_T014dynamic_lookup7consumeyAA5Fruit_pF // CHECK: bb0(%0 : $Fruit): // CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice> // CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2 // CHECK: bb1([[FN:%.*]] : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice // CHECK: [[RESULT:%.*]] = apply [[METHOD]]() : $@callee_owned () -> @owned Juice // CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1 // CHECK: store [[RESULT]] to [init] [[PAYLOAD]] // CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1 // CHECK: br bb3 // CHECK: bb2: // CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt // CHECK: br bb3 // CHECK: bb3: // CHECK: return func consume(_ fruit: Fruit) { _ = fruit.juice } // rdar://problem/29249513 -- looking up an IUO member through AnyObject // produces a Foo!? type. The SIL verifier did not correctly consider Optional // to be the lowering of IUO (which is now eliminated by SIL lowering). @objc protocol IUORequirement { var iuoProperty: AnyObject! { get } } func getIUOPropertyDynamically(x: AnyObject) -> Any { return x.iuoProperty }
apache-2.0
a4f876152020e06d5923ff26aae5bf14
50.557756
243
0.565677
3.162988
false
false
false
false
Pocketbrain/nativeadslib-ios
PocketMediaNativeAds/Core/Caching.swift
1
4561
// // Caching.swift // PocketMediaNativeAds // // Created by Iain Munro on 16/09/16. // // import Foundation import UIKit /** This class contains the sharedCache used for the images. */ class Caching { /// Static constant variable with our cache. static let sharedCache: NSCache = { () -> NSCache<AnyObject, AnyObject> in let cache = NSCache<AnyObject, AnyObject>() cache.name = "PocketMediaCache" // cache.countLimit = 1000 // Max 20 images in memory. // cache.totalCostLimit = 100 * 1024 * 1024 // Max 100MB used. return cache }() } /** This extension is used to cache the ad images. */ extension URL { /// Defines the method signature of the on completion methods. typealias ImageCacheCompletion = (UIImage) -> Void /// Holds the callbacks. URI as key. fileprivate static var callbacks = [String: [ImageCacheCompletion]]() /// Returns the cache key of a URL instance. func getCacheKey() -> String { return self.absoluteString // self.lastPathComponent! } /// Retrieves a pre-cached image, or nil if it isn't cached. /// You should call this before calling fetchImage. var cachedImage: UIImage? { return Caching.sharedCache.object( forKey: getCacheKey() as AnyObject) as? UIImage } /** Fetches the image from the network. Stores it in the cache if successful. Only calls completion on successful image download. Completion is called on the main thread. */ func fetchImage(_ completion: @escaping ImageCacheCompletion) { if URL.callbacks[self.getCacheKey()] == nil { // create it. URL.callbacks[self.getCacheKey()] = [ImageCacheCompletion]() let task = URLSession.shared.dataTask(with: self, completionHandler: { data, response, error in if error == nil { if let data = data, let image = UIImage(data: data) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { Caching.sharedCache.setObject(image, forKey: self.getCacheKey() as AnyObject, cost: data.count) for callback in URL.callbacks[self.getCacheKey()]! { callback(image) } // Reset it. So that if the Cache decides the remove this image. We'll be able to download it again. URL.callbacks[self.getCacheKey()] = nil } } } }) task.resume() } // Add to the list of images we need to call when we have the requested result. URL.callbacks[self.getCacheKey()]!.append(completion) } } /** This extension is used to cache the ad images. */ public extension UIImageView { /// The last url that an instance of the imageView has asked for. fileprivate static var currentUrl = [UIImageView: URL]() /** This method will kick off the caching process. It will start fetching the image if it isn't already being downloaded or in the cache and eventually call set the self.image. */ func nativeSetImageFromURL(_ url: URL, completion handler: ((Bool) -> Swift.Void)? = nil) { if UIImageView.currentUrl[self] == url { return } if let campaignImage = url.cachedImage { // Cached self.image = campaignImage // Clear up after ourselves. UIImageView.currentUrl[self] = nil } else { // Set this url as the last url we've asked for. UIImageView.currentUrl[self] = url url.fetchImage({ downloadedImage in // In some cases this fetchImage call gets called very quickly if people scroll very quickly. // This check here, makes sure that the response we are getting for this image, is actually the one he has last requested. if UIImageView.currentUrl[self] != url { return } self.image = downloadedImage handler?(true) // Check the cell hasn't recycled while loading. // UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: { // self.image = downloadedImage // }, completion: handler) }) } } }
mit
7749a6d0ad6c2b3422b1101ccf684868
35.198413
177
0.579917
5.006586
false
false
false
false
ACChe/eidolon
Kiosk/Auction Listings/MasonryCollectionViewCell.swift
1
4759
import UIKit let MasonryCollectionViewCellWidth: CGFloat = 254 class MasonryCollectionViewCell: ListingsCollectionViewCell { private lazy var bidView: UIView = { let view = UIView() for subview in [self.currentBidLabel, self.numberOfBidsLabel] { view.addSubview(subview) subview.alignTopEdgeWithView(view, predicate:"13") subview.alignBottomEdgeWithView(view, predicate:"0") subview.constrainHeight("18") } self.currentBidLabel.alignLeadingEdgeWithView(view, predicate: "0") self.numberOfBidsLabel.alignTrailingEdgeWithView(view, predicate: "0") return view }() private lazy var cellSubviews: [UIView] = [self.artworkImageView, self.lotNumberLabel, self.artistNameLabel, self.artworkTitleLabel, self.estimateLabel, self.bidView, self.bidButton, self.moreInfoLabel] private var artworkImageViewHeightConstraint: NSLayoutConstraint? override func setup() { super.setup() contentView.constrainWidth("\(MasonryCollectionViewCellWidth)") // Add subviews for subview in cellSubviews { self.contentView.addSubview(subview) subview.alignLeading("0", trailing: "0", toView: self.contentView) } // Constrain subviews artworkImageView.alignTop("0", bottom: nil, toView: contentView) let lotNumberTopConstraint = lotNumberLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkImageView, predicate: "20").first as! NSLayoutConstraint let artistNameTopConstraint = artistNameLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: lotNumberLabel, predicate: "10").first as! NSLayoutConstraint artistNameLabel.constrainHeight("20") artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artistNameLabel, predicate: "10") artworkTitleLabel.constrainHeight("16") estimateLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkTitleLabel, predicate: "10") estimateLabel.constrainHeight("16") bidView.alignAttribute(.Top, toAttribute: .Bottom, ofView: estimateLabel, predicate: "13") bidButton.alignAttribute(.Top, toAttribute: .Bottom, ofView: currentBidLabel, predicate: "13") moreInfoLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: bidButton, predicate: "0") moreInfoLabel.constrainHeight("44") moreInfoLabel.alignAttribute(.Bottom, toAttribute: .Bottom, ofView: contentView, predicate: "12") RACObserve(lotNumberLabel, "text").subscribeNext { (text) -> Void in switch text as! String? { case .Some(let text) where text.isEmpty: fallthrough case .None: lotNumberTopConstraint.constant = 0 artistNameTopConstraint.constant = 20 default: lotNumberTopConstraint.constant = 20 artistNameTopConstraint.constant = 10 } } // Bind subviews viewModelSignal.subscribeNext { [weak self] (viewModel) -> Void in let viewModel = viewModel as! SaleArtworkViewModel if let artworkImageViewHeightConstraint = self?.artworkImageViewHeightConstraint { self?.artworkImageView.removeConstraint(artworkImageViewHeightConstraint) } let imageHeight = heightForImageWithAspectRatio(viewModel.thumbnailAspectRatio) self?.artworkImageViewHeightConstraint = self?.artworkImageView.constrainHeight("\(imageHeight)").first as? NSLayoutConstraint self?.layoutIfNeeded() } } override func layoutSubviews() { super.layoutSubviews() bidView.drawTopDottedBorderWithColor(.artsyMediumGrey()) } } extension MasonryCollectionViewCell { class func heightForCellWithImageAspectRatio(aspectRatio: CGFloat?) -> CGFloat { let imageHeight = heightForImageWithAspectRatio(aspectRatio) let remainingHeight = 20 + // padding 20 + // artist name 10 + // padding 16 + // artwork name 10 + // padding 16 + // estimate 13 + // padding 13 + // padding 16 + // bid 13 + // padding 44 + // more info button 12 // padding return imageHeight + ButtonHeight + CGFloat(remainingHeight) } } private func heightForImageWithAspectRatio(aspectRatio: CGFloat?) -> CGFloat { if let ratio = aspectRatio { if ratio != 0 { return CGFloat(MasonryCollectionViewCellWidth) / ratio } } return CGFloat(MasonryCollectionViewCellWidth) }
mit
66a39c2e6d872192dc9d747f0fd05873
43.064815
206
0.656651
5.592244
false
false
false
false
rpitting/LGLinearFlow
Example/LGMagnifyingLinearFlowLayout/ViewController.swift
1
4775
// // ViewController.swift // LGLinearFlowViewSwift // // Created by Luka Gabric on 16/08/15. // Copyright © 2015 Luka Gabric. All rights reserved. // import UIKit import LGMagnifyingLinearFlowLayout class ViewController: UIViewController { // MARK: Vars private var collectionViewLayout: LGMagnifyingLinearFlowLayout! private var dataSource: Array<String>! @IBOutlet private var collectionView: UICollectionView! @IBOutlet private var nextButton: UIButton! @IBOutlet private var previousButton: UIButton! @IBOutlet private var pageControl: UIPageControl! private var animationsCount = 0 private var pageWidth: CGFloat { return self.collectionViewLayout.itemSize.width + self.collectionViewLayout.minimumLineSpacing } private var contentOffset: CGFloat { return self.collectionView.contentOffset.x + self.collectionView.contentInset.left } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.configureDataSource() self.configureCollectionView() self.configurePageControl() self.configureButtons() } // MARK: Configuration private func configureDataSource() { self.dataSource = Array() for index in 1...10 { self.dataSource.append("Page \(index)") } } private func configureCollectionView() { self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast self.collectionView.registerNib(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell") let layout = LGMagnifyingLinearFlowLayout() layout.minimumLineSpacing = 0 layout.itemSize = CGSizeMake(180, 180) self.collectionViewLayout = layout self.collectionView.collectionViewLayout = layout } private func configurePageControl() { self.pageControl.numberOfPages = self.dataSource.count } private func configureButtons() { self.nextButton.enabled = self.dataSource.count > 0 && self.pageControl.currentPage < self.dataSource.count - 1 self.previousButton.enabled = self.pageControl.currentPage > 0 } // MARK: Actions @IBAction private func pageControlValueChanged(sender: AnyObject) { self.scrollToPage(self.pageControl.currentPage, animated: true) } @IBAction private func nextButtonAction(sender: AnyObject) { self.scrollToPage(self.pageControl.currentPage + 1, animated: true) } @IBAction private func previousButtonAction(sender: AnyObject) { self.scrollToPage(self.pageControl.currentPage - 1, animated: true) } private func scrollToPage(page: Int, animated: Bool) { self.collectionView.userInteractionEnabled = false self.animationsCount += 1 let pageOffset = CGFloat(page) * self.pageWidth - self.collectionView.contentInset.left self.collectionView.setContentOffset(CGPointMake(pageOffset, 0), animated: true) self.pageControl.currentPage = page self.configureButtons() } } extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataSource.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let collectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell collectionViewCell.pageLabel.text = self.dataSource[indexPath.row] return collectionViewCell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if collectionView.dragging || collectionView.decelerating || collectionView.tracking { return } let selectedPage = indexPath.row if selectedPage == self.pageControl.currentPage { NSLog("Did select center item") } else { self.scrollToPage(selectedPage, animated: true) } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.pageControl.currentPage = Int(self.contentOffset / self.pageWidth) self.configureButtons() } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { self.animationsCount -= 1 if self.animationsCount == 0 { self.collectionView.userInteractionEnabled = true } } }
mit
3818b587df7db8b6339e577042ec5a01
33.345324
156
0.68894
5.590164
false
true
false
false
michaelvu812/MVFetchedResultsController
MVFetchedResultsController/MVFetchedResultsController.swift
1
6260
// // MVFetchedResultsController.swift // MVFetchedResultsController // // Created by Michael on 1/7/14. // Copyright (c) 2014 Michael Vu. All rights reserved. // import UIKit import CoreData class MVFetchedResultsController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { var context: NSManagedObjectContext = AppDelegate().managedObjectContext var fetchSize: Int = 5 var sortDescriptor: NSSortDescriptor = NSSortDescriptor() var entityName: String = String() { didSet { initFetchedResultsController() } } var tableView: UITableView = UITableView() var tableFrame: CGRect = CGRectZero { didSet { tableView.frame = tableFrame } } var tableBackgroundColor: UIColor = UIColor.clearColor() { didSet { tableView.backgroundColor = tableBackgroundColor } } var separatorColor: UIColor = UIColor.colorWithHexString("#bbbbbb") { didSet { tableView.separatorColor = separatorColor } } var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController() { didSet { if (fetchedResultsController != oldValue) { fetchedResultsController.delegate = self; if (fetchedResultsController.isKindOfClass(NSFetchedResultsController)) { self.performFetchResults() } else { self.tableView.reloadData() } } } } override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.backgroundColor = tableBackgroundColor self.tableView.dataSource = self self.tableView.delegate = self self.tableView.showsHorizontalScrollIndicator = false self.tableView.showsVerticalScrollIndicator = false self.tableView.separatorColor = self.separatorColor self.tableView.separatorStyle = .SingleLine self.tableView.separatorInset = UIEdgeInsetsZero self.view.addSubview(self.tableView) self.tableView.reloadData() } override func loadView() { super.loadView() if CGRectEqualToRect(self.tableView.frame, CGRectZero) { if CGRectEqualToRect(self.tableFrame, CGRectZero) { self.tableView.frame = self.view.frame } else { self.tableView.frame = self.tableFrame } } } func initFetchedResultsController() { var fetchRequest: NSFetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.fetchBatchSize = fetchSize if sortDescriptor != nil { fetchRequest.sortDescriptors = [sortDescriptor] } self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) } func performFetchResults() { if (self.fetchedResultsController.isKindOfClass(NSFetchedResultsController)) { var error: NSError? self.fetchedResultsController.performFetch(&error) } self.tableView.reloadData() } func numberOfSectionsInTableView(tableView: UITableView?) -> Int { if fetchedResultsController.sections != nil { return fetchedResultsController.sections.count } return 1 } func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { var rows = 0 if (fetchedResultsController.sections != nil && fetchedResultsController.sections.count > 0) { rows = fetchedResultsController.sections[section].numberOfObjects } return rows } func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! { return nil } func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool { return true } func controllerWillChangeContent(controller: NSFetchedResultsController!) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController!, didChangeSection sectionInfo: NSFetchedResultsSectionInfo!, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case NSFetchedResultsChangeInsert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) break case NSFetchedResultsChangeDelete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade) break default: break } } func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath : NSIndexPath!) { switch type { case NSFetchedResultsChangeInsert: self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) break case NSFetchedResultsChangeDelete: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) break case NSFetchedResultsChangeUpdate: self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) break case NSFetchedResultsChangeMove: self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) break default: break } } func controllerDidChangeContent(controller: NSFetchedResultsController!) { self.tableView.endUpdates() } }
mit
36a697a712207dd618d575e2728394f4
38.872611
214
0.663419
6.589474
false
false
false
false
spromicky/UICollectionViewAnimatedTransition
CollectionTransitions/src/transition/TransitionAnimator.swift
1
3152
// // TransitionAnimator.swift // CollectionTransitions // // Created by Nick on 1/7/16. // Copyright © 2016 spromicky. All rights reserved. // import Foundation import UIKit class TransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { let reverse: Bool init(reverse: Bool) { self.reverse = reverse super.init() } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { let defaultTime = 0.32 guard reverse else { return defaultTime } guard let transitionContext = transitionContext else { return defaultTime } guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? DetailViewController else { return defaultTime } guard let collectionView = fromVC.collectionView else { return defaultTime } let containFirstItem = collectionView.visibleCells().lazy.map { collectionView.indexPathForCell($0) }.contains { $0?.item == 0 } return containFirstItem ? defaultTime : 0.82 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else { return } guard let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else { return } guard let masterVC = (reverse ? toVC : fromVC) as? MasterViewController else { return } guard let detailVC = (reverse ? fromVC : toVC) as? DetailViewController else { return } guard let containerView = transitionContext.containerView() else { return } containerView.addSubview(toVC.view) if reverse { containerView.addSubview(fromVC.view) } else { toVC.view.frame = transitionContext.finalFrameForViewController(toVC) toVC.view.layoutIfNeeded() } if !reverse { detailVC.collectionView?.backgroundColor = .clearColor() } let cell = masterVC.collectionView?.cellForItemAtIndexPath(masterVC.selectedIndex) as! MasterCell cell.colorViews.forEach { $0.alpha = 0 } detailVC.flowLayout.toStartPosition = reverse detailVC.collectionView?.performBatchUpdates({ detailVC.collectionView?.collectionViewLayout.invalidateLayout() }, completion:nil) let invalidateTime = 0.32 UIView.animateWithDuration(invalidateTime, animations: { detailVC.collectionView?.backgroundColor = self.reverse ? .clearColor() : masterVC.collectionView?.backgroundColor }) { _ in cell.colorViews.forEach { $0.alpha = 1 } UIView.animateWithDuration(self.transitionDuration(transitionContext) - invalidateTime, animations: { guard self.reverse else { return } fromVC.view.alpha = 0 }) { _ in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true) } } } }
mit
426ede9d6746dfc25e5f8d47eaecd617
42.164384
160
0.673437
5.802947
false
false
false
false
loudnate/LoopKit
LoopKitTests/CarbStoreTests.swift
1
18751
// // CarbStoreTests.swift // LoopKitTests // // Copyright © 2018 LoopKit Authors. All rights reserved. // import XCTest import HealthKit import CoreData @testable import LoopKit class CarbStoreTests: PersistenceControllerTestCase, CarbStoreSyncDelegate { var carbStore: CarbStore! var healthStore: HKHealthStoreMock! override func setUp() { super.setUp() healthStore = HKHealthStoreMock() carbStore = CarbStore(healthStore: healthStore, cacheStore: cacheStore) carbStore.testQueryStore = healthStore carbStore.syncDelegate = self } override func tearDown() { carbStore.syncDelegate = nil carbStore = nil healthStore = nil uploadMessages = [] deleteMessages = [] uploadHandler = nil deleteHandler = nil super.tearDown() } // MARK: - CarbStoreSyncDelegate var uploadMessages: [(entries: [StoredCarbEntry], completion: ([StoredCarbEntry]) -> Void)] = [] var uploadHandler: ((_: [StoredCarbEntry], _: ([StoredCarbEntry]) -> Void) -> Void)? func carbStore(_ carbStore: CarbStore, hasEntriesNeedingUpload entries: [StoredCarbEntry], completion: @escaping ([StoredCarbEntry]) -> Void) { uploadMessages.append((entries: entries, completion: completion)) uploadHandler?(entries, completion) } var deleteMessages: [(entries: [DeletedCarbEntry], completion: ([DeletedCarbEntry]) -> Void)] = [] var deleteHandler: ((_: [DeletedCarbEntry], _: ([DeletedCarbEntry]) -> Void) -> Void)? func carbStore(_ carbStore: CarbStore, hasDeletedEntries entries: [DeletedCarbEntry], completion: @escaping ([DeletedCarbEntry]) -> Void) { deleteMessages.append((entries: entries, completion: completion)) deleteHandler?(entries, completion) } // MARK: - /// Adds a new entry, validates its uploading/uploaded transition func testAddAndSyncSuccessful() { let entry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let addCarb = expectation(description: "Add carb entry") let uploading = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") // 2. assert sync delegate called uploadHandler = { (entries, completion) in XCTAssertEqual(1, entries.count) // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) XCTAssertEqual(.uploading, objects.first!.uploadState) } uploading.fulfill() var entry = entries.first! entry.externalID = "1234" entry.isUploaded = true completion([entry]) // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() // 5. assert entered in db as uploaded XCTAssertEqual(.uploaded, objects.first!.uploadState) uploaded.fulfill() } } // 1. Add carb carbStore.addCarbEntry(entry) { (result) in addCarb.fulfill() } wait(for: [addCarb, uploading, uploaded], timeout: 2, enforceOrder: true) } /// Adds a new entry, validates its uploading/notUploaded transition func testAddAndSyncFailed() { let entry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let addCarb = expectation(description: "Add carb entry") let uploading = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") // 2. assert sync delegate called uploadHandler = { (entries, completion) in XCTAssertEqual(1, entries.count) // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) XCTAssertEqual(.uploading, objects.first!.uploadState) } uploading.fulfill() completion(entries) // Not uploaded // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() // 5. assert entered in db as not uploaded XCTAssertEqual(.notUploaded, objects.first!.uploadState) uploaded.fulfill() } } // 1. Add carb carbStore.addCarbEntry(entry) { (result) in addCarb.fulfill() } wait(for: [addCarb, uploading, uploaded], timeout: 2, enforceOrder: true) } /// Adds two entries, validating their transition as the delegate calls completion out-of-order func testAddAndSyncInterleve() { let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let addCarb1 = expectation(description: "Add carb entry") let addCarb2 = expectation(description: "Add carb entry") let uploading1 = expectation(description: "Sync delegate: upload") let uploading2 = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") uploaded.expectedFulfillmentCount = 2 // 2. assert sync delegate called uploadHandler = { (entries, completion) in XCTAssertEqual(1, entries.count) // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(self.uploadMessages.count, objects.count) for object in objects { XCTAssertEqual(.uploading, object.uploadState) } } switch self.uploadMessages.count { case 1: uploading1.fulfill() self.carbStore.addCarbEntry(entry2) { (result) in addCarb2.fulfill() } case 2: uploading2.fulfill() for index in (0...1).reversed() { var entry = self.uploadMessages[index].entries.first! entry.externalID = "\(index)" entry.isUploaded = true self.uploadMessages[index].completion([entry]) // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() for object in objects { if object.externalID == "\(index)" { XCTAssertEqual(.uploaded, object.uploadState) } } uploaded.fulfill() } } default: XCTFail() } } // 1. Add carb 1 carbStore.addCarbEntry(entry1) { (result) in addCarb1.fulfill() } wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true) } /// Adds an entry with a failed upload, validates its requested again for sync on next entry func testAddAndSyncMultipleCallbacks() { let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let addCarb1 = expectation(description: "Add carb entry") let addCarb2 = expectation(description: "Add carb entry") let uploading1 = expectation(description: "Sync delegate: upload") let uploading2 = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") uploaded.expectedFulfillmentCount = 2 // 2. assert sync delegate called uploadHandler = { (entries, completion) in // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(self.uploadMessages.count, objects.count) for object in objects { XCTAssertEqual(.uploading, object.uploadState) } } switch self.uploadMessages.count { case 1: XCTAssertEqual(1, entries.count) uploading1.fulfill() completion(entries) // Not uploaded self.carbStore.addCarbEntry(entry2) { (result) in addCarb2.fulfill() } case 2: XCTAssertEqual(2, entries.count) uploading2.fulfill() for index in (0...1).reversed() { var entry = self.uploadMessages[index].entries.first! entry.externalID = "\(index)" entry.isUploaded = true self.uploadMessages[index].completion([entry]) // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() for object in objects { if object.externalID == "\(index)" { XCTAssertEqual(.uploaded, object.uploadState) } } uploaded.fulfill() } } default: XCTFail() } } // 1. Add carb 1 carbStore.addCarbEntry(entry1) { (result) in addCarb1.fulfill() } wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true) } /// Adds and uploads an entry, then modifies it and validates its re-upload func testModifyUploadedCarb() { let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let sample2 = HKQuantitySample(type: carbStore.sampleType as! HKQuantityType, quantity: entry2.quantity, start: entry2.startDate, end: entry2.endDate) let addCarb1 = expectation(description: "Add carb entry") let addCarb2 = expectation(description: "Add carb entry") let uploading1 = expectation(description: "Sync delegate: upload") let uploading2 = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") var lastUUID: UUID? // 2. assert sync delegate called uploadHandler = { (entries, completion) in // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) XCTAssertEqual(.uploading, objects[0].uploadState) if let lastUUID = lastUUID { XCTAssertNotEqual(lastUUID, objects[0].uuid) } lastUUID = objects[0].uuid } switch self.uploadMessages.count { case 1: XCTAssertEqual(1, entries.count) uploading1.fulfill() var entry = entries.first! entry.externalID = "1234" entry.isUploaded = true completion([entry]) self.healthStore.queryResults = (samples: [sample2], error: nil) self.carbStore.replaceCarbEntry(entries.first!, withEntry: entry2) { (result) in addCarb2.fulfill() self.healthStore.queryResults = nil } case 2: XCTAssertEqual(1, entries.count) XCTAssertEqual("1234", entries.first!.externalID) XCTAssertFalse(entries.first!.isUploaded) uploading2.fulfill() var entry = entries.first! entry.isUploaded = true completion([entry]) // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) for object in objects { XCTAssertEqual(.uploaded, object.uploadState) } uploaded.fulfill() } default: XCTFail() } } deleteHandler = { (entries, completion) in XCTFail() } // 1. Add carb 1 carbStore.addCarbEntry(entry1) { (result) in addCarb1.fulfill() } wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true) } /// Adds an entry, modifying it before upload completes, validating the delegate is then asked to delete it func testModifyNotUploadedCarb() { let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: nil, absorptionTime: .hours(3)) let sample2 = HKQuantitySample(type: carbStore.sampleType as! HKQuantityType, quantity: entry2.quantity, start: entry2.startDate, end: entry2.endDate) let addCarb1 = expectation(description: "Add carb entry") let addCarb2 = expectation(description: "Add carb entry") let uploading1 = expectation(description: "Sync delegate: upload") let uploading2 = expectation(description: "Sync delegate: upload") let uploaded = expectation(description: "Sync delegate: completed") let deleted = expectation(description: "Sync delegate: deleted") // 2. assert sync delegate called uploadHandler = { (entries, completion) in // 3. assert entered in db as uploading self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) for object in objects { XCTAssertEqual(.uploading, object.uploadState) } } switch self.uploadMessages.count { case 1: XCTAssertEqual(1, entries.count) uploading1.fulfill() self.healthStore.queryResults = (samples: [sample2], error: nil) self.carbStore.replaceCarbEntry(entries.first!, withEntry: entry2) { (result) in addCarb2.fulfill() self.healthStore.queryResults = nil } case 2: XCTAssertEqual(1, entries.count) XCTAssertNil(entries.first!.externalID) XCTAssertFalse(entries.first!.isUploaded) uploading2.fulfill() var entry = entries.first! entry.externalID = "1234" entry.isUploaded = true completion([entry]) entry = self.uploadMessages[0].entries.first! entry.externalID = "5678" entry.isUploaded = true self.uploadMessages[0].completion([entry]) // 4. call delegate completion self.cacheStore.managedObjectContext.performAndWait { let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) for object in objects { XCTAssertEqual("1234", object.externalID) XCTAssertEqual(.uploaded, object.uploadState) } uploaded.fulfill() } default: XCTFail() } } deleteHandler = { (entries, completion) in XCTAssertEqual(1, entries.count) var entry = entries[0] XCTAssertEqual("5678", entry.externalID) XCTAssertFalse(entry.isUploaded) self.cacheStore.managedObjectContext.performAndWait { let objects: [DeletedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(1, objects.count) for object in objects { XCTAssertEqual("5678", object.externalID) XCTAssertEqual(.uploading, object.uploadState) } } entry.isUploaded = true completion([entry]) self.cacheStore.managedObjectContext.performAndWait { let objects: [DeletedCarbObject] = self.cacheStore.managedObjectContext.all() XCTAssertEqual(0, objects.count) } deleted.fulfill() } // 1. Add carb 1 carbStore.addCarbEntry(entry1) { (result) in addCarb1.fulfill() } wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded, deleted], timeout: 2, enforceOrder: true) } }
mit
5b46fcd17f91d5bb79518861c4779ddb
40.946309
158
0.58544
5.441091
false
false
false
false
lindydonna/azure-mobile-apps-quickstarts
client/iOS-Swift/ZUMOAPPNAME/ZUMOAPPNAME/ToDoTableViewController.swift
1
10811
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- // // 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 UIKit import CoreData class ToDoTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, ToDoItemDelegate { var table : MSSyncTable? var store : MSCoreDataStore? lazy var fetchedResultController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "TodoItem") let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! // show only non-completed items fetchRequest.predicate = NSPredicate(format: "complete != true") // sort by item text fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)] // Note: if storing a lot of data, you should specify a cache for the last parameter // for more information, see Apple's documentation: http://go.microsoft.com/fwlink/?LinkId=524591&clcid=0x409 let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) resultsController.delegate = self; return resultsController }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let client = MSClient(applicationURLString: "ZUMOAPPURL") let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! self.store = MSCoreDataStore(managedObjectContext: managedObjectContext) client.syncContext = MSSyncContext(delegate: nil, dataSource: self.store, callback: nil) self.table = client.syncTableWithName("TodoItem") self.refreshControl?.addTarget(self, action: "onRefresh:", forControlEvents: UIControlEvents.ValueChanged) var error : NSError? = nil do { try self.fetchedResultController.performFetch() } catch let error1 as NSError { error = error1 print("Unresolved error \(error), \(error?.userInfo)") abort() } // Refresh data on load self.refreshControl?.beginRefreshing() self.onRefresh(self.refreshControl) } func onRefresh(sender: UIRefreshControl!) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.table!.pullWithQuery(self.table?.query(), queryId: "AllRecords") { (error) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if error != nil { // A real application would handle various errors like network conditions, // server conflicts, etc via the MSSyncContextDelegate print("Error: \(error!.description)") // We will just discard our changes and keep the servers copy for simplicity if let opErrors = error!.userInfo[MSErrorPushResultKey] as? Array<MSTableOperationError> { for opError in opErrors { print("Attempted operation to item \(opError.itemId)") if (opError.operation == .Insert || opError.operation == .Delete) { print("Insert/Delete, failed discarding changes") opError.cancelOperationAndDiscardItemWithCompletion(nil) } else { print("Update failed, reverting to server's copy") opError.cancelOperationAndUpdateItem(opError.serverItem!, completion: nil) } } } } self.refreshControl?.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Table Controls override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.Delete } override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "Complete" } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let record = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject var item = self.store!.tableItemFromManagedObject(record) item["complete"] = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.table!.update(item) { (error) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if error != nil { print("Error: \(error!.description)") return } } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = self.fetchedResultController.sections { return sections[section].numberOfObjects } return 0; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellIdentifier = "Cell" var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) cell = configureCell(cell, indexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) -> UITableViewCell { let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject // Set the label on the cell and make sure the label color is black (in case this cell // has been reused and was previously greyed out if let text = item.valueForKey("text") as? String { cell.textLabel!.text = text } else { cell.textLabel!.text = "?" } cell.textLabel!.textColor = UIColor.blackColor() return cell } // MARK: Navigation @IBAction func addItem(sender : AnyObject) { self.performSegueWithIdentifier("addItem", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "addItem" { let todoController = segue.destinationViewController as! ToDoItemViewController todoController.delegate = self } } // MARK: - ToDoItemDelegate func didSaveItem(text: String) { if text.isEmpty { return } // We set created at to now, so it will sort as we expect it to post the push/pull let itemToInsert = ["text": text, "complete": false, "__createdAt": NSDate()] UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.table!.insert(itemToInsert) { (item, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if error != nil { print("Error: " + error!.description) } } } // MARK: - NSFetchedResultsDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.beginUpdates() }); } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { dispatch_async(dispatch_get_main_queue(), { () -> Void in let indexSectionSet = NSIndexSet(index: sectionIndex) if type == .Insert { self.tableView.insertSections(indexSectionSet, withRowAnimation: .Fade) } else if type == .Delete { self.tableView.deleteSections(indexSectionSet, withRowAnimation: .Fade) } }) } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { dispatch_async(dispatch_get_main_queue(), { () -> Void in switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Move: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Update: // note: Apple samples show a call to configureCell here; this is incorrect--it can result in retrieving the // wrong index when rows are reordered. For more information, see: // http://go.microsoft.com/fwlink/?LinkID=524590&clcid=0x409 self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) } }) } func controllerDidChangeContent(controller: NSFetchedResultsController) { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.endUpdates() }); } }
apache-2.0
2cad26006a13558c1974d2d0a833d5cb
40.741313
211
0.627139
5.904424
false
false
false
false
eggswift/ESTabBarController
Sources/ESTabBarItemContentView.swift
1
16255
// // ESTabBarContentView.swift // // Created by Vincent Li on 2017/2/8. // Copyright (c) 2013-2020 ESTabBarController (https://github.com/eggswift/ESTabBarController) // // 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 enum ESTabBarItemContentMode : Int { case alwaysOriginal // Always set the original image size case alwaysTemplate // Always set the image as a template image size } open class ESTabBarItemContentView: UIView { // MARK: - PROPERTY SETTING /// The title displayed on the item, default is `nil` open var title: String? { didSet { self.titleLabel.text = title self.updateLayout() } } /// The image used to represent the item, default is `nil` open var image: UIImage? { didSet { if !selected { self.updateDisplay() } } } /// The image displayed when the tab bar item is selected, default is `nil`. open var selectedImage: UIImage? { didSet { if selected { self.updateDisplay() } } } /// A Boolean value indicating whether the item is enabled, default is `YES`. open var enabled = true /// A Boolean value indicating whether the item is selected, default is `NO`. open var selected = false /// A Boolean value indicating whether the item is highlighted, default is `NO`. open var highlighted = false /// Text color, default is `UIColor(white: 0.57254902, alpha: 1.0)`. open var textColor = UIColor(white: 0.57254902, alpha: 1.0) { didSet { if !selected { titleLabel.textColor = textColor } } } /// Text color when highlighted, default is `UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0)`. open var highlightTextColor = UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0) { didSet { if selected { titleLabel.textColor = highlightTextColor } } } /// Icon color, default is `UIColor(white: 0.57254902, alpha: 1.0)`. open var iconColor = UIColor(white: 0.57254902, alpha: 1.0) { didSet { if !selected { imageView.tintColor = iconColor } } } /// Icon color when highlighted, default is `UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0)`. open var highlightIconColor = UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0) { didSet { if selected { imageView.tintColor = highlightIconColor } } } /// Background color, default is `UIColor.clear`. open var backdropColor = UIColor.clear { didSet { if !selected { backgroundColor = backdropColor } } } /// Background color when highlighted, default is `UIColor.clear`. open var highlightBackdropColor = UIColor.clear { didSet { if selected { backgroundColor = highlightBackdropColor } } } /// Icon imageView renderingMode, default is `.alwaysTemplate`. open var renderingMode: UIImage.RenderingMode = .alwaysTemplate { didSet { self.updateDisplay() } } /// Item content mode, default is `.alwaysTemplate` open var itemContentMode: ESTabBarItemContentMode = .alwaysTemplate { didSet { self.updateDisplay() } } /// The offset to use to adjust the title position, default is `UIOffset.zero`. open var titlePositionAdjustment: UIOffset = UIOffset.zero { didSet { self.updateLayout() } } /// The insets that you use to determine the insets edge for contents, default is `UIEdgeInsets.zero` open var insets = UIEdgeInsets.zero { didSet { self.updateLayout() } } open var imageView: UIImageView = { let imageView = UIImageView.init(frame: CGRect.zero) imageView.backgroundColor = .clear return imageView }() open var titleLabel: UILabel = { let titleLabel = UILabel.init(frame: CGRect.zero) titleLabel.backgroundColor = .clear titleLabel.textColor = .clear titleLabel.textAlignment = .center return titleLabel }() /// Badge value, default is `nil`. open var badgeValue: String? { didSet { if let _ = badgeValue { self.badgeView.badgeValue = badgeValue self.addSubview(badgeView) self.updateLayout() } else { // Remove when nil. self.badgeView.removeFromSuperview() } badgeChanged(animated: true, completion: nil) } } /// Badge color, default is `nil`. open var badgeColor: UIColor? { didSet { if let _ = badgeColor { self.badgeView.badgeColor = badgeColor } else { self.badgeView.badgeColor = ESTabBarItemBadgeView.defaultBadgeColor } } } /// Badge view, default is `ESTabBarItemBadgeView()`. open var badgeView: ESTabBarItemBadgeView = ESTabBarItemBadgeView() { willSet { if let _ = badgeView.superview { badgeView.removeFromSuperview() } } didSet { if let _ = badgeView.superview { self.updateLayout() } } } /// Badge offset, default is `UIOffset(horizontal: 6.0, vertical: -22.0)`. open var badgeOffset: UIOffset = UIOffset(horizontal: 6.0, vertical: -22.0) { didSet { if badgeOffset != oldValue { self.updateLayout() } } } // MARK: - public override init(frame: CGRect) { super.init(frame: frame) self.isUserInteractionEnabled = false addSubview(imageView) addSubview(titleLabel) titleLabel.textColor = textColor imageView.tintColor = iconColor backgroundColor = backdropColor } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open func updateDisplay() { imageView.image = (selected ? (selectedImage ?? image) : image)?.withRenderingMode(renderingMode) imageView.tintColor = selected ? highlightIconColor : iconColor titleLabel.textColor = selected ? highlightTextColor : textColor backgroundColor = selected ? highlightBackdropColor : backdropColor } open func updateLayout() { let w = self.bounds.size.width let h = self.bounds.size.height imageView.isHidden = (imageView.image == nil) titleLabel.isHidden = (titleLabel.text == nil) if self.itemContentMode == .alwaysTemplate { var s: CGFloat = 0.0 // image size var f: CGFloat = 0.0 // font var isLandscape = false if let keyWindow = UIApplication.shared.keyWindow { isLandscape = keyWindow.bounds.width > keyWindow.bounds.height } let isWide = isLandscape || traitCollection.horizontalSizeClass == .regular // is landscape or regular if #available(iOS 11.0, *), isWide { s = UIScreen.main.scale == 3.0 ? 23.0 : 20.0 f = UIScreen.main.scale == 3.0 ? 13.0 : 12.0 } else { s = 23.0 f = 10.0 } if !imageView.isHidden && !titleLabel.isHidden { titleLabel.font = UIFont.systemFont(ofSize: f) titleLabel.sizeToFit() if #available(iOS 11.0, *), isWide { titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + (UIScreen.main.scale == 3.0 ? 14.25 : 12.25) + titlePositionAdjustment.horizontal, y: (h - titleLabel.bounds.size.height) / 2.0 + titlePositionAdjustment.vertical, width: titleLabel.bounds.size.width, height: titleLabel.bounds.size.height) imageView.frame = CGRect.init(x: titleLabel.frame.origin.x - s - (UIScreen.main.scale == 3.0 ? 6.0 : 5.0), y: (h - s) / 2.0, width: s, height: s) } else { titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal, y: h - titleLabel.bounds.size.height - 1.0 + titlePositionAdjustment.vertical, width: titleLabel.bounds.size.width, height: titleLabel.bounds.size.height) imageView.frame = CGRect.init(x: (w - s) / 2.0, y: (h - s) / 2.0 - 6.0, width: s, height: s) } } else if !imageView.isHidden { imageView.frame = CGRect.init(x: (w - s) / 2.0, y: (h - s) / 2.0, width: s, height: s) } else if !titleLabel.isHidden { titleLabel.font = UIFont.systemFont(ofSize: f) titleLabel.sizeToFit() titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal, y: (h - titleLabel.bounds.size.height) / 2.0 + titlePositionAdjustment.vertical, width: titleLabel.bounds.size.width, height: titleLabel.bounds.size.height) } if let _ = badgeView.superview { let size = badgeView.sizeThatFits(self.frame.size) if #available(iOS 11.0, *), isWide { badgeView.frame = CGRect.init(origin: CGPoint.init(x: imageView.frame.midX - 3 + badgeOffset.horizontal, y: imageView.frame.midY + 3 + badgeOffset.vertical), size: size) } else { badgeView.frame = CGRect.init(origin: CGPoint.init(x: w / 2.0 + badgeOffset.horizontal, y: h / 2.0 + badgeOffset.vertical), size: size) } badgeView.setNeedsLayout() } } else { if !imageView.isHidden && !titleLabel.isHidden { titleLabel.sizeToFit() imageView.sizeToFit() titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal, y: h - titleLabel.bounds.size.height - 1.0 + titlePositionAdjustment.vertical, width: titleLabel.bounds.size.width, height: titleLabel.bounds.size.height) imageView.frame = CGRect.init(x: (w - imageView.bounds.size.width) / 2.0, y: (h - imageView.bounds.size.height) / 2.0 - 6.0, width: imageView.bounds.size.width, height: imageView.bounds.size.height) } else if !imageView.isHidden { imageView.sizeToFit() imageView.center = CGPoint.init(x: w / 2.0, y: h / 2.0) } else if !titleLabel.isHidden { titleLabel.sizeToFit() titleLabel.center = CGPoint.init(x: w / 2.0, y: h / 2.0) } if let _ = badgeView.superview { let size = badgeView.sizeThatFits(self.frame.size) badgeView.frame = CGRect.init(origin: CGPoint.init(x: w / 2.0 + badgeOffset.horizontal, y: h / 2.0 + badgeOffset.vertical), size: size) badgeView.setNeedsLayout() } } } // MARK: - INTERNAL METHODS internal final func select(animated: Bool, completion: (() -> ())?) { selected = true if enabled && highlighted { highlighted = false dehighlightAnimation(animated: animated, completion: { [weak self] in self?.updateDisplay() self?.selectAnimation(animated: animated, completion: completion) }) } else { updateDisplay() selectAnimation(animated: animated, completion: completion) } } internal final func deselect(animated: Bool, completion: (() -> ())?) { selected = false updateDisplay() self.deselectAnimation(animated: animated, completion: completion) } internal final func reselect(animated: Bool, completion: (() -> ())?) { if selected == false { select(animated: animated, completion: completion) } else { if enabled && highlighted { highlighted = false dehighlightAnimation(animated: animated, completion: { [weak self] in self?.reselectAnimation(animated: animated, completion: completion) }) } else { reselectAnimation(animated: animated, completion: completion) } } } internal final func highlight(animated: Bool, completion: (() -> ())?) { if !enabled { return } if highlighted == true { return } highlighted = true self.highlightAnimation(animated: animated, completion: completion) } internal final func dehighlight(animated: Bool, completion: (() -> ())?) { if !enabled { return } if !highlighted { return } highlighted = false self.dehighlightAnimation(animated: animated, completion: completion) } internal func badgeChanged(animated: Bool, completion: (() -> ())?) { self.badgeChangedAnimation(animated: animated, completion: completion) } // MARK: - ANIMATION METHODS open func selectAnimation(animated: Bool, completion: (() -> ())?) { completion?() } open func deselectAnimation(animated: Bool, completion: (() -> ())?) { completion?() } open func reselectAnimation(animated: Bool, completion: (() -> ())?) { completion?() } open func highlightAnimation(animated: Bool, completion: (() -> ())?) { completion?() } open func dehighlightAnimation(animated: Bool, completion: (() -> ())?) { completion?() } open func badgeChangedAnimation(animated: Bool, completion: (() -> ())?) { completion?() } }
mit
561409740b42772a0a4dec2e94f11fae
38.453883
189
0.545555
4.990789
false
false
false
false
sharkspeed/dororis
languages/swift/guide/20-nested-types.swift
1
25843
// import Foundation // import os // 20. Nested Types // define utility classes and structures purely for use within the context of a more complex type // Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support // BlackJack 汉语名称是梅花杰克又名,又名“二十一点” // 么点可当做1或11点,端看持有人如何运用;有人头的牌一律算10点;其他点与牌面所示相同。 // 20.1 Nested Types in Action // The BlackJack structure contains two nested enumeration types called Suit and Rank. struct BlackJackCard { enum Suit: Character { case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣" } enum Rank: Int { case two = 2, three, four, five, six, seven, eight, nine, ten case jack, queen, king, ace struct Values { let first: Int, second: Int? } var values: Values { // A computed property with a getter but no setter is known as a read-only computed property. switch self { case .ace: return Values(first: 1, second: 11) case .jack, .queen, .king: return Values(first: 10, second: nil) default: return Values(first: self.rawValue, second: nil) // the rank’s raw Int value } } } // properties and methods let rank: Rank, suit: Suit // Memberwise Initializers for Structure Types. var description: String { var output = "suit is \(suit.rawValue)," output += " value is \(rank.values.first)" if let second = rank.values.second { output += " or \(second)" } return output } } let theAceOfSpades = BlackJackCard(rank: .ace, suit: .spades) // Even though Rank and Suit are nested within BlackjackCard, their type can be inferred from context, and so the initialization of this instance is able to refer to the enumeration cases by their case names (.ace and .spades) alone print("theAceOfSpades: \(theAceOfSpades.description)") // 20.2 Referring to Nested Types // use a nested type outside of its definition context let heartsSymbol = BlackJackCard.Suit.hearts.rawValue print("heartsSymbol is \(heartsSymbol)") // 21. Extensions // Extensions add new functionality to an existing class, structure, enumeration, or protocol type. include the ability to extend types for which you do not have access to the original source code // Extensions in Swift can: // Add computed instance properties and computed type properties // Define instance methods and type methods // Provide new initializers // Define subscripts // Define and use new nested types // Make an existing type conform to a protocol // can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. // Extensions can add new functionality to a type, but they cannot override existing functionality. // 21.1 Extension Syntax /* extension SomeType { new functionality to add to SomeType } */ // An extension can extend an existing type to make it adopt one or more protocols. /* extension SomeType: SomeProtocol, AnotherProtocol { implementation of protocol requirements } */ // An extension can be used to extend an existing generic type or extend a generic type to conditionally add functionality // 对一个类的扩展会影响已经创建的实例 // 21.2 Computed Properties // add computed instance properties and computed type properties to existing types // * adds five computed instance properties to Swift’s built-in Double type extension Double { // a Double value of 1.0 is considered to represent “one meter” var km: Double { return self * 1_000.0 } var m: Double { return self } var cm: Double { return self / 100.0 } var mm: Double { return self / 1_000.0 } var ft: Double { return self / 3.28084 } } let oneInch = 25.4.mm print("one inch is \(oneInch) meters") let aMarathon = 42.km + 195.m print("A marathon is \(aMarathon) meters long") // Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties. // 21.3 Initializers // to extend other types to accept your own custom types as initializer parameters, or to provide additional initialization options that were not included as part of the type’s original implementation // can add new convenience initializers to a class, but they cannot add new designated initializers or deinitializers to a class struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() } // Rect 有默认初始化参数 Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself let defaultRect = Rect() let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) // extend the Rect structure to provide an additional initializer takes a specific center point and size extension Rect { init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // 需要保证每个实例完全初始化 // 21.4 Methods // add new instance methods and type methods to existing types 添加实例方法和类方法 // 给 Int 类型添加 extension Int { func repetitions(task: () -> Void) { for _ in 0..<self { task() } } } // repetions(task:) takes a single argument of type() -> Void => a function that has no parameters and does not return a value 3.repetitions { print("Hello!") } // 21.4.1 Mutating Instance Methods // Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation. extension Int { mutating func square() { self = self * self } } var myInt = 3 myInt.square() print("myInt square is \(myInt)") // 21.5 Subscripts // add new subscripts to an existing type // 123456789[0] returns 9 // 123456789[1] returns 8 extension Int { subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0..<digitIndex { decimalBase *= 10 } return (self / decimalBase) % 10 } } print("271828[0] is \(271828[0])") print("271828[3] is \(271828[3])") print("271828[5] is \(271828[15])") // 21.6 Nested Types // add new nested types extension Int { enum Kind { case negative, zero, positive } var kind: Kind { switch self { case 0: return .zero case let x where x > 0: return .positive default: return .negative } } } func printIntegerKinds(_ numbers: [Int]) { for number in numbers { switch number.kind { case .negative: print("- ", terminator: "") case .zero: print("0 ", terminator: "") case .positive: print("+ ", terminator: "") } } } let intArray = [3, 12, -10, 0, -19] printIntegerKinds(intArray) // number.kind is already known to be of type Int.Kind. Because of this, all of the Int.Kind case values can be written in shorthand form inside the switch statement, such as .negative rather than Int.Kind.negative. // 22. Protocols // A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. // The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to CONFORM to that protocol. // extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of // 22.1 Protocol Syntax // protocol SomeProtocol { // protocol definition goes here // } // Custom types 实现协议 // struct SomeStructure: FirstProtocol, AnotherProtocol { // structure definition goes here // } // 对于有父类的类 // class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definition goes here // } // 22.2 Property Requirements // 可以要求任意类型提供 instance property 实例属性 或者 type property 类属性 不指定该属性是 stored property 还是 computed property 只要求类型和名字 // 还可以指定属性是 只读的 还是 可读写的 // 如果要求是 可读写的, 就无法使用 constant stored property 或 a read-only computed property // 如果只要求 可读, 就可以使用任意类型 (同时这些属性自己可以是 可读写的) // property requirements 常用 variable properties 声明 var // Gettable 和 settable 使用 {get set} 和 { get } // protocol SomeProtocol { // var mustSettable: Int { get set } // var doesNotNeedToBeSettable: Int { get } // } // 限制类属性统一用 static 实现可以用 class 或 static // You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation 可以被子类复写的计算属性用 class 关键字 // protocol SomeProtocol { // static var someTypeProperty: Int { get set } // } protocol FullyNamed { var fullName: String { get } } // any FullyNamed type must have a gettable instance property called fullName, which is of type String. struct Person: FullyNamed { var fullName: String } let johnInfo = Person(fullName: "John Carmack") print(johnInfo) class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return (prefix != nil ? prefix! + " " : "") + name } } var cc = Starship(name: "Peace", prefix: "Mars") print(cc.fullName) // 22.3 Method Requirements // Protocols can require specific instance methods and type methods to be implemented by conforming types // 方法作为协议定义的一部分 和正常的实例或类方法定义一致,但是没有大括号和方法体。可以有可变参数,但没有默认参数 // 在协议中对类方法进行限定需要添加 static。 // protocol SomeProtocol { // static func someTypeMethod() // 类方法 // } protocol RandomNumberGenerator { func random() -> Double } // a pseudorandom number generator algorithm known as a linear congruential generator class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m)) return lastRandom / m } } let generator = LinearCongruentialGenerator() print("Here's a random number: \(generator.random())") print("Another one random number: \(generator.random())") // 22.4 Mutating Method Requirements // 有些修改值类型(structures enumerations)的内部方法 要在协议条件中的方法前加 mutating 在structures enumerations里要加 mutating 不用在实现协议的class内部写这个关键字 protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case off, on mutating func toggle() { switch self { case .off: self = .on case .on: self = .off } } } var lightSwitch = OnOffSwitch.off lightSwitch.toggle() print(lightSwitch) lightSwitch.toggle() print(lightSwitch) // 22.5 Initializer Requirements // 协议可以规定一些类型方法必须实现特定初始化方法 协议条件的初始化方法和正常初始化方法一样,只是没有大括号和方法体。 protocol SomeProtocol { init(someParameter: Int) } // 22.5.1 Class Implementations of Protocol Initializer Requirements // Rule 1 // A designated initializer must call a designated initializer from its immediate superclass. // Rule 2 // A convenience initializer must call another initializer from the same class. // Rule 3 // A convenience initializer must ultimately call a designated initializer. // A simple way to remember this is: // Designated initializers must always delegate up. // Convenience initializers must always delegate across. // 协议中的初始化方法可以用 designated 或 convenience 初始化方法。但都要在实现中在初始化方法前加关键字 required // 当然 final 修饰的初始化方法不用加 required // 如果子类 override 父类初始化方法并要实现协议的初始化方法, 要在初始化方法前加 required override // class SomeSubClass: SomeSuperClass, SomeProtocol { // // "required" from SomeProtocol conformance; "override" from SomeSuperClass // required override init() { // // initializer implementation goes here // } // } // 22.5.2 Failable Initializer Requirements // A failable initializer requirement can be satisfied by a failable or nonfailable initializer on a conforming type. A nonfailable initializer requirement can be satisfied by a nonfailable initializer or an implicitly unwrapped failable initializer. // 22.6 Protocols as Types // 可以将协议用在 类型 可以使用的地方 // 作为参数类型 或 函数/方法返回类型 // 作为 constant variable property 的类型 // 作为数组字典和其他容器的元素类型 class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { print("Random dice roll is \(d6.roll())") } // 22.7 Delegation // 设计模式 使得一个类或结构可以将一些对其他类型的响应 hand off / delegate。 // 通过定义一个封装delegated响应的协议完成 // 可用于响应特殊行动, 从外部接受数据不用知道数据源内部类型 protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(_ game: DiceGame) func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) func gameDidEnd(_ game: DiceGame) } // a version of the Snakes and Ladders game originally introduced in Control Flow class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = Array(repeating: 0, count: finalSquare + 1) board[03] = +08 board[06] = +11 board[09] = +09 board[10] = +02 board[14] = -10 board[19] = -11 board[22] = -02 board[24] = -08 } var delegate: DiceGameDelegate? func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } // play() 调用一个 optional chain 在 delegate 上调用一个方法,如果 delegate 是 nil 那么这个 delegate 会默默失败而不报错 如果不是 nil 就执行 gameLoop 并将 实例 self 作为参数传入 于是我们需要一个 adopt DiceGameDelegate 的 class 如下 class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(_ game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { print("Started a new game of Snakes and Ladders") } print("The game is using a \(game.dice.sides)-sides dice") } func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { numberOfTurns += 1 print("Rolled a \(diceRoll)") } func gameDidEnd(_ game: DiceGame) { print("The game lasted for \(numberOfTurns) turns") } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // 22.8 Adding Protocol Conformance with an Extension // 可以扩展已有类型使其遵守某个协议, 甚至你无法访问源代码也可以做到。 Extension 可以添加 新 properties , method, 和 subscripts // 给类型添加这些扩展会立即作用于类型实例上 // TextRepresentable 给任意类型添加显示文本功能 protocol TextRepresentable { var textualDescription: String { get } } // 给 Dice class 添加这个功能 extension Dice: TextRepresentable { var textualDescription: String { return "A \(sides)-sided dice" } } let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) print(d12.textualDescription) // 给 SnakesAndLadders 添加显示功能 extension SnakesAndLadders: TextRepresentable { var textualDescription: String { return "A game of Snakes and Ladders with \(finalSquare) squares" } } print(game.textualDescription) // 22.8.1 Declaring Protocol Adoption with an Extension // 1. 类型已经实现了一个协议的所有要求 2. 还没有声明其实现了哪个协议 -> 你可以用一个空 extension 来声明这一点 struct Hamster { var name: String var textualDescription: String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} // 声明实现了哪个协议 // Types do not automatically adopt a protocol just by satisfying its requirements. They must always explicitly declare their adoption of the protocol. 仅实现要求不够,还要声明自己实现了哪个协议的要求 let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster print(somethingTextRepresentable.textualDescription) // 22.9 Collections of Protocol Types // 作为元素的 protocol 类型 let things : [TextRepresentable] = [game, d12, simonTheHamster] for thing in things { print(thing.textualDescription) } // 注意 thing 的类型是 TextRepresentable 不是 Dice DiceGame 或 Hamster // 22.10 Protocol Inheritance // 协议可以继承一个或多个其他协议 语法类似 类继承 // protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // } protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } // 实现 PrettyTextRepresentable 要求的类型必须同时满足 TextRepresentable 的要求 extension SnakesAndLadders: PrettyTextRepresentable { var prettyTextualDescription: String { var output = textualDescription + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } // 22.11 Class-Only Protocols // 限制只能由 class 实现本协议 // protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol { // } // structure enumeration 来实现会导致 compile-time error 在要求实现类型为 引用类型时使用这个语法 // 22.12 Protocol Composition // 可以要求一个类型实现多个协议 多个协议组成的类型写成 SomeProtocol & AnotherProtocol & ThirdProtocol & ... // 实现多个协议写为 SomeProtocol, AnotherProtocol, ThirdProtocol... protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person1: Named, Aged { var name: String var age: Int } func wishHappyBirthday(to celebrator: Named & Aged) { print("Happy Birthday, \(celebrator.name), you're \(celebrator.age)!") } let birthdayPerson = Person1(name: "Jim", age: 22) wishHappyBirthday(to: birthdayPerson) // 22.12 Checking for Protocol Conformance // check for protocol conformance 用 is 操作符 // cast 到一个类型 用 as 操作符 as? 如果转失败就返回 nil as! 假定不出错,如果出错就 runtime error protocol HasArea { var area: Double { get } } class Circle: HasArea { let pi = 3.1415927 var radius: Double var area: Double { return pi * radius * radius } // 用计算属性初始化 init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double // 用存储属性初始化 init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } // Circle Conuntry Animal 没有共享的基类 但都是 class 可以用 AnyObject 标识 let objects: [AnyObject] = [ Circle(radius: 2.0), Country(area: 243_610), Animal(legs: 8) ] for object in objects { if let objectWithArea = object as? HasArea { print("Area is \(objectWithArea.area)") } else { print("Something that doesn't have an area") } } // Whenever an object in the array conforms to the HasArea protocol, the optional value returned by the as? operator is unwrapped with optional binding into a constant called objectWithArea (unwrapped 动作如何完成的?) // 22.13 Optional Protocol Requirements // 可以在协议里定义 可选要求 即部分要求可以不实现 这些要求要用 optional 做修饰符 // the protocol and the optional requirement must MUST be marked with the @objc attribute // @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes. 只能由继承自 Objective-C 类的类实现或其他 @objc 类实现。 // 使用一个 optional 协议 它的 optional 方法或属性会自动变为 optional 的。 整个方法变为 optional 而不是返回值变为 optional // 在方法后加 ? 可以检测一个类型实现了一个协议的 optional 要求 someOptionalMethod?(someArgument) // Need import Foundation ... // @objc protocol CounterDataSource { // @objc optional func increment(forCount count: Int) -> Int // @objc optional var fixedIncrement: Int { get } // } /* class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { // dataSource? 保证 dataSource 不为 nil 才调用 increment? // increment? 保证 dataSource 中有 increment 才调用 increment? => 返回 一个 optional 值 (不管实际返回什么类型) // let -> optional binding if let amount = dataSource?.increment?(forCount: count) { count += amount } else if let amount = dataSource?.fixedIncrement { // dataSource?.fixedIncrement 也是 optional 类型 count += amount } } } */ /* class ThreeSource: NSObject, CounterDataSource { let fixedIncrement = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() print(counter.count) } @objc class TowardsZeroSource: NSObject, CounterDataSource { func increment(forCount count: Int) -> Int { if count == 0{ return 0 } else if count < 0 { return 1 } else { return -1 } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() print(counter.count) } } */ // Optional requirements are available so that you can write code that interoperates with Objective-C. // 22.14 Protocol Extensions // 协议可以被扩展来给遵守协议的类型添加method property 这允许你在协议里定义行为 extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } } let generator1 = LinearCongruentialGenerator() print("Here's a random number: \(generator1.random())") print("And here's a random Boolean: \(generator1.randomBool())") // 22.14.1 Providing Default Implementations // 可以用扩展来给协议添加默认的条件(方法 或 计算属性)实现 // Although conforming types don’t have to provide their own implementation of either, requirements with default implementations can be called without optional chaining. extension PrettyTextRepresentable { var prettyTextualDescription: String { return textualDescription } } // 22.14.2 Adding Constraints to Protocol Extensions // 在实现协议的类型调用扩展方法或属性前可以对这些类型进行限定 extension Collection where Iterator.Element: TextRepresentable { var textualDescription: String { let itemAsText = self.map { $0.textualDescription } return "[" + itemAsText.joined(separator: ", ") + "]" } } let m1TheHamster = Hamster(name: "m1") let m2TheHamster = Hamster(name: "m2") let m3TheHamster = Hamster(name: "m3") let myHamsters = [m1TheHamster, m2TheHamster, m3TheHamster] print(myHamsters.textualDescription) // 多个限制条件选最严格的那个。。。
bsd-2-clause
c627699648177dd8784418b7422de13b
27.272506
250
0.687637
3.962995
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/VoidType.swift
1
799
#if SWIFT_PACKAGE import cllvm #endif /// The `Void` type represents any value and has no size. public struct VoidType: IRType { /// Returns the context associated with this type. public let context: Context /// Creates an instance of the `Void` type. /// /// - parameter context: The context to create this type in /// - SeeAlso: http://llvm.org/docs/ProgrammersManual.html#achieving-isolation-with-llvmcontext public init(in context: Context = Context.global) { self.context = context } /// Retrieves the underlying LLVM type object. public func asLLVM() -> LLVMTypeRef { return LLVMVoidTypeInContext(context.llvm) } } extension VoidType: Equatable { public static func == (lhs: VoidType, rhs: VoidType) -> Bool { return lhs.asLLVM() == rhs.asLLVM() } }
mit
0cabc4cfe496e1a88be9d907eb3b5cde
26.551724
97
0.699625
3.878641
false
false
false
false
bradwoo8621/Swift-Study
Instagram/Instagram/FollowerCell.swift
1
2063
// // FollowerCell.swift // Instagram // // Created by brad.wu on 2017/4/17. // Copyright © 2017年 bradwoo8621. All rights reserved. // import UIKit import AVOSCloud class FollowerCell: UITableViewCell { @IBOutlet weak var avaImg: UIImageView! @IBOutlet weak var usernameLbl: UILabel! @IBOutlet weak var followBtn: UIButton! var user:AVUser! override func awakeFromNib() { super.awakeFromNib() // Initialization code avaImg.layer.cornerRadius = avaImg.frame.width / 2 avaImg.clipsToBounds = true let width = UIScreen.main.bounds.width avaImg.frame = CGRect(x: 10, y: 10, width: width / 5.3, height: width / 5.3) usernameLbl.frame = CGRect(x: avaImg.frame.width + 20, y: 30, width: width / 3.2, height: 30) followBtn.frame = CGRect(x: width - width / 3.5 - 20, y: 30, width: width / 3.5, height: 30) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func followBtnClicked(_ sender: UIButton) { let title = followBtn.title(for: .normal) if title == "关注" { guard user != nil else {return} AVUser.current()?.follow(user.objectId!, andCallback: { (success: Bool, error: Error?) in if success { self.followBtn.setTitle("已关注", for: .normal) self.followBtn.backgroundColor = .green } else { print(error?.localizedDescription as Any) } }) } else { guard user != nil else {return} AVUser.current()?.unfollow(user.objectId!, andCallback: {(success: Bool, error: Error?) in if success { self.followBtn.setTitle("关注", for: .normal) self.followBtn.backgroundColor = .lightGray } else { print(error?.localizedDescription as Any) } }) } } }
mit
96a8eedd8bbe74855dc473c3e8834882
28.228571
93
0.585533
3.795918
false
false
false
false
augmify/ModelRocket
ModelRocket/Property.swift
6
4022
// Property.swift // // Copyright (c) 2015 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation final public class Property<T : JSONTransformable>: PropertyDescription { typealias PropertyType = T /// Backing store for property data public var value: PropertyType? /// Post-processing closure. public var postProcess: ((PropertyType?) -> Void)? /// JSON parameter key public var key: String /// Type information public var type: String { return "\(PropertyType.self)" } /// Specify whether value is required public var required = false public subscript() -> PropertyType? { return value } // MARK: Initialization /// Initialize with JSON property key public init(key: String, defaultValue: PropertyType? = nil, required: Bool = false, postProcess: ((PropertyType?) -> Void)? = nil) { self.key = key self.value = defaultValue self.required = required self.postProcess = postProcess } // MARK: Transform /// Extract object from JSON and return whether or not the value was extracted public func fromJSON(json: JSON) -> Bool { var jsonValue = json let keyPaths = key.componentsSeparatedByString(".") for key in keyPaths { jsonValue = jsonValue[key] } if let newValue = PropertyType.fromJSON(jsonValue) as? PropertyType { value = newValue } return (value != nil) } /// Convert object to JSON public func toJSON() -> AnyObject? { return value?.toJSON() } /// Perform initialization post-processing public func initPostProcess() { postProcess?(value) } // MARK: Coding /// Encode public func encode(coder: NSCoder) { if let object: AnyObject = value as? AnyObject { coder.encodeObject(object, forKey: key) } } public func decode(decoder: NSCoder) { if let decodedValue = decoder.decodeObjectForKey(key) as? PropertyType { value = decodedValue } } } // MARK:- Printable extension Property: Printable { public var description: String { var string = "Property<\(type)> (key: \(key), value: " if let value = value { string += "\(value)" } else { string += "nil" } string += ", required: \(required))" return string } } // MARK:- DebugPrintable extension Property: DebugPrintable { public var debugDescription: String { return description } } // MARK:- Hashable extension Property: Hashable { public var hashValue: Int { return key.hashValue } } // MARK:- Equatable extension Property: Equatable {} public func ==<T>(lhs: Property<T>, rhs: Property<T>) -> Bool { return lhs.key == rhs.key }
mit
dd39d849231d711b96c99e3f03957f42
27.125874
136
0.63277
4.851628
false
false
false
false
qbalsdon/br.cd
brcd/brcd/Model/CoreDataStackManager.swift
1
2715
// // CoreDataStackManager.swift // brcd // // Created by Quintin Balsdon on 2016/01/17. // Copyright © 2016 Balsdon. All rights reserved. // import Foundation import CoreData private let SQLITE_FILE_NAME = "brcd.sqlite" class CoreDataStackManager { // MARK: - Shared Instance static let sharedInstance = CoreDataStackManager() // MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate. lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("brcd", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME) var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "br.cd", code: 9999, userInfo: dict) print("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
917dce4612ae194725a0be98aacae167
35.689189
130
0.657332
5.874459
false
false
false
false
farshidce/RKMultiUnitRuler
Example/RKMultiUnitRuler/ViewController.swift
1
6585
// // ViewController.swift // RKMultiUnitRulerDemo // // Created by Farshid Ghods on 12/29/16. // Copyright © 2016 Rekovery. All rights reserved. // import UIKit import RKMultiUnitRuler class ViewController: UIViewController, RKMultiUnitRulerDataSource, RKMultiUnitRulerDelegate { @IBOutlet weak var ruler: RKMultiUnitRuler? @IBOutlet weak var controlHConstraint: NSLayoutConstraint? @IBOutlet weak var colorSwitch: UISwitch? var backgroundColor: UIColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) @IBOutlet weak var directionSwitch: UISwitch? @IBOutlet weak var moreMarkersSwitch: UISwitch? var rangeStart = Measurement(value: 30.0, unit: UnitMass.kilograms) var rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) var colorOverridesEnabled = false var moreMarkers = false var direction: RKLayerDirection = .horizontal var segments = Array<RKSegmentUnit>() override func viewDidLoad() { super.viewDidLoad() self.colorSwitch?.addTarget(self, action: #selector(ViewController.colorSwitchValueChanged(sender:)), for: .valueChanged) self.directionSwitch?.addTarget(self, action: #selector(ViewController.directionSwitchValueChanged(sender:)), for: .valueChanged) self.moreMarkersSwitch?.addTarget(self, action: #selector(ViewController.moreMarkersSwitchValueChanged(sender:)), for: .valueChanged) ruler?.direction = direction ruler?.tintColor = UIColor(red: 0.15, green: 0.18, blue: 0.48, alpha: 1.0) controlHConstraint?.constant = 200.0 segments = self.createSegments() ruler?.delegate = self ruler?.dataSource = self let initialValue = (self.rangeForUnit(UnitMass.kilograms).location + self.rangeForUnit(UnitMass.kilograms).length) / 2 ruler?.measurement = NSMeasurement( doubleValue: Double(initialValue), unit: UnitMass.kilograms) self.view.layoutSubviews() // Do any additional setup after loading the view, typically from a nib. } private func createSegments() -> Array<RKSegmentUnit> { let formatter = MeasurementFormatter() formatter.unitStyle = .medium formatter.unitOptions = .providedUnit let kgSegment = RKSegmentUnit(name: "Kilograms", unit: UnitMass.kilograms, formatter: formatter) kgSegment.name = "Kilogram" kgSegment.unit = UnitMass.kilograms let kgMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 5.0) kgMarkerTypeMax.labelVisible = true kgSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 0.5), RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 1.0)] let lbsSegment = RKSegmentUnit(name: "Pounds", unit: UnitMass.pounds, formatter: formatter) let lbsMarkerTypeMax = RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 50.0), scale: 10.0) lbsSegment.markerTypes = [ RKRangeMarkerType(color: UIColor.white, size: CGSize(width: 1.0, height: 35.0), scale: 1.0)] if moreMarkers { kgSegment.markerTypes.append(kgMarkerTypeMax) lbsSegment.markerTypes.append(lbsMarkerTypeMax) } kgSegment.markerTypes.last?.labelVisible = true lbsSegment.markerTypes.last?.labelVisible = true return [kgSegment, lbsSegment] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func unitForSegmentAtIndex(index: Int) -> RKSegmentUnit { return segments[index] } var numberOfSegments: Int { get { return segments.count } set { } } func rangeForUnit(_ unit: Dimension) -> RKRange<Float> { let locationConverted = rangeStart.converted(to: unit as! UnitMass) let lengthConverted = rangeLength.converted(to: unit as! UnitMass) return RKRange<Float>(location: ceilf(Float(locationConverted.value)), length: ceilf(Float(lengthConverted.value))) } func styleForUnit(_ unit: Dimension) -> RKSegmentUnitControlStyle { let style: RKSegmentUnitControlStyle = RKSegmentUnitControlStyle() style.scrollViewBackgroundColor = UIColor(red: 0.22, green: 0.74, blue: 0.86, alpha: 1.0) let range = self.rangeForUnit(unit) if unit == UnitMass.pounds { style.textFieldBackgroundColor = UIColor.clear // color override location:location+40% red , location+60%:location.100% green } else { style.textFieldBackgroundColor = UIColor.red } if (colorOverridesEnabled) { style.colorOverrides = [ RKRange<Float>(location: range.location, length: 0.1 * (range.length)): UIColor.red, RKRange<Float>(location: range.location + 0.4 * (range.length), length: 0.2 * (range.length)): UIColor.green] } style.textFieldBackgroundColor = UIColor.clear style.textFieldTextColor = UIColor.white return style } func valueChanged(measurement: NSMeasurement) { print("value changed to \(measurement.doubleValue)") } func colorSwitchValueChanged(sender: UISwitch) { colorOverridesEnabled = sender.isOn ruler?.refresh() } func directionSwitchValueChanged(sender: UISwitch) { if sender.isOn { direction = .vertical controlHConstraint?.constant = 400 } else { direction = .horizontal controlHConstraint?.constant = 200 } ruler?.direction = direction ruler?.refresh() self.view.layoutSubviews() } func moreMarkersSwitchValueChanged(sender: UISwitch) { moreMarkers = sender.isOn if moreMarkers { self.rangeLength = Measurement(value: Double(90), unit: UnitMass.kilograms) } else { self.rangeLength = Measurement(value: Double(130), unit: UnitMass.kilograms) } segments = self.createSegments() ruler?.refresh() self.view.layoutSubviews() } }
mit
3cffe4cb363489e54438428b7649337d
38.90303
126
0.638366
4.719713
false
false
false
false
theodinspire/FingerBlade
FingerBlade/MenuTableViewController.swift
1
4226
// // MenuTableViewController.swift // FingerBlade // // Created by Cormack on 3/8/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import UIKit class MenuTableViewController: UITableViewController { @IBOutlet weak var handednessLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) handednessLabel.text = UserDefaults.standard.string(forKey: HAND) ?? "None" emailLabel.text = UserDefaults.standard.string(forKey: EMAIL) ?? "None" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } */ /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if var destination = segue.destination as? OptionViewController { destination.fromMenu = true } } /// For use in unwinding from sample cutting screen /// /// - Parameter segue: Segue of return @IBAction func unwindToMenu(segue: UIStoryboardSegue) { } /// Function for clearing defaults, debug only /// /// - Parameter sender: Object that sends the clear request @IBAction func clearDefaults(_ sender: Any) { UserDefaults.standard.removeObject(forKey: HAND) UserDefaults.standard.removeObject(forKey: EMAIL) UserDefaults.standard.removeObject(forKey: STORE) UserDefaults.standard.removeObject(forKey: COMPLETE) } }
gpl-3.0
9ef87c8b7ada0e930ec7e6d5b8591dec
33.349593
136
0.668402
5.23544
false
false
false
false
adilbenmoussa/ABCircularProgressView
ABCircularProgressView/ABCircularProgressView.swift
1
5975
// // ABCircularProgressView.swift // Simple UIView for showing a circular progress view and the stop button when the pregress is stopped. // // Created by Adil Ben Moussa on 11/9/15. // // import UIKit class ABCircularProgressView: UIView { /** * The color of the progress view and the stop icon */ let tintCGColor: CGColor = UIColor.blueColor().CGColor /** * Size ratio of the stop button related to the progress view * @default 1/3 of the progress view */ let stopSizeRatio: CGFloat = 0.3 /** * The Opacity of the progress background layer */ let progressBackgroundOpacity: Float = 0.1 /** * The width of the line used to draw the progress view. */ let lineWidth: CGFloat = 1.0 //define the shape layers private let progressBackgroundLayer = CAShapeLayer() private let circlePathLayer = CAShapeLayer() private let iconLayer = CAShapeLayer() private var _isSpinning = false var progress: CGFloat { get { return circlePathLayer.strokeEnd } set { if (newValue > 1) { circlePathLayer.strokeEnd = 1 } else if (newValue <= 0) { circlePathLayer.strokeEnd = 0 clearStopIcon() } else { circlePathLayer.strokeEnd = newValue stopSpinning() drawStopIcon() } } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } private func setup() { progress = 0 progressBackgroundLayer.frame = bounds progressBackgroundLayer.strokeColor = tintCGColor progressBackgroundLayer.fillColor = nil progressBackgroundLayer.lineCap = kCALineCapRound progressBackgroundLayer.lineWidth = lineWidth progressBackgroundLayer.opacity = progressBackgroundOpacity layer.addSublayer(progressBackgroundLayer) circlePathLayer.frame = bounds circlePathLayer.lineWidth = lineWidth circlePathLayer.fillColor = UIColor.clearColor().CGColor circlePathLayer.strokeColor = tintCGColor layer.addSublayer(circlePathLayer) iconLayer.frame = bounds iconLayer.lineWidth = lineWidth iconLayer.lineCap = kCALineCapButt iconLayer.fillColor = nil layer.addSublayer(iconLayer) backgroundColor = UIColor.whiteColor() } private func circlePath() -> UIBezierPath { let circleRadius = (self.bounds.size.width - lineWidth)/2 var cgRect = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius) cgRect.origin.x = CGRectGetMidX(circlePathLayer.bounds) - CGRectGetMidX(cgRect) cgRect.origin.y = CGRectGetMidY(circlePathLayer.bounds) - CGRectGetMidY(cgRect) return UIBezierPath(ovalInRect: cgRect) } private func stopPath() -> UIBezierPath { let radius = bounds.size.width/2 let sideSize = bounds.size.width * stopSizeRatio let stopPath : UIBezierPath = UIBezierPath() stopPath.moveToPoint(CGPointMake(0, 0)) stopPath.addLineToPoint(CGPointMake(sideSize, 0.0)) stopPath.addLineToPoint(CGPointMake(sideSize, sideSize)) stopPath.addLineToPoint(CGPointMake(0.0, sideSize)) stopPath.closePath() stopPath.applyTransform(CGAffineTransformMakeTranslation((radius * (1-stopSizeRatio)), (radius * (1-stopSizeRatio)))) return stopPath; } private func drawStopIcon() { iconLayer.fillColor = tintCGColor iconLayer.path = stopPath().CGPath } private func clearStopIcon() { iconLayer.fillColor = nil iconLayer.path = nil } private func backgroundCirclePath(partial: Bool=false) -> UIBezierPath{ let startAngle: CGFloat = -(CGFloat)(M_PI / 2); // 90 degrees var endAngle: CGFloat = CGFloat(2 * M_PI) + startAngle let center: CGPoint = CGPointMake(bounds.size.width/2, bounds.size.height/2) let radius: CGFloat = (bounds.size.width - lineWidth)/2 // Draw background let processBackgroundPath: UIBezierPath = UIBezierPath() processBackgroundPath.lineWidth = lineWidth processBackgroundPath.lineCapStyle = CGLineCap.Round if (partial) { endAngle = (1.8 * CGFloat(M_PI)) + startAngle; progressBackgroundLayer.opacity = progressBackgroundOpacity + 0.1 } else{ progressBackgroundLayer.opacity = progressBackgroundOpacity } processBackgroundPath.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) return processBackgroundPath } override func layoutSubviews() { super.layoutSubviews() progressBackgroundLayer.path = backgroundCirclePath().CGPath circlePathLayer.path = circlePath().CGPath } func startSpinning() { _isSpinning = true progressBackgroundLayer.path = backgroundCirclePath(true).CGPath let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.toValue = M_PI * 2.0 rotationAnimation.duration = 1 rotationAnimation.cumulative = true rotationAnimation.repeatCount = Float.infinity; progressBackgroundLayer.addAnimation(rotationAnimation, forKey: "rotationAnimation") } func stopSpinning(){ progressBackgroundLayer.path = backgroundCirclePath(false).CGPath progressBackgroundLayer.removeAllAnimations() _isSpinning = false } func isSpinning()->Bool { return _isSpinning } }
mit
70444579fefaf34d780c11d3e72d7178
32.567416
131
0.638661
5.392599
false
false
false
false
GalinaCode/Nutriction-Cal
NutritionCal/Nutrition Cal/HealthStore.swift
1
9976
// // HealthStore.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // import Foundation import HealthKit class HealthStore { class func sharedInstance() -> HealthStore { struct Singleton { static let instance = HealthStore() } return Singleton.instance } let healthStore: HKHealthStore? = HKHealthStore() func addNDBItemToHealthStore(item: NDBItem,selectedMeasure: NDBMeasure , qty: Int, completionHandler: (success: Bool, errorString: String?) -> Void) { let timeFoodWasEntered = NSDate() let foodMetaData = [ HKMetadataKeyFoodType : item.name, "Group": item.group!, "USDA id": item.ndbNo, "Quantity": "\(qty) \(selectedMeasure.label!)", ] func getCalcium() -> HKQuantitySample? { // check if calcium nutrient available if let calcium = item.nutrients?.find({$0.id == 301}) { // check if selected measure available if let measure = calcium.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let calciumSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return calciumSample } return nil } return nil } func getCarbohydrate() -> HKQuantitySample? { // check if carbohydrate nutrient available if let carbohydrate = item.nutrients?.find({$0.id == 205}) { // check if selected measure available if let measure = carbohydrate.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let carbohydrateSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return carbohydrateSample } return nil } return nil } func getCholesterol() -> HKQuantitySample? { // check if cholesterol nutrient available if let cholesterol = item.nutrients?.find({$0.id == 601}) { // check if selected measure available if let measure = cholesterol.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let cholesterolSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return cholesterolSample } return nil } return nil } func getEnergy() -> HKQuantitySample? { // check if energy nutrient available if let energy = item.nutrients?.find({$0.id == 208}) { // check if selected measure available if let measure = energy.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: value) let energySample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return energySample } return nil } return nil } func getFatTotal() -> HKQuantitySample? { // check if fatTotal nutrient available if let fatTotal = item.nutrients?.find({$0.id == 204}) { // check if selected measure available if let measure = fatTotal.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let fatTotalSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return fatTotalSample } return nil } return nil } func getProtein() -> HKQuantitySample? { // check if protein nutrient available if let protein = item.nutrients?.find({$0.id == 203}) { // check if selected measure available if let measure = protein.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let proteinSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return proteinSample } return nil } return nil } func getSugar() -> HKQuantitySample? { // check if sugar nutrient available if let sugar = item.nutrients?.find({$0.id == 269}) { // check if selected measure available if let measure = sugar.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnit(), doubleValue: value) let sugarSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return sugarSample } return nil } return nil } func getVitaminC() -> HKQuantitySample? { // check if vitamin C nutrient available if let vitaminC = item.nutrients?.find({$0.id == 401}) { // check if selected measure available if let measure = vitaminC.measures?.find({$0.label == selectedMeasure.label}) { let value: Double = Double(qty) * (measure.value as! Double) let unit = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Milli), doubleValue: value) let vitaminCSample = HKQuantitySample(type: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC)!, quantity: unit, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, metadata: foodMetaData) return vitaminCSample } return nil } return nil } if HKHealthStore.isHealthDataAvailable() { var nutrientsArray: [HKQuantitySample] = [] if let calcium = getCalcium() { nutrientsArray.append(calcium) } if let carbohydrates = getCarbohydrate() { nutrientsArray.append(carbohydrates) } if let cholesterol = getCholesterol() { nutrientsArray.append(cholesterol) } if let energy = getEnergy() { nutrientsArray.append(energy) } if let fatTotal = getFatTotal() { nutrientsArray.append(fatTotal) } if let protein = getProtein() { nutrientsArray.append(protein) } if let sugar = getSugar() { nutrientsArray.append(sugar) } if let vitaminC = getVitaminC() { nutrientsArray.append(vitaminC) } let foodDataSet = NSSet(array: nutrientsArray) let foodCoorelation = HKCorrelation(type: HKCorrelationType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)!, startDate: timeFoodWasEntered, endDate: timeFoodWasEntered, objects: foodDataSet as! Set<HKSample>, metadata : foodMetaData) healthStore?.saveObject(foodCoorelation, withCompletion: { (success, error) -> Void in if success { print("Item saved to Heath App successfully") completionHandler(success: true, errorString: nil) } else { print(error?.localizedDescription) if error!.code == 4 { completionHandler(success: false, errorString: "Access to Health App denied, You can allow access from Health App -> Sources -> NutritionDiary. or disable sync with Health App in settings tab.") } else { completionHandler(success: false, errorString: "\(error!.code)") } } }) } else { completionHandler(success: false, errorString: "Health App is not available, Device is not compatible.") } } func requestAuthorizationForHealthStore() { let dataTypesToWrite: [AnyObject] = [ HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC)! ] healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite) as? Set<HKSampleType>, readTypes: nil, completion: { (success, error) -> Void in if success { print("User completed authorization request.") } else { print("User canceled the request \(error!.localizedDescription)") } }) } }
apache-2.0
175569f073c889f1170bc75faee7afee
30.974359
251
0.698947
4.592541
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Models/Mapping/LoginServiceModelMapping.swift
1
4718
// // LoginServiceModelMapping.swift // Rocket.Chat // // Created by Matheus Cardoso on 10/17/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift extension LoginService: ModelMappeable { // swiftlint:disable cyclomatic_complexity func map(_ values: JSON, realm: Realm?) { if identifier == nil { identifier = values["_id"].string ?? values["id"].string } service = values["name"].string ?? values["service"].string clientId = values["appId"].string ?? values["clientId"].string custom = values["custom"].boolValue serverUrl = values["serverURL"].string tokenPath = values["tokenPath"].string authorizePath = values["authorizePath"].string scope = values["scope"].string buttonLabelText = values["buttonLabelText"].stringValue buttonLabelColor = values["buttonLabelColor"].stringValue tokenSentVia = values["tokenSentVia"].stringValue usernameField = values["usernameField"].stringValue mergeUsers = values["mergeUsers"].boolValue loginStyle = values["loginStyle"].string buttonColor = values["buttonColor"].string // CAS loginUrl = values["login_url"].string // SAML entryPoint = values["entryPoint"].string issuer = values["issuer"].string provider = values["clientConfig"]["provider"].string switch type { case .google: mapGoogle() case .facebook: mapFacebook() case .gitlab: mapGitLab() case .github: mapGitHub() case .linkedin: mapLinkedIn() case .wordpress: break // not mapped here since it needs a public setting for type case .saml: break case .cas: break case .custom: break case .invalid: break } } // swiftlint:enable cyclomatic_complexity func mapGoogle() { service = "google" scope = "email profile" serverUrl = "https://accounts.google.com" tokenPath = "/login/oauth/access_token" authorizePath = "/o/oauth2/v2/auth" buttonLabelText = "google" buttonLabelColor = "#ffffff" buttonColor = "#dd4b39" callbackPath = "google?close" } func mapGitHub() { service = "github" scope = "" serverUrl = "https://github.com" tokenPath = "/login/oauth/access_token" authorizePath = "/login/oauth/authorize" buttonLabelText = "github" buttonLabelColor = "#ffffff" buttonColor = "#4c4c4c" } func mapGitLab() { service = "gitlab" scope = "read_user" serverUrl = "https://gitlab.com" tokenPath = "/oauth/token" authorizePath = "/oauth/authorize" buttonLabelText = "gitlab" buttonLabelColor = "#ffffff" buttonColor = "#373d47" callbackPath = "gitlab?close" } func mapFacebook() { service = "facebook" scope = "" serverUrl = "https://facebook.com" scope = "email" tokenPath = "https://graph.facebook.com/oauth/v2/accessToken" authorizePath = "/v2.9/dialog/oauth" buttonLabelText = "facebook" buttonLabelColor = "#ffffff" buttonColor = "#325c99" callbackPath = "facebook?close" } func mapLinkedIn() { service = "linkedin" scope = "" serverUrl = "https://linkedin.com" tokenPath = "/oauth/v2/accessToken" authorizePath = "/oauth/v2/authorization" buttonLabelText = "linkedin" buttonLabelColor = "#ffffff" buttonColor = "#1b86bc" callbackPath = "linkedin?close" } func mapWordPress() { service = "wordpress" scope = scope ?? "auth" serverUrl = "https://public-api.wordpress.com" tokenPath = "/oauth2/token" authorizePath = "/oauth2/authorize" buttonLabelText = "wordpress" buttonLabelColor = "#ffffff" buttonColor = "#1e8cbe" callbackPath = "wordpress?close" } func mapWordPressCustom() { service = "wordpress" scope = scope ?? "openid" serverUrl = serverUrl ?? "https://public-api.wordpress.com" tokenPath = tokenPath ?? "/oauth/token" authorizePath = authorizePath ?? "/oauth/authorize" buttonLabelText = "wordpress" buttonLabelColor = "#ffffff" buttonColor = "#1e8cbe" callbackPath = "wordpress?close" } func mapCAS() { service = "cas" buttonLabelText = "CAS" buttonLabelColor = "#ffffff" buttonColor = "#13679a" } }
mit
85104d49ad7c0baa605a408bb1b8779c
27.762195
77
0.591902
4.665678
false
false
false
false