repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Jamol/Nutil
refs/heads/master
Sources/SSL/SslSocket.swift
mit
1
// // SslSocket.swift // Nutil // // Created by Jamol Bao on 11/4/16. // Copyright © 2016 Jamol Bao. All rights reserved. // import Foundation public enum SslFlag: UInt32 { case none = 0 case sslDefault = 0x01 case allowExpiredCert = 0x02 case allowInvalidCertCN = 0x04 case allowExpiredRoot = 0x08 case allowAnyRoot = 0x10 case allowRevokedCert = 0x20 case verifyHostName = 0x40 } public class SslSocket { fileprivate let sslHandler = SslHandler() fileprivate var tcpSocket: TcpSocket! fileprivate var alpnProtos: AlpnProtos? = nil fileprivate var serverName = "" fileprivate var hostName = "" fileprivate var sslFlags: UInt32 = 0 fileprivate var cbConnect: ErrorCallback? fileprivate var cbRead: EventCallback? fileprivate var cbWrite: EventCallback? fileprivate var cbClose: EventCallback? public init() { tcpSocket = TcpSocket() tcpSocket .onConnect(onConnect) .onRead(onRead) .onWrite(onWrite) .onClose(onClose) } public init (queue: DispatchQueue?) { tcpSocket = TcpSocket(queue: queue) tcpSocket .onConnect(onConnect) .onRead(onRead) .onWrite(onWrite) .onClose(onClose) } public func bind(_ addr: String, _ port: Int) -> KMError { return tcpSocket.bind(addr, port) } public func connect(_ addr: String, _ port: Int) -> KMError { if !isNumericHost(addr) { hostName = addr } return tcpSocket.connect(addr, port) } public func attachFd(_ fd: Int32) -> KMError { return tcpSocket.attachFd(fd) } public func close() { cleanup() } func cleanup() { sslHandler.close() tcpSocket.close() } } // read methods extension SslSocket { public func read<T>(_ data: UnsafeMutablePointer<T>, _ len: Int) -> Int { let ret = sslHandler.receive(data: data, len: len) if ret < 0 { cleanup() } return ret } } // write methods extension SslSocket { public func write(_ str: String) -> Int { return self.write(UnsafePointer<Int8>(str), str.utf8.count) } public func write<T>(_ data: [T]) -> Int { let wlen = data.count * MemoryLayout<T>.size return self.write(data, wlen) } public func write<T>(_ data: UnsafePointer<T>, _ len: Int) -> Int { let ret = sslHandler.send(data: data, len: len) if ret < 0 { cleanup() } return ret } public func writev(_ iovs: [iovec]) -> Int { let ret = sslHandler.send(iovs: iovs) if ret < 0 { cleanup() } return ret } } extension SslSocket { func onConnect(err: KMError) { var err = err if err == .noError { err = startSslHandshake(.client) if err == .noError && sslHandler.getState() == .handshake { return // continue to SSL handshake } } else { cleanup() } cbConnect?(err) } func onRead() { if sslHandler.getState() == .handshake { _ = checkSslState() } else { cbRead?() } } func onWrite() { if sslHandler.getState() == .handshake { _ = checkSslState() } else { cbWrite?() } } func onClose() { cleanup() cbClose?() } func checkSslState() -> Bool { if sslHandler.getState() == .handshake { let ssl_state = sslHandler.doSslHandshake() if ssl_state == .error { cbConnect?(.sslError) return false } else if ssl_state == .handshake { return false } else { cbConnect?(.noError) } } return true } } extension SslSocket { func setSslFlags(_ flags: UInt32) { sslFlags = flags } func getSslFlags() -> UInt32 { return sslFlags } func sslEnabled() -> Bool { return sslFlags != SslFlag.none.rawValue } func setAlpnProtocols(_ alpn: AlpnProtos) { alpnProtos = alpn } func getAlpnSelected() -> String? { return sslHandler.getAlpnSelected() } func setSslServerName(_ name: String) { self.serverName = name } } extension SslSocket { func startSslHandshake(_ role: SslRole) -> KMError { infoTrace("startSslHandshake, role=\(role), fd=\(tcpSocket.fd), state=\(tcpSocket.state)") sslHandler.close() do { try sslHandler.attachFd(fd: tcpSocket.fd, role: role) } catch NUError.ssl(let code) { errTrace("startSslHandshake, SSL error, code=\(code)") return .sslError } catch { errTrace("startSslHandshake, failed") return .sockError } if (role == .client) { if let alpn = alpnProtos { if !sslHandler.setAlpnProtocols(alpn: alpn) { warnTrace("startSslHandshake, failed to set alpn: \(alpn)") } } if !serverName.isEmpty { _ = sslHandler.setServerName(name: serverName) } else if !hostName.isEmpty { _ = sslHandler.setServerName(name: hostName) } if !hostName.isEmpty && (sslFlags & SslFlag.verifyHostName.rawValue) != 0 { _ = sslHandler.setHostName(name: hostName) } } let ssl_state = sslHandler.doSslHandshake() if(ssl_state == .error) { return .sslError } return .noError } } extension SslSocket { func sync(_ block: (() -> Void)) { tcpSocket.sync(block) } func async(_ block: @escaping (() -> Void)) { tcpSocket.async(block) } } extension SslSocket { @discardableResult public func onConnect(_ cb: @escaping (KMError) -> Void) -> Self { cbConnect = cb return self } @discardableResult public func onRead(_ cb: @escaping () -> Void) -> Self { cbRead = cb return self } @discardableResult public func onWrite(_ cb: @escaping () -> Void) -> Self { cbWrite = cb return self } @discardableResult public func onClose(_ cb: @escaping () -> Void) -> Self { cbClose = cb return self } }
1fdfdd886bac6407502ff019cf5002ad
24.728682
98
0.534498
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
test/SILGen/unmanaged.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-sil %s | FileCheck %s class C {} struct Holder { unowned(unsafe) var value: C } _ = Holder(value: C()) // CHECK-LABEL:sil hidden @_TFV9unmanaged6HolderC{{.*}} : $@convention(thin) (@owned C, @thin Holder.Type) -> Holder // CHECK: bb0([[T0:%.*]] : $C, // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C // CHECK-NEXT: strong_release [[T0]] : $C // CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C) // CHECK-NEXT: return [[T2]] : $Holder func set(inout holder holder: Holder) { holder.value = C() } // CHECK-LABEL:sil hidden @_TF9unmanaged3setFT6holderRVS_6Holder_T_ : $@convention(thin) (@inout Holder) -> () // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK: [[T0:%.*]] = function_ref @_TFC9unmanaged1CC{{.*}} // CHECK: [[C:%.*]] = apply [[T0]]( // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[ADDR]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]] // CHECK-NEXT: store [[T1]] to [[T0]] // CHECK-NEXT: strong_release [[C]] // CHECK-NEXT: tuple () // CHECK-NEXT: return func get(inout holder holder: Holder) -> C { return holder.value } // CHECK-LABEL:sil hidden @_TF9unmanaged3getFT6holderRVS_6Holder_CS_1C : $@convention(thin) (@inout Holder) -> @owned C // CHECK: bb0([[ADDR:%.*]] : $*Holder): // CHECK-NEXT: debug_value_addr %0 : $*Holder, var, name "holder", argno 1 // CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[ADDR]] : $*Holder, #Holder.value // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*@sil_unmanaged C // CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]] // CHECK-NEXT: strong_retain [[T2]] // CHECK-NEXT: return [[T2]] func project(fn fn: () -> Holder) -> C { return fn().value } // CHECK-LABEL:sil hidden @_TF9unmanaged7projectFT2fnFT_VS_6Holder_CS_1C : $@convention(thin) (@owned @callee_owned () -> Holder) -> @owned C // CHECK: bb0([[FN:%.*]] : $@callee_owned () -> Holder): // CHECK: strong_retain [[FN]] // CHECK-NEXT: [[T0:%.*]] = apply [[FN]]() // CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value // CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]] // CHECK-NEXT: strong_retain [[T2]] // CHECK-NEXT: strong_release [[FN]] // CHECK-NEXT: return [[T2]]
795d265f23f28aac5f2bf7d6497e1898
41.924528
141
0.584615
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01251-getcallerdefaultarg.swift
apache-2.0
13
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class func a() -> String { re> d) { } protocol A { } init <A: A where A.B == D>(e: A.B) { } var e: Int -> Int = { return $0 = { c, b in }(f, e) func a(b: Int = 0) { } let c = a c()
101edd212e929dd8ec93a009cba80828
17.904762
87
0.619647
false
true
false
false
konanxu/WeiBoWithSwift
refs/heads/master
WeiBo/WeiBo/Classes/Home/QRCode/QRCodeViewController.swift
mit
1
// // QRCodeViewController.swift // WeiBo // // Created by Konan on 16/3/13. // Copyright © 2016年 Konan. All rights reserved. // import UIKit import AVFoundation class QRCodeViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! ///顶部约束 @IBOutlet weak var scanLineCons: NSLayoutConstraint! /// 高度约束 @IBOutlet weak var containerHeightCons: NSLayoutConstraint! @IBOutlet weak var scanLine: UIImageView! @IBOutlet weak var customTabBar: UITabBar! @IBAction func closeBtnItemClick(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func albumClick(sender: AnyObject) { let sb = UIStoryboard(name: "SegueTestViewController", bundle: nil) let vc = sb.instantiateInitialViewController() presentViewController(vc!, animated: true, completion: nil) } @IBAction func myCardClick(sender: AnyObject) { let vc = QRCodeCardViewController() navigationController?.pushViewController(vc, animated: true) } override func viewDidLoad() { super.viewDidLoad() customTabBar.selectedItem = customTabBar.items![0] customTabBar.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //开始动画 startAnimation() //开始扫描 startScan() } private func startScan(){ //1.判断是否能够将输入添加到会话中 //2.判断是否能够将输出添加到会话中 if (!session.canAddInput(deviceInput)){ return } if (!session.canAddOutput(output)){ return } //3.将输入和输出添加到会话中 session.addInput(deviceInput) session.addOutput(output) //4.设置输出能够解析的数据类型 output.metadataObjectTypes = output.availableMetadataObjectTypes //5.这只输出对象代理,解析成功就会通知代理 output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) output.rectOfInterest = CGRectMake(0.0, 0.0, 1, 1) view.layer.insertSublayer(preViewLayer, atIndex: 0) preViewLayer.addSublayer(drawLayer) //6.告诉session开始扫描 session.startRunning() } private func startAnimation(){ self.scanLineCons.constant = -self.containerHeightCons.constant self.scanLine.layoutIfNeeded() UIView.animateWithDuration(2, animations: { () -> Void in self.scanLineCons.constant = self.containerHeightCons.constant UIView.setAnimationRepeatCount(MAXFLOAT) self.scanLine.layoutIfNeeded() }, completion: nil) } private lazy var session:AVCaptureSession = AVCaptureSession() private lazy var deviceInput :AVCaptureDeviceInput? = { //获取摄像头 let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do{ //创建输入对象 let input = try AVCaptureDeviceInput(device: device) return input }catch{ print(error) return nil } }() // 拿到输出对象 private lazy var output:AVCaptureMetadataOutput = AVCaptureMetadataOutput() // MARK: - 创建预览图层 private lazy var preViewLayer:AVCaptureVideoPreviewLayer = { let layer = AVCaptureVideoPreviewLayer(session: self.session) layer.frame = UIScreen.mainScreen().bounds return layer }() // MARK: - 绘制边线图层 private lazy var drawLayer:CALayer = { let layer = CALayer() layer.frame = UIScreen.mainScreen().bounds return layer }() } extension QRCodeViewController:UITabBarDelegate{ func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { if(item == customTabBar.items![0]){ print("二维码") self.containerHeightCons.constant = 300 }else{ print("条形码") self.containerHeightCons.constant = 150 } scanLine.layer.removeAllAnimations() startAnimation() } } extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{ func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { //获取扫描数据 print(metadataObjects) if(metadataObjects.last == nil){ clearCorners() } resultLabel.text = metadataObjects.last?.stringValue resultLabel.sizeToFit() //获取扫描位置,转换坐标 print(metadataObjects.last) for object in metadataObjects{ if object is AVMetadataMachineReadableCodeObject{ let codeobject = preViewLayer.transformedMetadataObjectForMetadataObject(object as!AVMetadataObject) as! AVMetadataMachineReadableCodeObject //绘制图形 drawCorners(codeobject) } } } private func drawCorners(codeObject:AVMetadataMachineReadableCodeObject) { if(codeObject.corners.isEmpty){ clearCorners() return } clearCorners() let layer = CAShapeLayer() layer.lineWidth = 4 layer.strokeColor = UIColor.redColor().CGColor layer.fillColor = UIColor.clearColor().CGColor //创建路径 // layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).CGPath let path = UIBezierPath() var point = CGPointZero var index :Int = 0 CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point) path.moveToPoint(point) while index < codeObject.corners.count{ CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point) path.addLineToPoint(point) } //关闭路径 path.closePath() layer.path = path.CGPath drawLayer.addSublayer(layer) /* let time : NSTimeInterval = 1.5 let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))) dispatch_after(delay, dispatch_get_main_queue()) { () -> Void in self.clearCorners() } */ } //清空边线 private func clearCorners(){ if((drawLayer.sublayers == nil) || drawLayer.sublayers?.count == 0){ return } for subLayer in drawLayer.sublayers!{ subLayer.removeFromSuperlayer() } } }
748962e0692d2f415f5e54f906066e2e
30.32381
162
0.619431
false
false
false
false
BenziAhamed/Tracery
refs/heads/master
Common/Tracery.Text.swift
mit
1
// // Tracery.Text.swift // Tracery // // Created by Benzi on 21/03/17. // Copyright © 2017 Benzi Ahamed. All rights reserved. // import Foundation // File format that can scan plain text extension Tracery { convenience public init(path: String) { if let reader = StreamReader(path: path) { self.init { TextParser.parse(lines: reader) } } else { warn("unable to parse input file: \(path)") self.init() } } convenience public init(lines: [String]) { self.init { TextParser.parse(lines: lines) } } } struct TextParser { enum State { case consumeRule case consumeDefinitions } static func parse<S: Sequence>(lines: S) -> [String: Any] where S.Iterator.Element == String { var ruleSet = [String: Any]() var state = State.consumeRule var rule = "" var candidates = [String]() func createRule() { if ruleSet[rule] != nil { warn("rule '\(rule)' defined twice, will be overwritten") } if candidates.count == 0 { candidates.append("") } ruleSet[rule] = candidates } for line in lines { switch state { case .consumeRule: if line.count > 2, line.hasPrefix("["), line.hasSuffix("]") { let start = line.index(after: line.startIndex) let end = line.index(before: line.endIndex) rule = String(line[start..<end]) state = .consumeDefinitions } case .consumeDefinitions: if line == "" { createRule() candidates.removeAll() state = .consumeRule } else { candidates.append(line) } } } // if we reached the end, and // we are in the midst of consuming // definitions, create a rule if state == .consumeDefinitions { createRule() } return ruleSet } } class StreamReader { let encoding : String.Encoding let chunkSize : Int var fileHandle : FileHandle! let buffer : NSMutableData! let delimData : Data! var atEof : Bool = false init?(path: String, delimiter: String = "\n", encoding: String.Encoding = .utf8, chunkSize : Int = 4096) { self.chunkSize = chunkSize self.encoding = encoding if let fileHandle = FileHandle(forReadingAtPath: path), let delimData = delimiter.data(using: encoding), let buffer = NSMutableData(capacity: chunkSize) { self.fileHandle = fileHandle self.delimData = delimData self.buffer = buffer } else { self.fileHandle = nil self.delimData = nil self.buffer = nil return nil } } deinit { self.close() } /// Return next line, or nil on EOF. func nextLine() -> String? { precondition(fileHandle != nil, "Attempt to read from closed file") if atEof { return nil } // Read data chunks from file until a line delimiter is found: var range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length)) while range.location == NSNotFound { let tmpData = fileHandle.readData(ofLength: chunkSize) if tmpData.count == 0 { // EOF or read error. atEof = true if buffer.length > 0 { // Buffer contains last line in file (not terminated by delimiter). let line = String(data: buffer as Data, encoding: encoding) buffer.length = 0 return line as String? } // No more lines. return nil } buffer.append(tmpData) range = buffer.range(of: delimData, options: [], in: NSMakeRange(0, buffer.length)) } // Convert complete line (excluding the delimiter) to a string: let line = String(data: buffer.subdata(with: NSMakeRange(0, range.location)), encoding: encoding) // Remove line (and the delimiter) from the buffer: buffer.replaceBytes(in: NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0) return line } /// Start reading from the beginning of file. func rewind() -> Void { fileHandle.seek(toFileOffset: 0) buffer.length = 0 atEof = false } /// Close the underlying file. No reading must be done after calling this method. func close() -> Void { fileHandle?.closeFile() fileHandle = nil } } extension StreamReader: Sequence { func makeIterator() -> AnyIterator<String> { return AnyIterator<String> { return self.nextLine() } } }
0b4ce17f59e38cb65c8ec3dba8b334f3
28
110
0.517432
false
false
false
false
alexshepard/Fishtacos
refs/heads/master
Fishtacos/ViewController.swift
mit
1
// // ViewController.swift // Fishtacos // // Created by Alex Shepard on 8/22/15. // Copyright © 2015 Alex Shepard. All rights reserved. // import UIKit import GameKit class ViewController: UIViewController, GKGameCenterControllerDelegate, GKLocalPlayerListener, GKTurnBasedMatchmakerViewControllerDelegate { @IBOutlet weak var newGameButton: UIButton? @IBOutlet weak var leaderboardButton: UIButton? @IBOutlet weak var loadingGameCenterLabel: UILabel? override func viewDidLoad() { super.viewDidLoad() self.loadingGameCenterLabel?.hidden = false self.newGameButton?.enabled = false self.leaderboardButton?.enabled = false // auth our user let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(ViewController, error) -> Void in if let authVC = ViewController { self.presentViewController(authVC, animated: true, completion: nil) } else if (localPlayer.authenticated) { self.loadingGameCenterLabel?.hidden = true self.newGameButton?.enabled = true self.leaderboardButton?.enabled = true localPlayer.registerListener(self) } else { let alert = UIAlertController(title: "No game center", message: "Try again later", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (_) -> Void in self.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) self.loadingGameCenterLabel?.text = "No game center" } } } //MARK: - UIButton targets @IBAction func newGame(sender: UIButton) { let matchRequest = GKMatchRequest() matchRequest.minPlayers = 2 matchRequest.maxPlayers = 2 matchRequest.defaultNumberOfPlayers = 2 let vc = GKTurnBasedMatchmakerViewController( matchRequest: matchRequest ) vc.turnBasedMatchmakerDelegate = self presentViewController(vc, animated: true, completion: nil) } @IBAction func leaderboards(sender: UIButton) { let gcVC: GKGameCenterViewController = GKGameCenterViewController() gcVC.gameCenterDelegate = self gcVC.viewState = GKGameCenterViewControllerState.Leaderboards gcVC.leaderboardIdentifier = "LeaderboardID" self.presentViewController(gcVC, animated: true, completion: nil) } //MARK: - GKGameCenterControllerDelegate func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } //MARK: - GKTurnBasedMatchmakerViewControllerDelegate func turnBasedMatchmakerViewController(viewController: GKTurnBasedMatchmakerViewController, didFindMatch match: GKTurnBasedMatch) { dismissViewControllerAnimated(true) { print("matchmaker got match \(match)") self.updateCurrentMatchData(match) } } func turnBasedMatchmakerViewController(viewController: GKTurnBasedMatchmakerViewController, didFailWithError error: NSError) { dismissViewControllerAnimated(true) { print("matchmaker failed with error \(error)") } } func turnBasedMatchmakerViewController(viewController: GKTurnBasedMatchmakerViewController, playerQuitForMatch match: GKTurnBasedMatch) { dismissViewControllerAnimated(true) { print("matchmaker player quit \(match)") } } func turnBasedMatchmakerViewControllerWasCancelled(viewController: GKTurnBasedMatchmakerViewController) { dismissViewControllerAnimated(true) { print("matchmaker was cancelled") } } //MARK: - GKTurnBasedEventListener func player(player: GKPlayer, receivedTurnEventForMatch match: GKTurnBasedMatch, didBecomeActive: Bool) { updateCurrentMatchData(match) } //MARK: - update match data func updateCurrentMatchData(match: GKTurnBasedMatch) { print("update for \(match)") } }
5d5d1fad2438dcf73c07f15e4a7c07aa
35.691667
141
0.664093
false
false
false
false
a178960320/MyDouyu
refs/heads/master
Douyu/Douyu/Classes/Home/Controller/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // Douyu // // Created by 住梦iOS on 2017/2/28. // Copyright © 2017年 qiongjiwuxian. All rights reserved. // import UIKit private let kItemMargin:CGFloat = 10 private let kItemW = (SCREEN_WIDTH - 3 * kItemMargin)/2 private let kNormalItemH = kItemW * 3 / 4 private let kPrettyItemH = kItemW * 8 / 7 class RecommendViewController: UIViewController { //ViewModel let recommentViewModel = RecommentViewModel() //MARK: - 懒加载属性 lazy var collectionView:UICollectionView = { //1.定义布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: 50) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //2。创建collectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib.init(nibName: "NormalCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "NormalCell") collectionView.register(UINib.init(nibName: "PrettyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "PrettyCell") collectionView.register(UINib.init(nibName: "HeaderCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView") //设置collectionView随着父控件的缩小而缩小 collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth] return collectionView }() override func viewDidLoad() { super.viewDidLoad() //设置UI setupUI() //网络请求 getNetData() } } //MARK: - 创建UI extension RecommendViewController{ func setupUI(){ view.addSubview(collectionView) } } //MARK: - collection的协议代理 extension RecommendViewController:UICollectionViewDelegateFlowLayout,UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommentViewModel.anchorGroup[section] return group.room_list.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ //1.定义cell var cell:BaseCollectionViewCell! //2.取出cell if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PrettyCell", for: indexPath) as! BaseCollectionViewCell }else{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NormalCell", for: indexPath) as! BaseCollectionViewCell } cell.model = recommentViewModel.anchorGroup[indexPath.section].room_list[indexPath.row] return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return recommentViewModel.anchorGroup.count } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1. let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headView", for: indexPath) as! HeaderCollectionReusableView //2. let group = recommentViewModel.anchorGroup[indexPath.section] //3. headView.iconImageView.image = UIImage.init(named: group.icon_name) headView.titleLabel.text = group.tag_name return headView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) }else{ return CGSize(width: kItemW, height: kNormalItemH) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let liveVC = HomeLiveViewController() liveVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(liveVC, animated: true) } } //MARK: - 网络请求 extension RecommendViewController{ func getNetData(){ recommentViewModel.loadData { self.collectionView.reloadData() } } }
ce072cf80f0705c7c994a4646c5a7b53
36.65873
196
0.688514
false
false
false
false
myandy/shi_ios
refs/heads/master
shishi/UI/All/AllAuthorCell.swift
apache-2.0
1
// // AllAuthorCell.swift // shishi // // Created by andymao on 2017/4/5. // Copyright © 2017年 andymao. All rights reserved. // import UIKit public class AllAuthorCell: UICollectionViewCell { public var topView: UIView! public var dynastyLabel: UILabel! public var dynastyEnLabel: UILabel! public var numLabel: UILabel! public var authorLabel: UILabel! public override init(frame: CGRect) { super.init(frame: frame) topView = UIView(frame:CGRect(x: 0, y: 0, width: 70, height: 3)) self.addSubview(topView) dynastyLabel=UILabel(frame:CGRect(x:0,y:10,width:20,height:20)) dynastyLabel.layer.cornerRadius = 10 dynastyLabel.clipsToBounds = true dynastyLabel.layer.borderWidth = 1 dynastyLabel.textAlignment = NSTextAlignment.center dynastyLabel.font=UIFont(name: FontsUtils.FONTS[0], size: 12) self.addSubview(dynastyLabel) dynastyEnLabel=UILabel(frame:CGRect(x:-66,y:115,width:150,height:20)) dynastyEnLabel.transform=CGAffineTransform.init(rotationAngle:CGFloat(Double.pi/2)) self.addSubview(dynastyEnLabel) numLabel=UILabel(frame:CGRect(x:32,y:15,width:30,height:12)) numLabel.font=UIFont(name: FontsUtils.FONTS[0], size: 15) numLabel.textAlignment = NSTextAlignment.center self.addSubview(numLabel) authorLabel=UILabel(frame:CGRect(x:35,y:30,width:30,height:120)) authorLabel.font = UIFont(name: FontsUtils.FONTS[0], size: 24) authorLabel.numberOfLines = 0 self.addSubview(authorLabel) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
146e1c2e2ea762cd0b052a5125622be7
34.14
91
0.67103
false
false
false
false
massada/swift-collections
refs/heads/master
CollectionsTests/StackTests.swift
apache-2.0
1
// // StackTests.swift // Collections // // Copyright (c) 2016 José Massada <[email protected]> // // 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 XCTest @testable import Collections class StackTests : XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInitialises() { let stack = Stack<Int>() XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testInitialisesFromEmptyArrayLiteral() { let stack: Stack<Int> = [] XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testInitialisesFromArrayLiteral() { let stack: Stack = [1, 2, 3] XCTAssertFalse(stack.isEmpty) XCTAssertEqual(3, stack.count) XCTAssertEqual(3, stack.top) for (i, element) in stack.enumerated() { XCTAssertEqual(3 - i, element) } } func testInitialisesFromEmptySequence() { let stack = Stack<Int>([]) XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testInitialisesFromSequence() { let stack = Stack<Int>([1, 2, 3]) XCTAssertFalse(stack.isEmpty) XCTAssertEqual(3, stack.count) XCTAssertEqual(3, stack.top) for (i, element) in stack.enumerated() { XCTAssertEqual(3 - i, element) } } func testClears() { var stack: Stack = [1, 2, 3] stack.clear() XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testPushesElement() { var stack = Stack<Int>() stack.push(1) XCTAssertFalse(stack.isEmpty) XCTAssertEqual(1, stack.count) XCTAssertEqual(1, stack.top) } func testPushesElements() { var stack = Stack<Int>() stack.push(1) stack.push(2) stack.push(3) XCTAssertFalse(stack.isEmpty) XCTAssertEqual(3, stack.count) XCTAssertEqual(3, stack.top) } func testPopsElement() { var stack: Stack = [1] XCTAssertEqual(1, stack.pop()) XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testPopsElements() { var stack: Stack = [1, 2, 3] XCTAssertEqual(3, stack.pop()) XCTAssertEqual(2, stack.pop()) XCTAssertEqual(1, stack.pop()) XCTAssertTrue(stack.isEmpty) XCTAssertEqual(0, stack.count) XCTAssertEqual(nil, stack.top) } func testEquals() { XCTAssertTrue(Stack<Int>() == []) XCTAssertTrue([] == Stack<Int>([])) XCTAssertTrue(Stack<Int>() == Stack<Int>([])) let stack: Stack = [1, 2, 3] var anotherStack: Stack = [1, 2] XCTAssertTrue(stack != anotherStack) anotherStack.push(3) XCTAssertTrue(stack == anotherStack) } func testPushingPerformance() { measure { var stack = Stack<Int>() for i in 0..<100_000 { stack.push(i) } } } func testPushingPoppingPerformance() { measure { var stack = Stack<Int>() for i in 0..<100_000 { stack.push(i) XCTAssertEqual(i, stack.pop()) } } } func testGetsDescriptions() { var stack: Stack<Int> = [] XCTAssertEqual(stack.description, "[]") XCTAssertEqual(stack.debugDescription, "Stack([])") stack = [1, 2] XCTAssertEqual(stack.description, "[2, 1]") XCTAssertEqual(stack.debugDescription, "Stack([2, 1])") } }
e72c20d44802048c759b80da0f34b919
22.485549
75
0.635245
false
true
false
false
FotiosTragopoulos/Core-Geometry
refs/heads/master
Core Geometry/Par3ViewFilling.swift
apache-2.0
1
// // Par3ViewFilling.swift // Core Geometry // // Created by Fotios Tragopoulos on 13/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Par3ViewFilling: UIView { override func draw(_ rect: CGRect) { let filling = UIGraphicsGetCurrentContext() let xView = viewWithTag(7)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(7)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(7)?.frame.size.width let height = self.viewWithTag(7)?.frame.size.height let size = CGSize(width: width! * 0.6, height: height! * 0.4) let linePlacementX = CGFloat(size.width/2) let linePlacementY = CGFloat(size.height/2) let myShadowOffset = CGSize (width: 10, height: 10) filling?.setShadow (offset: myShadowOffset, blur: 8) filling?.saveGState() filling?.move(to: CGPoint(x: (xView! - (linePlacementX * 1.3)), y: (yView! + (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 0.7)), y: (yView! + (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! + (linePlacementX * 1.3)), y: (yView! - (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 0.7)), y: (yView! - (linePlacementY * 1.2)))) filling?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 1.3)), y: (yView! + (linePlacementY * 1.2)))) filling?.setFillColor(UIColor.white.cgColor) filling?.fillPath() filling?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
8957b1e6e99507375a676252d90a2f44
42.977273
219
0.625323
false
false
false
false
SEMT2Group1/CASPER_IOS_Client
refs/heads/master
Pods/Socket.IO-Client-Swift/Source/SocketEngine.swift
mit
2
// // SocketEngine.swift // Socket.IO-Client-Swift // // Created by Erik Little on 3/3/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 public final class SocketEngine: NSObject, SocketEnginePollable, SocketEngineWebsocket { public let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL) public let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL) public let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL) public var connectParams: [String: AnyObject]? { didSet { (urlPolling, urlWebSocket) = createURLs() } } public var postWait = [String]() public var waitingForPoll = false public var waitingForPost = false public private(set) var closed = false public private(set) var connected = false public private(set) var cookies: [NSHTTPCookie]? public private(set) var doubleEncodeUTF8 = true public private(set) var extraHeaders: [String: String]? public private(set) var fastUpgrade = false public private(set) var forcePolling = false public private(set) var forceWebsockets = false public private(set) var invalidated = false public private(set) var pingTimer: NSTimer? public private(set) var polling = true public private(set) var probing = false public private(set) var session: NSURLSession? public private(set) var sid = "" public private(set) var socketPath = "/engine.io/" public private(set) var urlPolling = NSURL() public private(set) var urlWebSocket = NSURL() public private(set) var websocket = false public private(set) var ws: WebSocket? public weak var client: SocketEngineClient? private weak var sessionDelegate: NSURLSessionDelegate? private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData]) private typealias ProbeWaitQueue = [Probe] private let logType = "SocketEngine" private let url: NSURL private var pingInterval: Double? private var pingTimeout = 0.0 { didSet { pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25)) } } private var pongsMissed = 0 private var pongsMissedMax = 0 private var probeWait = ProbeWaitQueue() private var secure = false private var selfSigned = false private var voipEnabled = false public init(client: SocketEngineClient, url: NSURL, options: Set<SocketIOClientOption>) { self.client = client self.url = url for option in options { switch option { case let .ConnectParams(params): connectParams = params case let .Cookies(cookies): self.cookies = cookies case let .DoubleEncodeUTF8(encode): doubleEncodeUTF8 = encode case let .ExtraHeaders(headers): extraHeaders = headers case let .SessionDelegate(delegate): sessionDelegate = delegate case let .ForcePolling(force): forcePolling = force case let .ForceWebsockets(force): forceWebsockets = force case let .Path(path): socketPath = path case let .VoipEnabled(enable): voipEnabled = enable case let .Secure(secure): self.secure = secure case let .SelfSigned(selfSigned): self.selfSigned = selfSigned default: continue } } super.init() (urlPolling, urlWebSocket) = createURLs() } public convenience init(client: SocketEngineClient, url: NSURL, options: NSDictionary?) { self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? []) } @available(*, deprecated=5.3) public convenience init(client: SocketEngineClient, urlString: String, options: Set<SocketIOClientOption>) { guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") } self.init(client: client, url: url, options: options) } @available(*, deprecated=5.3) public convenience init(client: SocketEngineClient, urlString: String, options: NSDictionary?) { guard let url = NSURL(string: urlString) else { fatalError("Incorrect url") } self.init(client: client, url: url, options: options?.toSocketOptionsSet() ?? []) } deinit { DefaultSocketLogger.Logger.log("Engine is being released", type: logType) closed = true stopPolling() } private func checkAndHandleEngineError(msg: String) { guard let stringData = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return } do { if let dict = try NSJSONSerialization.JSONObjectWithData(stringData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { guard let code = dict["code"] as? Int else { return } guard let error = dict["message"] as? String else { return } switch code { case 0: // Unknown transport didError(error) case 1: // Unknown sid. didError(error) case 2: // Bad handshake request didError(error) case 3: // Bad request didError(error) default: didError(error) } } } catch { didError("Got unknown error from server \(msg)") } } private func checkIfMessageIsBase64Binary(message: String) -> Bool { if message.hasPrefix("b4") { // binary in base64 string let noPrefix = message[message.startIndex.advancedBy(2)..<message.endIndex] if let data = NSData(base64EncodedString: noPrefix, options: .IgnoreUnknownCharacters) { client?.parseEngineBinaryData(data) } return true } else { return false } } public func close(reason: String) { func postSendClose(data: NSData?, _ res: NSURLResponse?, _ err: NSError?) { sid = "" closed = true invalidated = true connected = false pingTimer?.invalidate() ws?.disconnect() stopPolling() client?.engineDidClose(reason) } DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType) if websocket { sendWebSocketMessage("", withType: .Close, withData: []) postSendClose(nil, nil, nil) } else { // We need to take special care when we're polling that we send it ASAP // Also make sure we're on the emitQueue since we're touching postWait dispatch_sync(emitQueue) { self.postWait.append(String(SocketEnginePacketType.Close.rawValue)) let req = self.createRequestForPostWithPostWait() self.doRequest(req, withCallback: postSendClose) } } } private func createURLs() -> (NSURL, NSURL) { if client == nil { return (NSURL(), NSURL()) } let urlPolling = NSURLComponents(string: url.absoluteString)! let urlWebSocket = NSURLComponents(string: url.absoluteString)! var queryString = "" urlWebSocket.path = socketPath urlPolling.path = socketPath urlWebSocket.query = "transport=websocket" urlPolling.query = "transport=polling&b64=1" if secure { urlPolling.scheme = "https" urlWebSocket.scheme = "wss" } else { urlPolling.scheme = "http" urlWebSocket.scheme = "ws" } if connectParams != nil { for (key, value) in connectParams! { queryString += "&\(key)=\(value)" } } urlWebSocket.query = urlWebSocket.query! + queryString urlPolling.query = urlPolling.query! + queryString return (urlPolling.URL!, urlWebSocket.URL!) } private func createWebsocketAndConnect() { ws = WebSocket(url: urlWebSocketWithSid) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) for (key, value) in headers { ws?.headers[key] = value } } if extraHeaders != nil { for (headerName, value) in extraHeaders! { ws?.headers[headerName] = value } } ws?.queue = handleQueue ws?.voipEnabled = voipEnabled ws?.delegate = self ws?.selfSignedSSL = selfSigned ws?.connect() } public func didError(error: String) { DefaultSocketLogger.Logger.error(error, type: logType) client?.engineDidError(error) close(error) } public func doFastUpgrade() { if waitingForPoll { DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," + "we'll probably disconnect soon. You should report this.", type: logType) } sendWebSocketMessage("", withType: .Upgrade, withData: []) websocket = true polling = false fastUpgrade = false probing = false flushProbeWait() } private func flushProbeWait() { DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType) dispatch_async(emitQueue) { for waiter in self.probeWait { self.write(waiter.msg, withType: waiter.type, withData: waiter.data) } self.probeWait.removeAll(keepCapacity: false) if self.postWait.count != 0 { self.flushWaitingForPostToWebSocket() } } } // We had packets waiting for send when we upgraded // Send them raw public func flushWaitingForPostToWebSocket() { guard let ws = self.ws else { return } for msg in postWait { ws.writeString(fixDoubleUTF8(msg)) } postWait.removeAll(keepCapacity: true) } private func handleClose(reason: String) { client?.engineDidClose(reason) } private func handleMessage(message: String) { client?.parseEngineMessage(message) } private func handleNOOP() { doPoll() } private func handleOpen(openData: String) { let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! do { let json = try NSJSONSerialization.JSONObjectWithData(mesData, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary if let sid = json?["sid"] as? String { let upgradeWs: Bool self.sid = sid connected = true if let upgrades = json?["upgrades"] as? [String] { upgradeWs = upgrades.contains("websocket") } else { upgradeWs = false } if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double { self.pingInterval = pingInterval / 1000.0 self.pingTimeout = pingTimeout / 1000.0 } if !forcePolling && !forceWebsockets && upgradeWs { createWebsocketAndConnect() } startPingTimer() if !forceWebsockets { doPoll() } client?.engineDidOpen?("Connect") } } catch { didError("Error parsing open packet") return } } private func handlePong(pongMessage: String) { pongsMissed = 0 // We should upgrade if pongMessage == "3probe" { upgradeTransport() } } public func open() { if connected { DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType) close("reconnect") } DefaultSocketLogger.Logger.log("Starting engine", type: logType) DefaultSocketLogger.Logger.log("Handshaking", type: logType) resetEngine() if forceWebsockets { polling = false websocket = true createWebsocketAndConnect() return } let reqPolling = NSMutableURLRequest(URL: urlPolling) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) reqPolling.allHTTPHeaderFields = headers } if let extraHeaders = extraHeaders { for (headerName, value) in extraHeaders { reqPolling.setValue(value, forHTTPHeaderField: headerName) } } doLongPoll(reqPolling) } public func parseEngineData(data: NSData) { DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data) client?.parseEngineBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1))) } public func parseEngineMessage(message: String, fromPolling: Bool) { DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message) let reader = SocketStringReader(message: message) let fixedString: String guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else { if !checkIfMessageIsBase64Binary(message) { checkAndHandleEngineError(message) } return } if fromPolling && type != .Noop && doubleEncodeUTF8 { fixedString = fixDoubleUTF8(message) } else { fixedString = message } switch type { case .Message: handleMessage(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex]) case .Noop: handleNOOP() case .Pong: handlePong(fixedString) case .Open: handleOpen(fixedString[fixedString.startIndex.successor()..<fixedString.endIndex]) case .Close: handleClose(fixedString) default: DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType) } } private func resetEngine() { closed = false connected = false fastUpgrade = false polling = true probing = false invalidated = false session = NSURLSession(configuration: .defaultSessionConfiguration(), delegate: sessionDelegate, delegateQueue: NSOperationQueue()) sid = "" waitingForPoll = false waitingForPost = false websocket = false } @objc private func sendPing() { //Server is not responding if pongsMissed > pongsMissedMax { pingTimer?.invalidate() client?.engineDidClose("Ping timeout") return } pongsMissed += 1 write("", withType: .Ping, withData: []) } // Starts the ping timer private func startPingTimer() { if let pingInterval = pingInterval { pingTimer?.invalidate() pingTimer = nil dispatch_async(dispatch_get_main_queue()) { self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self, selector: Selector("sendPing"), userInfo: nil, repeats: true) } } } private func upgradeTransport() { if ws?.isConnected ?? false { DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType) fastUpgrade = true sendPollMessage("", withType: .Noop, withData: []) // After this point, we should not send anymore polling messages } } /** Write a message, independent of transport. */ public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]) { dispatch_async(emitQueue) { guard self.connected else { return } if self.websocket { DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendWebSocketMessage(msg, withType: type, withData: data) } else if !self.probing { DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg, data.count != 0) self.sendPollMessage(msg, withType: type, withData: data) } else { self.probeWait.append((msg, type, data)) } } } // Delegate methods public func websocketDidConnect(socket: WebSocket) { if !forceWebsockets { probing = true probeWebSocket() } else { connected = true probing = false polling = false } } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { probing = false if closed { client?.engineDidClose("Disconnect") return } if websocket { pingTimer?.invalidate() connected = false websocket = false let reason = error?.localizedDescription ?? "Socket Disconnected" if error != nil { didError(reason) } client?.engineDidClose(reason) } else { flushProbeWait() } } }
5f2bc00f2af094b6aa7f701c3f3c6be9
33.246479
130
0.579118
false
false
false
false
notbenoit/tvOS-Twitch
refs/heads/develop
Code/iOS/Controllers/Home/Cells/GameCell.swift
bsd-3-clause
1
// Copyright (c) 2015 Benoit Layer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ReactiveSwift import WebImage import DataSource final class GameCell: CollectionViewCell { static let identifier: String = "cellIdentifierGame" static let nib: UINib = UINib(nibName: "GameCell", bundle: nil) @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var labelName: UILabel! fileprivate let disposable = CompositeDisposable() override func prepareForReuse() { imageView.image = nil labelName.text = nil } override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.twitchLightColor() disposable += self.cellModel.producer .map { $0 as? GameCellViewModel } .skipNil() .startWithValues { [weak self] in self?.configure(with: $0) } } private func configure(with item: GameCellViewModel) { labelName.text = item.gameName if let url = URL(string: item.gameImageURL) { imageView.sd_setImage(with: url) } } }
76894252839eee370598b73fd8f54612
35.142857
80
0.751482
false
false
false
false
sambatech/player_sdk_ios
refs/heads/master
SambaPlayer/AssetLoaderDelegate.swift
mit
1
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: `AssetLoaderDelegate` is a class that implements an AVAssetResourceLoader delegate that will handle FairPlay Streaming key requests. */ import Foundation import AVFoundation class AssetLoaderDelegate: NSObject { /// The URL scheme for FPS content. static let customScheme = "^skd|^http" /// Error domain for errors being thrown in the process of getting a CKC. static let errorDomain = "SambaPlayerErrorDomain" /// Notification for when the persistent content key has been saved to disk. //static let didPersistContentKeyNotification = NSNotification.Name(rawValue: "handleAssetLoaderDelegateDidPersistContentKeyNotification") /// The AVURLAsset associated with the asset. fileprivate let asset: AVURLAsset /// The name associated with the asset. fileprivate let assetName: String /// The SambaTech/Irdeto DRM request. fileprivate let drmRequest: DrmRequest /// The DispatchQueue to use for AVAssetResourceLoaderDelegate callbacks. fileprivate let resourceLoadingRequestQueue = DispatchQueue(label: "com.sambatech.resourcerequests") /// The document URL to use for saving persistent content key. fileprivate let documentURL: URL fileprivate let isForPersist: Bool init(asset: AVURLAsset, assetName: String, drmRequest: DrmRequest, isForPersist: Bool = false) { // Determine the library URL. guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { fatalError("Unable to determine library URL") } documentURL = URL(fileURLWithPath: documentPath) self.asset = asset self.assetName = assetName self.drmRequest = drmRequest self.isForPersist = isForPersist super.init() self.asset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "\(assetName)-delegateQueue")) self.asset.resourceLoader.preloadsEligibleContentKeys = true } /// Returns the Application Certificate needed to generate the Server Playback Context message. public func fetchApplicationCertificate() -> Data? { let applicationCertificate: Data? = try? Data(contentsOf: URL(string: drmRequest.acUrl)!) // if applicationCertificate == nil { // fatalError("No certificate being returned by \(#function)!") // } return applicationCertificate } public func contentKeyFromKeyServerModuleWithSPCData(spcData: Data, assetIDString: String, requestUrl: String) -> Data? { var ckcData: Data? = nil guard let url = URL(string: requestUrl + (requestUrl.contains("&") ? "&" : "?") + drmRequest.licenseUrlParamsStr) else { fatalError("Invalid URL (\(requestUrl)) and query string (\(drmRequest.licenseUrlParamsStr)) at \(#function)!") } print(url) var req = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: Helpers.requestTimeout) req.httpMethod = "POST" req.httpBody = spcData let sem = DispatchSemaphore.init(value: 0) Helpers.requestURL(req, { (data: Data?) in ckcData = data sem.signal() },{ (error, response) in sem.signal() }) _ = sem.wait(timeout: .distantFuture) // if ckcData == nil { // fatalError("No CKC being returned by \(#function)!") // } return ckcData } public func deletePersistedConentKeyForAsset() { OfflineUtils.clearCurrentTimeForContentKey(for: assetName) guard let filePathURLForPersistedContentKey = filePathURLForPersistedContentKey() else { return } do { try FileManager.default.removeItem(at: filePathURLForPersistedContentKey) UserDefaults.standard.removeObject(forKey: "\(assetName)-Key") } catch { print("An error occured removing the persisted content key: \(error)") } } } //MARK:- Internal methods extension. private extension AssetLoaderDelegate { func filePathURLForPersistedContentKey() -> URL? { var filePathURL: URL? guard let fileName = UserDefaults.standard.value(forKey: "\(assetName)-Key") as? String else { return filePathURL } let url = documentURL.appendingPathComponent(fileName) if url != documentURL { filePathURL = url } return filePathURL } func prepareAndSendContentKeyRequest(resourceLoadingRequest: AVAssetResourceLoadingRequest) { var proto: String? if drmRequest.provider == "SAMBA_DRM" { proto = "https" } else { proto = "http" } guard let urlStr = resourceLoadingRequest.request.url?.absoluteString.replacingOccurrences(of: "^skd", with: proto!, options: .regularExpression), let url = URL(string: urlStr), let assetIDString = url.host else { print("Failed to get url or assetIDString for the request object of the resource.") return } var shouldPersist = false if #available(iOS 9.0, *) { shouldPersist = isForPersist // Check if this reuqest is the result of a potential AVAssetDownloadTask. if shouldPersist { if resourceLoadingRequest.contentInformationRequest != nil { resourceLoadingRequest.contentInformationRequest!.contentType = AVStreamingKeyDeliveryPersistentContentKeyType } else { print("Unable to set contentType on contentInformationRequest.") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } } } // Check if we have an existing key on disk for this asset. if let filePathURLForPersistedContentKey = filePathURLForPersistedContentKey() { if !OfflineUtils.isContentKeyExpired(for: assetName) { // Verify the file does actually exist on disk. if FileManager.default.fileExists(atPath: filePathURLForPersistedContentKey.path) { do { // Load the contents of the persistedContentKey file. let persistedContentKeyData = try Data(contentsOf: filePathURLForPersistedContentKey) guard let dataRequest = resourceLoadingRequest.dataRequest else { print("Error loading contents of content key file.") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } // Pass the persistedContentKeyData into the dataRequest so complete the content key request. dataRequest.respond(with: persistedContentKeyData) resourceLoadingRequest.finishLoading() return } catch { print("Error initializing Data from contents of URL: \(error.localizedDescription)") OfflineUtils.clearCurrentTimeForContentKey(for: assetName) let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } } } else { deletePersistedConentKeyForAsset() } } // Get the application certificate. guard let applicationCertificate = fetchApplicationCertificate() else { print("Error loading application certificate.") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } guard let assetIDData = assetIDString.data(using: String.Encoding.utf8) else { print("Error retrieving Asset ID.") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } var resourceLoadingRequestOptions: [String : AnyObject]? = nil // Check if this reuqest is the result of a potential AVAssetDownloadTask. if #available(iOS 9.0, *), shouldPersist { // Since this request is the result of an AVAssetDownloadTask, we configure the options to request a persistent content key from the KSM. resourceLoadingRequestOptions = [AVAssetResourceLoadingRequestStreamingContentKeyRequestRequiresPersistentKey: true as AnyObject] } let spcData: Data! do { /* To obtain the Server Playback Context (SPC), we call AVAssetResourceLoadingRequest.streamingContentKeyRequestData(forApp:contentIdentifier:options:) using the information we obtained earlier. */ spcData = try resourceLoadingRequest.streamingContentKeyRequestData(forApp: applicationCertificate, contentIdentifier: assetIDData, options: resourceLoadingRequestOptions) } catch { let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } /* Send the SPC message (requestBytes) to the Key Server and get a CKC in reply. The Key Server returns the CK inside an encrypted Content Key Context (CKC) message in response to the app’s SPC message. This CKC message, containing the CK, was constructed from the SPC by a Key Security Module in the Key Server’s software. When a KSM receives an SPC with a media playback state TLLV, the SPC may include a content key duration TLLV in the CKC message that it returns. If the Apple device finds this type of TLLV in a CKC that delivers an FPS content key, it will honor the type of rental or lease specified when the key is used. */ guard let ckcData = contentKeyFromKeyServerModuleWithSPCData(spcData: spcData, assetIDString: assetIDString, requestUrl: urlStr) else { print("Error retrieving CKC from KSM.") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } // Check if this reuqest is the result of a potential AVAssetDownloadTask. if #available(iOS 9.0, *), shouldPersist { // Since this request is the result of an AVAssetDownloadTask, we should get the secure persistent content key. var error: NSError? /* Obtain a persistable content key from a context. The data returned from this method may be used to immediately satisfy an AVAssetResourceLoadingDataRequest, as well as any subsequent requests for the same key url. The value of AVAssetResourceLoadingContentInformationRequest.contentType must be set to AVStreamingKeyDeliveryPersistentContentKeyType when responding with data created with this method. */ let persistentContentKeyData: Data! do { persistentContentKeyData = try resourceLoadingRequest.persistentContentKey(fromKeyVendorResponse: ckcData, options: nil) } catch { print("Error creating persistent content key: \(error)") resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name:Notification.Name.SambaDRMErrorNotification, object: nil) return } // Save the persistentContentKeyData onto disk for use in the future. do { let persistentContentKeyURL = documentURL.appendingPathComponent("\(asset.url.hashValue).key") if persistentContentKeyURL == documentURL { print("failed to create the URL for writing the persistent content key") resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } do { try persistentContentKeyData.write(to: persistentContentKeyURL, options: Data.WritingOptions.atomicWrite) // Since the save was successful, store the location of the key somewhere to reuse it for future calls. UserDefaults.standard.set("\(asset.url.hashValue).key", forKey: "\(assetName)-Key") guard let dataRequest = resourceLoadingRequest.dataRequest else { print("no data is being requested in loadingRequest") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } // Provide data to the loading request. OfflineUtils.saveCurrentTimeForContentKey(for: assetName) dataRequest.respond(with: persistentContentKeyData) resourceLoadingRequest.finishLoading() // Treat the processing of the request as complete. // Since the request has complete, notify the rest of the app that the content key has been persisted for this asset. //NotificationCenter.default.post(name: AssetLoaderDelegate.didPersistContentKeyNotification, object: asset, userInfo: [Asset.Keys.name : assetName]) } catch let error as NSError { print("failed writing persisting key to path: \(persistentContentKeyURL) with error: \(error)") OfflineUtils.clearCurrentTimeForContentKey(for: assetName) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } } } else { guard let dataRequest = resourceLoadingRequest.dataRequest else { print("no data is being requested in loadingRequest") let error = NSError(domain: AssetLoaderDelegate.errorDomain, code: -5, userInfo: nil) resourceLoadingRequest.finishLoading(with: error) NotificationCenter.default.post(name: Notification.Name.SambaDRMErrorNotification, object: nil) return } // Provide data to the loading request. dataRequest.respond(with: ckcData) resourceLoadingRequest.finishLoading() // Treat the processing of the request as complete. } } func shouldLoadOrRenewRequestedResource(resourceLoadingRequest: AVAssetResourceLoadingRequest) -> Bool { guard let url = resourceLoadingRequest.request.url else { print("No DRM URL request found!") return false } // AssetLoaderDelegate only should handle FPS Content Key requests. if url.scheme?.compare(AssetLoaderDelegate.customScheme, options: .regularExpression) == nil { print("Wrong DRM URL scheme: \(String(describing: url.scheme))") return false } resourceLoadingRequestQueue.async { self.prepareAndSendContentKeyRequest(resourceLoadingRequest: resourceLoadingRequest) } return true } } //MARK:- AVAssetResourceLoaderDelegate protocol methods extension extension AssetLoaderDelegate: AVAssetResourceLoaderDelegate { /* resourceLoader:shouldWaitForLoadingOfRequestedResource: When iOS asks the app to provide a CK, the app invokes the AVAssetResourceLoader delegate’s implementation of its -resourceLoader:shouldWaitForLoadingOfRequestedResource: method. This method provides the delegate with an instance of AVAssetResourceLoadingRequest, which accesses the underlying NSURLRequest for the requested resource together with support for responding to the request. */ public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { print("\(#function) was called in AssetLoaderDelegate with loadingRequest: \(loadingRequest)") return shouldLoadOrRenewRequestedResource(resourceLoadingRequest: loadingRequest) } /* resourceLoader: shouldWaitForRenewalOfRequestedResource: Delegates receive this message when assistance is required of the application to renew a resource previously loaded by resourceLoader:shouldWaitForLoadingOfRequestedResource:. For example, this method is invoked to renew decryption keys that require renewal, as indicated in a response to a prior invocation of resourceLoader:shouldWaitForLoadingOfRequestedResource:. If the result is YES, the resource loader expects invocation, either subsequently or immediately, of either -[AVAssetResourceRenewalRequest finishLoading] or -[AVAssetResourceRenewalRequest finishLoadingWithError:]. If you intend to finish loading the resource after your handling of this message returns, you must retain the instance of AVAssetResourceRenewalRequest until after loading is finished. If the result is NO, the resource loader treats the loading of the resource as having failed. Note that if the delegate's implementation of -resourceLoader:shouldWaitForRenewalOfRequestedResource: returns YES without finishing the loading request immediately, it may be invoked again with another loading request before the prior request is finished; therefore in such cases the delegate should be prepared to manage multiple loading requests. */ public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool { print("\(#function) was called in AssetLoaderDelegate with renewalRequest: \(renewalRequest)") return shouldLoadOrRenewRequestedResource(resourceLoadingRequest: renewalRequest) } }
134fbc86f725deccbb82a8278758daf3
45.529817
199
0.650614
false
false
false
false
jverkoey/swift-midi
refs/heads/master
LUMI/AudioGraph.swift
apache-2.0
1
import AudioToolbox public struct AudioNode { public init?(graph: AudioGraph, type: UInt32, subType: UInt32, manufacturer: UInt32) { var cd = AudioComponentDescription( componentType: OSType(type), componentSubType: OSType(subType), componentManufacturer: OSType(manufacturer), componentFlags: 0, componentFlagsMask: 0) var node: AUNode = 0 if AUGraphAddNode(graph.graph, &cd, &node) != noErr { return nil } self.graph = graph self.node = node var unit: AudioUnit = nil AUGraphNodeInfo(self.graph.graph, self.node, nil, &unit) self.unit = unit } public func connectTo(node: AudioNode) { AUGraphConnectNodeInput(self.graph.graph, self.node, 0, node.node, 0) } private let graph: AudioGraph private let node: AUNode public let unit: AudioUnit } public class AudioGraph { public init() { var graph: AUGraph = nil NewAUGraph(&graph) self.graph = graph AUGraphOpen(self.graph) } public func start() { AUGraphInitialize(self.graph) AUGraphStart(self.graph) } private var nodes: Set<AudioNode> = [] private let graph: AUGraph } extension AudioGraph { public func createMusicDeviceNode() -> AudioNode { let node = AudioNode( graph: self, type: kAudioUnitType_MusicDevice, subType: kAudioUnitSubType_DLSSynth, manufacturer: kAudioUnitManufacturer_Apple )! self.nodes.insert(node) return node } public func createDefaultOutputNode() -> AudioNode { let node = AudioNode( graph: self, type: kAudioUnitType_Output, subType: kAudioUnitSubType_DefaultOutput, manufacturer: kAudioUnitManufacturer_Apple )! self.nodes.insert(node) return node } } extension AudioNode : Hashable { public var hashValue: Int { return Int(self.node) } } public func ==(lhs: AudioNode, rhs: AudioNode) -> Bool { return lhs.graph.graph == rhs.graph.graph && lhs.node == rhs.node }
b94380c111c61539dabdeb3dbf1f872b
23.170732
88
0.676589
false
false
false
false
hooman/swift
refs/heads/main
test/Interop/Cxx/operators/member-inline-typechecker.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop import MemberInline var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs - rhs let resultCall0 = lhs() let resultCall1 = lhs(1) let resultCall2 = lhs(1, 2) var addressOnly = AddressOnlyIntWrapper(42) let addressOnlyResultCall0 = addressOnly() let addressOnlyResultCall1 = addressOnly(1) let addressOnlyResultCall2 = addressOnly(1, 2) var readWriteIntArray = ReadWriteIntArray() readWriteIntArray[2] = 321 let readWriteValue = readWriteIntArray[2] var readOnlyIntArray = ReadOnlyIntArray(3) let readOnlyValue = readOnlyIntArray[1] var writeOnlyIntArray = WriteOnlyIntArray() writeOnlyIntArray[2] = 654 let writeOnlyValue = writeOnlyIntArray[2] var diffTypesArray = DifferentTypesArray() let diffTypesResultInt: Int32 = diffTypesArray[0] let diffTypesResultDouble: Double = diffTypesArray[0.5] var nonTrivialIntArrayByVal = NonTrivialIntArrayByVal(3) let nonTrivialValueByVal = nonTrivialIntArrayByVal[1] var diffTypesArrayByVal = DifferentTypesArrayByVal() let diffTypesResultIntByVal: Int32 = diffTypesArrayByVal[0] let diffTypesResultDoubleByVal: Double = diffTypesArrayByVal[0.5]
8f9cd2b256a6840ca524f8fcdae58a11
30.102564
71
0.809563
false
false
false
false
henriquecfreitas/diretop
refs/heads/master
Diretop/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // Diretop // // Created by Henrique on 21/04/17. // Copyright © 2017 Henrique. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if (firstTimeRun()) { initializeDefaultSettings() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func firstTimeRun() -> Bool { return !UserDefaults.standard.bool(forKey: "alreadyInitializedDefaultSettings") } func initializeDefaultSettings() -> Void { UserDefaults.standard.set(true, forKey: "alreadyInitializedDefaultSettings") let speechTime = 90 let touchOnTimerLabel = true let alarmDuration = 2 let alarmTimeLeft = 5 let alarmIsActive = false let alarmVibration = true let delegationsList = Array<String>() let speechList = Array<String>() UserDefaults.standard.set(speechTime, forKey: "speechTime") UserDefaults.standard.set(touchOnTimerLabel, forKey: "touchOnTimerLabel") UserDefaults.standard.set(alarmIsActive, forKey: "alarmIsActive") UserDefaults.standard.set(alarmTimeLeft, forKey: "alarmTimeLeft") UserDefaults.standard.set(alarmDuration, forKey: "alarmDuration") UserDefaults.standard.set(alarmVibration, forKey: "alarmVibration") UserDefaults.standard.set(delegationsList, forKey: "delegationsList") UserDefaults.standard.set(speechList, forKey: "speechList") } }
e5b1dfd784d347ee4ac3578ec33518be
42.708861
285
0.714162
false
false
false
false
takeo-asai/math-puzzle
refs/heads/master
problems/42.swift
mit
1
extension Array { // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // // https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift // https://github.com/pNre/ExSwift/blob/master/LICENSE /** - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } return permutations } } private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0 let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } return endArray } func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]} var combinations: [[Element]] = [] let offset = self.count - indexes.count while true { var combination: [Element] = [] for index in indexes { combination.append(self[index]) } combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { i-- } if i < 0 { break } i++ let start = indexes[i-1] + 1 for j in (i-1)..<indexes.count { indexes[j] = start + j - i + 1 } } return combinations } /** - parameter length: The length of each permutations - returns: All of the permutations of this array of a given length, allowing repeats */ func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } var indexes: [[Int]] = [] indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes) return indexes.map({ $0.map({ i in self[i] }) }) } private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) { if seed.count == length { indexes.append(seed) return } for i in (0..<arrayLength) { var newSeed: [Int] = seed newSeed.append(i) self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes) } } } enum Expr { case Value(Int) case Plus case Minus case Multiply case Divide case Join func isPriorTo(expr: Expr) -> Bool { switch expr { case .Value(_): return true case .Plus: switch self { case .Value(_): return true default: return false } case .Minus: switch self { case .Value(_): return true default: return false } case .Multiply: switch self { case .Value(_), .Plus, .Minus: return true default: return false } case .Divide: switch self { case .Value(_), .Plus, .Minus: return true default: return false } case .Join: switch self { case .Value(_), .Plus, .Minus, .Multiply, .Divide: return true default: return false } } } func value() -> Int? { switch self { case .Value(let x): return x default: return nil } } func fun() -> (Int, Int) -> Int { switch self { case .Value(let x): return {_, _ in x} case .Plus: return {$0+$1} case .Minus: return {$0-$1} case .Multiply: return {$0*$1} case .Divide: return { if $1 == 0 { return 2147483647 } return $0/$1 } case .Join: return {$1*10+$0} } } } func calcReversePolish(var exprs: [Expr]) -> Int? { var stack: [Expr] = [] while !exprs.isEmpty { let expr = exprs.removeAtIndex(0) switch expr { case .Value(_): stack.insert(expr, atIndex: 0) default: let b = calcReversePolish([stack.removeAtIndex(0)])! let a = calcReversePolish([stack.removeAtIndex(0)])! stack.insert(.Value(expr.fun()(a, b)), atIndex: 0) } } return stack[0].value() } func convertToReversePolish(var exprs: [Expr]) -> [Expr] { var stack: [Expr] = [] var results: [Expr] = [] while !exprs.isEmpty { let expr = exprs.removeAtIndex(0) switch expr { case .Value(_): results.append(expr) default: if stack.count > 0 { while stack.count > 0 && expr.isPriorTo(stack[0]) { let drop = stack.removeAtIndex(0) results.append(drop) } stack.insert(expr, atIndex: 0) } else { stack.append(expr) } } } while stack.count > 0 { let drop = stack.removeAtIndex(0) results.append(drop) } return results } /* let exprs: [Expr] = [.Value(3), .Divide, .Value(5), .Plus, .Value(7)] //let exprs: [Expr] = [.Value(3), .Plus, .Value(5), .Join, .Value(7)] let reverse = convertToReversePolish(exprs) let ans = calcReversePolish(reverse) let exprs: [Expr] = [.Value(9), .Join, .Value(9), .Join, .Value(9), .Join, .Value(9), .Join, .Value(9)] let reverse = convertToReversePolish(exprs) let ans = calcReversePolish(reverse) print("rev: \(reverse)") print("ans: \(ans)") */ var n = 5 label: while true { for x in 0 ... 9 { let e: [Expr] = [.Plus, .Minus, .Multiply, .Divide, .Join] let xs = Array(count: n-1, repeatedValue: Expr.Value(x)) for es in e.repeatedPermutation(n-1) { let expr = zip(es, xs).reduce([Expr.Value(x)]) {$0+[$1.0]+[$1.1]} let reverse = convertToReversePolish(expr) let ans = calcReversePolish(reverse)! if ans == 1234 { print("n = \(n), x = \(x), \(expr)") break label } } } print("n=\(n), not found") n = n + 1 }
d48a340e33b4f1996c2a18a47d0729dd
27.223577
112
0.513035
false
false
false
false
JaSpa/swift
refs/heads/master
test/DebugInfo/generic_args.swift
apache-2.0
3
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir -verify -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} protocol AProtocol { func f() -> String } class AClass : AProtocol { func f() -> String { return "A" } } class AnotherClass : AProtocol { func f() -> String { return "B" } } // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction{{.*}}D",{{.*}} elements: ![[PROTOS:[0-9]+]] // CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]} // CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:[0-9]+]] // CHECK-DAG: ![[PROTOCOL]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9AProtocol_pmD", // CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]]) // CHECK-DAG: ![[T]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction // CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]]) // CHECK-DAG: ![[Q]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T012generic_args9aFunction func aFunction<T : AProtocol, Q : AProtocol>(_ x: T, _ y: Q, _ z: String) { markUsed("I am in \(z): \(x.f()) \(y.f())") } aFunction(AClass(),AnotherClass(),"aFunction") struct Wrapper<T: AProtocol> { init<U: AProtocol>(from : Wrapper<U>) { // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_T012generic_args7WrapperVyAcCyxGACyqd__G4from_tcAA9AProtocolRd__lufcQq_GD") var wrapped = from wrapped = from _ = wrapped } func passthrough(_ t: T) -> T { // The type of local should have the context Wrapper<T>. // CHECK-DAG: ![[WRAPPER:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args7WrapperVQq_D") // CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[WRAPPER]] var local = t local = t return local } } // CHECK-DAG: ![[FNTY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args5applyq_x_q_xc1ftr0_lFQq_AaBq_x_q_xcACtr0_lFQq0_Ixir_D" // CHECK-DAG: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: ![[FNTY]]) func apply<T, U> (_ x: T, f: (T) -> (U)) -> U { return f(x) }
7330e8b3b9f1d19f7f7c4e67c1d96e1c
40.886792
173
0.616667
false
false
false
false
IvanKalaica/GitHubSearch
refs/heads/master
GitHubSearch/GitHubSearch/ViewModel/MyProfileViewModel.swift
mit
1
// // MyProfileViewModel.swift // GitHubSearch // // Created by Ivan Kalaica on 24/09/2017. // Copyright © 2017 Kalaica. All rights reserved. // import Foundation import RxSwift import RxCocoa import RxFeedback enum State { case loggedIn(AuthenticatedUserViewModel) case loggedOut case authorizing var buttonTitle: String? { switch self { case .loggedIn: return NSLocalizedString("Logout", comment: "My profile logout button title") case .loggedOut: return NSLocalizedString("Login", comment: "My profile login button title") case .authorizing: return "" } } fileprivate typealias FeedbackLoop = (Driver<State>) -> Signal<Event> } fileprivate enum Event { case newData(AuthenticatedUserViewModel) case logOut case login } fileprivate extension State { static func reduce(state: State, event: Event) -> State { switch event { case .newData(let data): return .loggedIn(data) case .logOut: return .loggedOut case .login: return .authorizing } } } fileprivate func system( initialState: State, oAuthService: OAuthService, gitHubService: GitHubService, viewModels: ViewModels, toggleUser: Driver<()> ) -> Driver<State> { let currentUser = gitHubService .authenticatedUser() .map { Event.newData(viewModels.authenticatedUserViewModel(user: $0)) } let dataFeedbackLoop: State.FeedbackLoop = { state in return currentUser.asSignalIgnoringErrors() } let toggleUserFeedbackLoop: State.FeedbackLoop = { state in return toggleUser .withLatestFrom(state) .flatMapLatest { state in switch state { case .loggedIn: oAuthService.logout() return Signal.just(Event.logOut) case .loggedOut: return currentUser.asSignalIgnoringErrors() case .authorizing: return Signal.empty() } } } return Driver<Any>.system(initialState: initialState, reduce: State.reduce, feedback: dataFeedbackLoop, toggleUserFeedbackLoop) } protocol MyProfileViewModel { var state: Driver<State> { get } var toggleUser: PublishSubject<Void> { get } } struct DefaultMyProfileViewModel: MyProfileViewModel { let toggleUser: PublishSubject<Void> = PublishSubject<Void>() let state: Driver<State> init(oAuthService: OAuthService, gitHubService: GitHubService, viewModels: ViewModels) { self.state = system( initialState: .authorizing, oAuthService: oAuthService, gitHubService: gitHubService, viewModels: viewModels, toggleUser: self.toggleUser.asDriverIgnoringErrors() ) } }
eb6d5feb104369950599fc32e2450cb6
27.447619
92
0.614329
false
false
false
false
mlilback/rc2SwiftClient
refs/heads/master
MacClient/session/sidebar/SidebarFileController.swift
isc
1
// // SidebarFileController.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Cocoa import MJLLogger import ReactiveSwift import SwiftyUserDefaults import Rc2Common import Networking import Model class FileRowData: Equatable { var sectionName: String? var file: AppFile? init(name: String?, file: AppFile?) { self.sectionName = name self.file = file } static public func == (lhs: FileRowData, rhs: FileRowData) -> Bool { if lhs.sectionName != nil && lhs.sectionName == rhs.sectionName { return true } if rhs.file != nil && lhs.file != nil && lhs.file?.fileId == rhs.file?.fileId { return true } return false } } protocol FileViewControllerDelegate: class { func fileSelectionChanged(_ file: AppFile?, forEditing: Bool) } let FileDragTypes = [NSPasteboard.PasteboardType(kUTTypeFileURL as String)] let addFileSegmentIndex: Int = 0 let removeFileSegmentIndex: Int = 1 // swiftlint:disable type_body_length class SidebarFileController: AbstractSessionViewController, NSTableViewDataSource, NSTableViewDelegate, NSOpenSavePanelDelegate, NSMenuDelegate { // MARK: properties let sectionNames: [String] = ["Source Files", "Images", "Other"] @IBOutlet var tableView: NSTableView! @IBOutlet var addRemoveButtons: NSSegmentedControl? @IBOutlet var messageView: NSView? @IBOutlet var messageLabel: NSTextField? @IBOutlet var messageButtons: NSStackView? private var getInfoPopover: NSPopover? private var fileInfoController: FileInfoController? var rowData: [FileRowData] = [FileRowData]() weak var delegate: FileViewControllerDelegate? lazy var importPrompter: MacFileImportSetup? = { MacFileImportSetup() }() var fileImporter: FileImporter? private var fileChangeDisposable: Disposable? /// used to disable interface when window is busy private var busyDisposable: Disposable? fileprivate var selectionChangeInProgress = false fileprivate var formatMenu: NSMenu? var selectedFile: AppFile? { didSet { fileSelectionChanged() } } // MARK: - lifecycle override func awakeFromNib() { super.awakeFromNib() if addRemoveButtons != nil { let menu = NSMenu(title: "new document format") for (index, aType) in FileType.creatableFileTypes.enumerated() { let mi = NSMenuItem(title: aType.details ?? "unknown", action: #selector(addDocumentOfType(_:)), keyEquivalent: "") mi.representedObject = index menu.addItem(mi) } menu.autoenablesItems = false //NOTE: the action method of the menu item wasn't being called the first time. This works all times. NotificationCenter.default.addObserver(self, selector: #selector(addFileMenuAction(_:)), name: NSMenu.didSendActionNotification, object: menu) addRemoveButtons?.setMenu(menu, forSegment: 0) addRemoveButtons?.target = self formatMenu = menu } if tableView != nil { tableView.setDraggingSourceOperationMask(.copy, forLocal: true) tableView.setDraggingSourceOperationMask(.copy, forLocal: false) tableView.draggingDestinationFeedbackStyle = .none tableView.registerForDraggedTypes(FileDragTypes) } adjustForFileSelectionChange() } override func sessionChanged() { fileChangeDisposable?.dispose() fileChangeDisposable = session.workspace.fileChangeSignal.observe(on: UIScheduler()).take(during: session.lifetime).observe(on: UIScheduler()).observeValues(filesRefreshed) loadData() tableView.reloadData() if selectedFile != nil { fileSelectionChanged() } if rowData.count == 0 { messageView?.isHidden = false } else { messageView?.isHidden = true } } override func appStatusChanged() { // don't observe if session not set yet guard let session = sessionOptional else { return } busyDisposable = appStatus?.busySignal.observe(on: UIScheduler()).take(during: session.lifetime).observeValues { [weak self] isBusy in guard let tv = self?.tableView else { return } if isBusy { tv.unregisterDraggedTypes() } else { tv.registerForDraggedTypes(FileDragTypes) } } } func loadData() { guard let session = sessionOptional else { Log.warn("loadData called without a session", .app); return } var sectionedFiles = [[AppFile](), [AppFile](), [AppFile]()] for aFile in session.workspace.files.sorted(by: { $1.name > $0.name }) { if aFile.fileType.isSource { sectionedFiles[0].append(aFile) } else if aFile.fileType.isImage { sectionedFiles[1].append(aFile) } else { sectionedFiles[2].append(aFile) } } rowData.removeAll() for i in 0..<sectionNames.count where sectionedFiles[i].count > 0 { rowData.append(FileRowData(name: sectionNames[i], file: nil)) rowData.append(contentsOf: sectionedFiles[i].map({ return FileRowData(name: nil, file: $0) })) } } fileprivate func adjustForFileSelectionChange() { addRemoveButtons?.setEnabled(selectedFile != nil, forSegment: removeFileSegmentIndex) } @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let action = menuItem.action else { return false } switch action { case #selector(editFile(_:)): let fileName = selectedFile?.name ?? "" menuItem.title = String.localizedStringWithFormat(NSLocalizedString("Edit File", comment: ""), fileName) guard let file = selectedFile, file.fileSize <= MaxEditableFileSize else { return false } return file.fileType.isEditable case #selector(promptToImportFiles(_:)): return true case #selector(exportSelectedFile(_:)): return selectedFile != nil case #selector(exportAllFiles(_:)), #selector(exportZippedFiles(_:)): return true default: return false } } //as the delegate for the action menu, need to enable/disable items func menuNeedsUpdate(_ menu: NSMenu) { menu.items.forEach { item in guard let action = item.action else { return } switch action { case #selector(promptToImportFiles(_:)): item.isEnabled = true case #selector(editFile(_:)): item.isEnabled = selectedFile != nil && selectedFile!.fileSize <= MaxEditableFileSize default: item.isEnabled = selectedFile != nil } } } func fileDataIndex(fileId: Int) -> Int? { for (idx, data) in rowData.enumerated() where data.file?.fileId == fileId { return idx } return nil } // NSMenu calls this method before an item's action is called. we listen to it from the add button's menu @objc func addFileMenuAction(_ note: Notification) { guard let menuItem = note.userInfo?["MenuItem"] as? NSMenuItem, let index = menuItem.representedObject as? Int else { return } let fileType = FileType.creatableFileTypes[index] let prompt = NSLocalizedString("Filename:", comment: "") let baseName = NSLocalizedString("Untitled", comment: "default file name") DispatchQueue.main.async { self.promptForFilename(prompt: prompt, baseName: baseName, type: fileType) { (name) in guard let newName = name else { return } self.session.create(fileName: newName, contentUrl: self.fileTemplate(forType: fileType)) { result in // the id of the file that was created switch result { case .failure(let err): Log.error("error creating empty file: \(err)", .app) self.appStatus?.presentError(err, session: self.session) case .success(let fid): self.select(fileId: fid) } } } } } // MARK: - actions @IBAction func createFirstFile(_ sender: Any?) { guard let button = sender as? NSButton else { return } DispatchQueue.main.async { switch button.tag { case 0: self.promptToImportFiles(sender) case 1: self.formatMenu?.popUp(positioning: nil, at: NSPoint.zero, in: self.messageButtons) default: break } // NSAnimationContext.runAnimationGroup({ (context) in // context.allowsImplicitAnimation = true self.messageView?.animator().isHidden = true // }, completionHandler: nil) } // messageView?.isHidden = true } @IBAction func deleteFile(_ sender: Any?) { guard let file = selectedFile else { Log.error("deleteFile should never be called without selected file", .app) return } let defaults = UserDefaults.standard if defaults[.suppressDeleteFileWarnings] { self.actuallyPerformDelete(file: file) return } confirmAction(message: NSLocalizedString(LocalStrings.deleteFileWarning, comment: ""), infoText: String(format: NSLocalizedString(LocalStrings.deleteFileWarningInfo, comment: ""), file.name), buttonTitle: NSLocalizedString("Delete", comment: ""), defaultToCancel: true, suppressionKey: .suppressDeleteFileWarnings) { (confirmed) in guard confirmed else { return } self.actuallyPerformDelete(file: file) } } @IBAction func duplicateFile(_ sender: Any?) { guard let file = selectedFile else { Log.error("duplicateFile should never be called without selected file", .app) return } let prompt = NSLocalizedString("Filename:", comment: "") let baseName = NSLocalizedString("Untitled", comment: "default file name") DispatchQueue.main.async { self.promptForFilename(prompt: prompt, baseName: baseName, type: file.fileType) { (name) in guard let newName = name else { return } self.session.duplicate(file: file, to: newName) .updateProgress(status: self.appStatus!, actionName: "Duplicate \(file.name)") .startWithResult { result in // the id of the file that was created switch result { case .failure(let rerror): Log.error("error duplicating file: \(rerror)", .app) self.appStatus?.presentError(rerror, session: self.session) case .success(let fid): self.select(fileId: fid) } } } } } @IBAction func renameFile(_ sender: Any?) { guard let cellView = tableView.view(atColumn: 0, row: tableView.selectedRow, makeIfNecessary: false) as? EditableTableCellView else { Log.warn("renameFile: failed to get tableViewCell", .app) return } guard let file = cellView.objectValue as? AppFile else { Log.error("renameFile: no file for file cell view", .app) return } cellView.validator = { self.validateRename(file: file, newName: $0) } cellView.textField?.isEditable = true tableView.editColumn(0, row: tableView.selectedRow, with: nil, select: true) cellView.editText { value in cellView.textField?.isEditable = false cellView.textField?.stringValue = file.name guard var name = value else { return } if !name.hasSuffix(".\(file.fileType.fileExtension)") { name += ".\(file.fileType.fileExtension)" } self.session.rename(file: file, to: name) .updateProgress(status: self.appStatus!, actionName: "Rename \(file.name)") .startWithResult { result in if case .failure(let error) = result { Log.error("error duplicating file: \(error)", .app) self.appStatus?.presentError(error, session: self.session) return } self.select(fileId: file.fileId) } } } @IBAction func editFile(_ sender: Any) { delegate?.fileSelectionChanged(selectedFile, forEditing: true) } /// called to display info about a specific file @IBAction func inforForFile(_ sender: Any) { if getInfoPopover == nil { // setup the popup and view controller fileInfoController = FileInfoController() assert(fileInfoController != nil) getInfoPopover = NSPopover() getInfoPopover?.behavior = .transient getInfoPopover?.contentViewController = fileInfoController } // getInfoPopover!.contentSize = fileInfoController!.view.frame.size var rowIdx = -1 if let button = sender as? NSButton { // if the sender is a button, it's tag was set to the row index rowIdx = button.tag } else { rowIdx = tableView.selectedRow // otherwise, use selected row } guard rowIdx >= 0 && rowIdx < rowData.count else { Log.warn("invalid file for info", .app); return } fileInfoController?.file = rowData[rowIdx].file self.getInfoPopover?.show(relativeTo: tableView.rect(ofRow: rowIdx), of: tableView, preferredEdge: .maxX) } // never gets called, but file type menu items must have an action or addFileMenuAction never gets called @IBAction func addDocumentOfType(_ menuItem: NSMenuItem) { } @IBAction func segButtonClicked(_ sender: Any?) { switch addRemoveButtons!.selectedSegment { case addFileSegmentIndex: //should never be called since a menu is attached assertionFailure("segButtonClicked should never be called for addSegment") case removeFileSegmentIndex: deleteFile(sender) default: assertionFailure("unknown segment selected") } } @IBAction func promptToImportFiles(_ sender: Any?) { if nil == importPrompter { importPrompter = MacFileImportSetup() } importPrompter!.performFileImport(view.window!, workspace: session.workspace) { files in guard files != nil else { return } //user canceled import self.importFiles(files!) } } @IBAction func exportSelectedFile(_ sender: Any?) { let defaults = UserDefaults.standard let savePanel = NSSavePanel() savePanel.isExtensionHidden = false savePanel.allowedFileTypes = [(selectedFile?.fileType.fileExtension)!] savePanel.nameFieldStringValue = (selectedFile?.name)! if let bmarkData = defaults[.lastExportDirectory] { do { savePanel.directoryURL = try (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL) } catch { } } savePanel.beginSheetModal(for: view.window!) { result in do { let bmark = try (savePanel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) defaults[.lastExportDirectory] = bmark } catch let err as NSError { Log.error("why did we get error creating export bookmark: \(err)", .app) } savePanel.close() if result == .OK && savePanel.url != nil { do { try Foundation.FileManager.default.copyItem(at: self.session.fileCache.cachedUrl(file: self.selectedFile!), to: savePanel.url!) } catch let error as NSError { Log.error("failed to copy file for export: \(error)", .app) let alert = NSAlert(error: error) alert.beginSheetModal(for: self.view.window!, completionHandler: { (_) -> Void in //do nothing }) } } } } @IBAction func exportZippedFiles(_ sender: Any?) { let defaults = UserDefaults.standard let panel = NSSavePanel() panel.isExtensionHidden = false panel.allowedFileTypes = ["zip"] panel.nameFieldStringValue = session.workspace.name + ".zip" if let bmarkData = defaults[.lastExportDirectory] { do { panel.directoryURL = try (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL) } catch { } } panel.beginSheetModal(for: view.window!) { response in do { let urlbmark = try (panel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) defaults[.lastExportDirectory] = urlbmark } catch let err as NSError { Log.warn("why did we get error creating export bookmark: \(err)", .app) } panel.close() guard response == .OK, let destination = panel.url else { return } self.exportAll(to: destination) } } @IBAction func exportAllFiles(_ sender: Any?) { let defaults = UserDefaults.standard let panel = NSOpenPanel() panel.allowsMultipleSelection = false panel.canChooseDirectories = true panel.canChooseFiles = false panel.resolvesAliases = true panel.canCreateDirectories = true if let bmarkData = defaults[.lastExportDirectory] { panel.directoryURL = try? (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL) } panel.prompt = NSLocalizedString("Export All Files", comment: "") panel.message = NSLocalizedString("Select File Destination", comment: "") panel.beginSheetModal(for: view.window!) { response in do { let urlbmark = try (panel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) defaults[.lastExportDirectory] = urlbmark } catch let err as NSError { Log.warn("why did we get error creating export bookmark: \(err)", .app) } panel.close() guard response == .OK && panel.urls.count > 0, let destination = panel.urls.first else { return } self.exportAll(to: destination) } } // MARK: - private methods private func exportAll(to destination: URL) { let fm = FileManager() let zip = destination.pathExtension == "zip" var tmpDir: URL? let folderDest: URL if zip { do { tmpDir = try fm.createTemporaryDirectory() folderDest = tmpDir!.appendingPathComponent(destination.deletingPathExtension().lastPathComponent) try fm.createDirectory(at: folderDest, withIntermediateDirectories: true) } catch { appStatus?.presentError(Rc2Error(type: .cocoa, nested: nil, severity: .error, explanation: "Failed to create temporary directory"), session: session) return } } else { folderDest = destination } let urls = self.session.workspace.files.map { (self.session.fileCache.cachedUrl(file: $0), $0.name) } // use a producer to allow updating of progress let producer = SignalProducer<ProgressUpdate, Rc2Error> { observer, _ in var copiedCount: Double = 0 do { observer.send(value: ProgressUpdate(.start)) for (aUrl, fileName) in urls { observer.send(value: ProgressUpdate(.value, message: "Exporting \(fileName)", value: copiedCount / Double(urls.count), error: nil, disableInput: true)) let destUrl = folderDest.appendingPathComponent(fileName) if destUrl.fileExists() { try? fm.removeItem(at: destUrl) } try fm.copyItem(at: aUrl, to: destUrl) copiedCount += 1.0 } if zip { // need to compress destFolder to a zip file // TODO: map progress: argument to a Progress object that will be updating observer do { try fm.zipItem(at: folderDest, to: destination, shouldKeepParent: true, compressionMethod: .deflate, progress: nil) } catch { Log.error("error zipping export: \(error)") throw Rc2Error(type: .application, nested: error, severity: .error, explanation: "failed to zip files") } } observer.sendCompleted() } catch let error as NSError { observer.send(error: Rc2Error(type: .cocoa, nested: error, explanation: "Error exporting file: \(error)")) Log.error("failed to copy file for export: \(error)", .app) } catch let rc2error as Rc2Error { observer.send(error: rc2error) } if let tdir = tmpDir { do { try fm.removeItem(at: tdir) } catch { Log.warn("failed to delete temporary directory") } } } DispatchQueue.global(qos: .userInitiated).async { producer .updateProgress(status: self.appStatus!, actionName: NSLocalizedString("Export Files", comment: "")) .start() } } fileprivate func select(fileId: Int) { // the id of the file that was created guard let fidx = self.fileDataIndex(fileId: fileId) else { Log.warn("selecting unknown file \(fileId)", .app) return } tableView.selectRowIndexes(IndexSet(integer: fidx), byExtendingSelection: false) } fileprivate func actuallyPerformDelete(file: AppFile) { self.session.remove(file: file) .updateProgress(status: self.appStatus!, actionName: "Delete \(file.name)") .startWithResult { result in DispatchQueue.main.async { switch result { case .failure(let error): self.appStatus?.presentError(error, session: self.session) case .success: self.delegate?.fileSelectionChanged(nil, forEditing: false) } } } } /// prompts for a filename /// /// - Parameters: /// - prompt: label shown to user /// - baseName: base file name (without extension) /// - type: the type of file being prompted for /// - handler: called when complete. If value is nil, the user canceled the prompt private func promptForFilename(prompt: String, baseName: String, type: FileType, handler: @escaping (String?) -> Void) { let fileExtension = ".\(type.fileExtension)" let prompter = InputPrompter(prompt: prompt, defaultValue: baseName + fileExtension, suffix: fileExtension) prompter.minimumStringLength = type.fileExtension.count + 1 let fileNames = session.workspace.files.map { return $0.name } prompter.validator = { (proposedName) in return fileNames.filter({ $0.caseInsensitiveCompare(proposedName) == .orderedSame }).count == 0 } prompter.prompt(window: self.view.window!) { (gotValue, value) in guard gotValue, var value = value else { handler(nil); return } if !value.hasSuffix(fileExtension) { value += fileExtension } handler(value) } } private func validateRename(file: AppFile, newName: String?) -> Bool { guard var name = newName else { return true } //empty is allowable if !name.hasSuffix(".\(file.fileType.fileExtension)") { name += ".\(file.fileType.fileExtension)" } guard name.count > 3 else { return false } //if same name, is valid guard name.caseInsensitiveCompare(file.name) != .orderedSame else { return true } //no duplicate names let fileNames = session.workspace.files.map { return $0.name } guard fileNames.filter({ $0.caseInsensitiveCompare(name) == .orderedSame }).count == 0 else { return false } return true } private func importFiles(_ files: [FileImporter.FileToImport]) { let converter = { (iprogress: FileImporter.ImportProgress) -> ProgressUpdate? in return ProgressUpdate(.value, message: iprogress.status, value: iprogress.percentComplete) } do { fileImporter = try FileImporter(files, fileCache: self.session.fileCache, connectInfo: session.conInfo) } catch { let myError = Rc2Error(type: .file, nested: error) appStatus?.presentError(myError, session: session) return } //save reference so ARC doesn't dealloc importer fileImporter!.producer() .updateProgress(status: appStatus!, actionName: "Import", determinate: true, converter: converter) .start { [weak self] event in switch event { case .failed(let error): var message = error.localizedDescription if let neterror = error.nestedError { message = neterror.localizedDescription } Log.error("got import error \(message)", .app) self?.fileImporter = nil //free up importer case .completed: NotificationCenter.default.post(name: .filesImported, object: self?.fileImporter!) self?.fileImporter = nil //free up importer case .interrupted: Log.info("import canceled", .app) self?.fileImporter = nil //free up importer default: break } } } /// returns URL to template for the passed in file type func fileTemplate(forType fileType: FileType) -> URL? { do { let templateDir = try AppInfo.subdirectory(type: .applicationSupportDirectory, named: Resources.fileTemplateDirName) let userFile = templateDir.appendingPathComponent("default.\(fileType.fileExtension)") if FileManager.default.fileExists(atPath: userFile.path) { return userFile } } catch { // ignore error, just use builtin template } return Bundle(for: type(of: self)).url(forResource: "default", withExtension: fileType.fileExtension, subdirectory: Resources.fileTemplateDirName) } // MARK: - TableView datasource/delegate implementation func numberOfRows(in tableView: NSTableView) -> Int { return rowData.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let data = rowData[row] if data.sectionName != nil { // swiftlint:disable:next force_cast let tview = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "string"), owner: nil) as! NSTableCellView tview.textField!.stringValue = data.sectionName! return tview } else { // swiftlint:disable:next force_cast let fview = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "file"), owner: nil) as! EditableTableCellView fview.objectValue = data.file fview.textField?.stringValue = data.file!.name fview.infoButton?.tag = row return fview } } func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool { return rowData[row].sectionName != nil } func tableViewSelectionDidChange(_ notification: Notification) { if tableView.selectedRow >= 0 { selectedFile = rowData[tableView.selectedRow].file } else { selectedFile = nil } adjustForFileSelectionChange() delegate?.fileSelectionChanged(selectedFile, forEditing: false) } func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { return rowData[row].file != nil } func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool { guard let row = rowIndexes.last, let file = rowData[row].file else { return false } let url = session.fileCache.cachedUrl(file: file) as NSURL pboard.declareTypes(url.writableTypes(for: pboard), owner: nil) url.write(to: pboard) return true } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { return importPrompter!.validateTableViewDrop(info) } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool { importPrompter!.acceptTableViewDrop(info, workspace: session.workspace, window: view.window!) { (files) in self.importFiles(files) } return true } } // MARK: - FileHandler implementation extension SidebarFileController: FileHandler { func filesRefreshed(_ changes: [AppWorkspace.FileChange]) { //TODO: ideally should figure out what file was changed and animate the tableview update instead of refreshing all rows loadData() //preserve selection let selFile = selectedFile tableView.reloadData() if selFile != nil, let idx = rowData.index(where: { $0.file?.fileId ?? -1 == selFile!.fileId }) { tableView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false) } } func fileSelectionChanged() { guard !selectionChangeInProgress else { return } selectionChangeInProgress = true // defer { selectionChangeInProgress = false } guard let file = selectedFile else { DispatchQueue.main.async { self.tableView.selectRowIndexes(IndexSet(), byExtendingSelection: false) self.selectionChangeInProgress = false } return } guard let idx = fileDataIndex(fileId: file.fileId) else { Log.info("failed to find file to select", .app) self.selectionChangeInProgress = false return } DispatchQueue.main.async { self.tableView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false) self.selectionChangeInProgress = false } } } // MARK: - Accessory Classes //least hackish way to get segment's menu to show immediately if set, otherwise perform control's action class AddRemoveSegmentedCell: NSSegmentedCell { override var action: Selector? { get { if self.menu(forSegment: self.selectedSegment) != nil { return nil } return super.action! } set { super.action = newValue } } } class FileTableView: NSTableView { override func menu(for event: NSEvent) -> NSMenu? { let row = self.row(at: convert(event.locationInWindow, from: nil)) if row != -1 { //if right click is over a row, select that row selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) } return super.menu(for: event) } }
a5a96ce023d626fbb09f070793f641a8
36.253061
181
0.715204
false
false
false
false
eeschimosu/LicensingViewController
refs/heads/master
LicensingViewController/LicensingItemCell.swift
mit
1
// // LicensingItemCell.swift // LicensingViewController // // Created by Tiago Henriques on 15/07/15. // Copyright (c) 2015 Tiago Henriques. All rights reserved. // import UIKit class LicensingItemCell: UITableViewCell { // MARK: - Constants let spacing = 15 // MARK: - Properties let titleLabel = UILabel() let noticeLabel = UILabel() // MARK: - Lifecycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = "" noticeLabel.text = "" } // MARK: - Views func setupSubviews() { titleLabel.numberOfLines = 0 titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) noticeLabel.numberOfLines = 0 noticeLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(noticeLabel) self.setNeedsUpdateConstraints() } override func updateConstraints() { super.updateConstraints() let views = [ "titleLabel": titleLabel, "noticeLabel": noticeLabel ] let metrics = [ "spacing": spacing ] contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-spacing-[titleLabel]-spacing-|", options: [], metrics: metrics, views: views )) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-spacing-[titleLabel]-[noticeLabel]-spacing-|", options: [], metrics: metrics, views: views )) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-spacing-[noticeLabel]-spacing-|", options: [], metrics: metrics, views: views )) } }
2aa85b42878588715551e3e3dd391950
22.855556
133
0.61388
false
false
false
false
Swerfvalk/SwerfvalkExtensionKit
refs/heads/master
Source/UIImageExtension.swift
mit
1
// // UIImageExtension.swift // SwerfvalkExtensionKit // // Created by 萧宇 on 14/08/2017. // Copyright © 2017 Swerfvalk. All rights reserved. // import UIKit public extension UIImage { /// Creates an image with a color. /// /// - Parameters: /// - color: The color for the image. /// - size: The size of the image. public convenience init(color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) { var imageSize = size if !(size.width > 0 && size.height > 0) { imageSize = CGSize(width: 1.0, height: 1.0) log("The size<\(size)> is not a correct size, use size<\(imageSize)> instead") } let rect = CGRect(x: 0.0, y: 0.0, width: imageSize.width, height: imageSize.height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: (image?.cgImage)!) } /// Resize an image with scale. /// /// - Parameters: /// - image: The original image. /// - scale: The scale to resize. /// - Returns: The resized image. public class func resize(_ image: UIImage, toScale scale: CGFloat) -> UIImage { UIGraphicsBeginImageContext(CGSize(width: image.size.width * scale, height: image.size.height * scale)) image.draw(in: CGRect(x: 0.0, y: 0.0, width: image.size.width * scale, height: image.size.height * scale)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage! } /// Resize an image with new size. /// /// - Parameters: /// - image: The original image. /// - size: The new size of the image. /// - Returns: the resized image. public class func resize(_ image: UIImage, to size: CGSize) -> UIImage { UIGraphicsBeginImageContext(CGSize(width: size.width, height: size.height)) image.draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage! } }
bac995414d897e32b19f18a0bcc8c340
36.349206
114
0.61921
false
false
false
false
ethanneff/organize
refs/heads/master
Organize/ListViewController.swift
mit
1
import UIKit import MessageUI import Firebase import GoogleMobileAds class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate, ListTableViewCellDelegate, SettingsDelegate, ReorderTableViewDelegate,GADBannerViewDelegate { // MARK: - properties private var notebook: Notebook lazy var tableView: UITableView = ReorderTableView() weak var menuDelegate: MenuViewController? private var addButton: UIButton! private var bannerAd: GADBannerView! private var bannerAdHeight: CGFloat = 50 private var tableViewBottomConstraint: NSLayoutConstraint! private var addButtonBottomPadding: CGFloat = Constant.Button.padding*2 private var addButtonBottomConstraint: NSLayoutConstraint! lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(tableViewRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged) refreshControl.tintColor = Constant.Color.title.colorWithAlphaComponent(0.5) return refreshControl }() // MARK: - init init() { notebook = Notebook(title: "") super.init(nibName: nil, bundle: nil) initialize() } required init?(coder aDecoder: NSCoder) { fatalError("init coder not implemented") } private func initialize() { loadNotebook() loadListeners() createBannerAd() createTableView() createAddButton() createGestures() } // MARK: - deinit deinit { print("list deinit)") NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillTerminateNotification, object: nil) // FIXME: dismiss viewcontollor does not call deinit (reference cycle) (has to do with menu) } // MARK: - error override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - appear override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // session loadSession() // config loadRemoteConfig() // title updateTitle() // accessed Remote.User.open() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // shake becomeFirstResponder() } // MARK: - load internal func applicationDidBecomeActiveNotification() { // update reminder icons tableView.reloadData() } internal func applicationDidBecomeInactiveNotification() { Remote.Auth.upload(notebook: notebook) } private func loadNotebook() { Notebook.get { data in if let data = data { Util.threadMain { self.notebook = data self.tableView.reloadData() self.updateTitle() } } else { self.displayLogout() } } } private func loadListeners() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeInactiveNotification), name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeInactiveNotification), name: UIApplicationWillTerminateNotification, object: nil) } private func loadSession() { let reviewCount = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewCount) as? Int ?? 0 Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewCount, val: reviewCount+1) } private func loadRemoteConfig() { Remote.Config.fetch { config in if let config = config { // ads if let user = Remote.Auth.user { // FIXME: remove hardcode in place for user check if paid if user.email != "[email protected]" && config[Remote.Config.Keys.ShowAds.rawValue].boolValue { self.loadBannerAd() } } // review let feedbackApp = Constant.UserDefault.get(key: Constant.UserDefault.Key.FeedbackApp) as? Bool ?? false let reviewApp = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewApp) as? Bool ?? false let reviewCount = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewCount) as? Int ?? 0 let reviewCountConfig = config[Remote.Config.Keys.ShowReview.rawValue].numberValue as? Int ?? 0 if !(reviewApp || feedbackApp) && reviewCount > reviewCountConfig { self.displayReview() } } } } // MARK: - create private func createBannerAd() { bannerAd = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) view.addSubview(bannerAd) bannerAd.delegate = self bannerAd.rootViewController = self bannerAd.adUnitID = Constant.App.firebaseBannerAdUnitID bannerAd.translatesAutoresizingMaskIntoConstraints = false bannerAd.backgroundColor = Constant.Color.background NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: bannerAd, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: bannerAdHeight), NSLayoutConstraint(item: bannerAd, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: bannerAd, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: bannerAd, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0), ]) } private func createTableView() { // add view.addSubview(tableView) // delegates tableView.delegate = self tableView.dataSource = self if let tableView = tableView as? ReorderTableView { tableView.reorderDelegate = self } // cell tableView.registerClass(ListTableViewCell.self, forCellReuseIdentifier: ListTableViewCell.identifier) // refresh tableView.addSubview(refreshControl) // color tableView.backgroundColor = Constant.Color.background // borders tableView.contentInset = UIEdgeInsetsZero tableView.separatorInset = UIEdgeInsetsZero tableView.separatorColor = Constant.Color.border tableView.scrollIndicatorInsets = UIEdgeInsetsZero tableView.tableFooterView = UIView(frame: CGRect.zero) if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } tableView.layoutMargins = UIEdgeInsetsZero // constraints tableView.translatesAutoresizingMaskIntoConstraints = false tableViewBottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: tableView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: tableView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0), tableViewBottomConstraint, ]) } private func createAddButton() { let button = UIButton() let buttonSize = Constant.Button.height*1.33 let image = UIImage(named: "icon-add")! let imageView = Util.imageViewWithColor(image: image, color: Constant.Color.background) view.addSubview(button) button.layer.cornerRadius = buttonSize/2 // TODO: make shadow same as menu button.layer.shadowColor = UIColor.blackColor().CGColor button.layer.shadowOffset = CGSizeMake(0, 2) button.layer.shadowOpacity = 0.2 button.layer.shadowRadius = 2 button.layer.masksToBounds = false button.backgroundColor = Constant.Color.button button.tintColor = Constant.Color.background button.setImage(imageView.image, forState: .Normal) button.setImage(imageView.image, forState: .Highlighted) button.addTarget(self, action: #selector(addButtonPressed(_:)), forControlEvents: .TouchUpInside) addButtonBottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -addButtonBottomPadding) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -addButtonBottomPadding), addButtonBottomConstraint, NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: buttonSize), NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: buttonSize), ]) addButton = button } private func createGestures() { // double tap let gestureDoubleTap = UITapGestureRecognizer(target: self, action: #selector(gestureRecognizedDoubleTap(_:))) gestureDoubleTap.numberOfTapsRequired = 2 gestureDoubleTap.numberOfTouchesRequired = 1 tableView.addGestureRecognizer(gestureDoubleTap) // single tap let gestureSingleTap = UITapGestureRecognizer(target: self, action: #selector(gestureRecognizedSingleTap(_:))) gestureSingleTap.numberOfTapsRequired = 1 gestureSingleTap.numberOfTouchesRequired = 1 gestureSingleTap.requireGestureRecognizerToFail(gestureDoubleTap) tableView.addGestureRecognizer(gestureSingleTap) } private func updateTitle() { if let controller = self.navigationController?.childViewControllers.first { controller.navigationItem.title = notebook.title } } // MARK: - banner private func loadBannerAd() { let request = GADRequest() request.testDevices = Constant.App.firebaseTestDevices bannerAd.loadRequest(request) } internal func adViewDidReceiveAd(bannerView: GADBannerView!) { displayBannerAd(show: true) } internal func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) { Report.sharedInstance.log("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } private func displayBannerAd(show show: Bool) { tableViewBottomConstraint.constant = show ? -bannerAdHeight : 0 addButtonBottomConstraint.constant = show ? -bannerAdHeight-addButtonBottomPadding : 0 UIView.animateWithDuration(0.3, animations: { self.view.layoutIfNeeded() }) } // MARK: - tableview datasource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { addButton?.hidden = notebook.display.count > 0 return notebook.display.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ListTableViewCell.height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ListTableViewCell.identifier, forIndexPath: indexPath) as! ListTableViewCell cell.delegate = self cell.updateCell(note: notebook.display[indexPath.row]) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // fixes separator disappearing tableView.deselectRowAtIndexPath(indexPath, animated: false) tableView.separatorStyle = .None; tableView.separatorStyle = .SingleLine } // MARK: - refresh func tableViewRefresh(refreshControl: UIRefreshControl) { if !Constant.App.release { notebook = Notebook.getDefault() // notebook.display = notebook.notes refreshControl.endRefreshing() tableView.reloadData() return } let modal = ModalConfirmation() modal.trackButtons = true modal.message = "Download from cloud and overwrite data on device?" modal.show(controller: self, dismissible: true) { (output) in refreshControl.endRefreshing() if let selection = output[ModalConfirmation.OutputKeys.Selection.rawValue] as? Int where selection == 1 { Remote.Auth.download(controller: self) { (error) in if let error = error { let modal = ModalError() modal.message = error modal.show(controller: self) return } self.loadNotebook() } } } } // MARK - swipe func cellSwiped(type type: SwipeType, cell: UITableViewCell) { Util.playSound(systemSound: .Tap) if let indexPath = tableView.indexPathForCell(cell) { switch type { case .Complete: notebook.complete(indexPath: indexPath, tableView: tableView) case .Indent: notebook.indent(indexPath: indexPath, tableView: tableView) case .Reminder: displayReminder(indexPath: indexPath) case .Uncomplete: notebook.uncomplete(indexPath: indexPath, tableView: tableView) case .Unindent: notebook.unindent(indexPath: indexPath, tableView: tableView) case .Delete: displayDeleteCell(indexPath: indexPath) } } } // MARK: - reorder func reorderBeforeLift(fromIndexPath: NSIndexPath, completion: () -> ()) { notebook.reorderBeforeLift(indexPath: fromIndexPath, tableView: tableView) { completion() } Util.playSound(systemSound: .Tap) } func reorderAfterLift(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) { notebook.reorderAfterLift(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) { completion() } } func reorderDuringMove(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) { notebook.reorderDuringMove(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) { completion() } } func reorderAfterDrop(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) { notebook.reorderAfterDrop(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath, tableView: tableView) { completion() } Util.playSound(systemSound: .Tap) } // MARK: - gestures func gestureRecognizedSingleTap(gesture: UITapGestureRecognizer) { let location = gesture.locationInView(tableView) if let indexPath = tableView.indexPathForRowAtPoint(location), cell = tableView.cellForRowAtIndexPath(indexPath) { Util.animateButtonPress(button: cell) displayNoteDetail(indexPath: indexPath, create: false) } } func gestureRecognizedDoubleTap(gesture: UITapGestureRecognizer) { let location = gesture.locationInView(tableView) if let indexPath = tableView.indexPathForRowAtPoint(location) { let item = notebook.display[indexPath.row] if item.collapsed { notebook.uncollapse(indexPath: indexPath, tableView: tableView) } else { notebook.collapse(indexPath: indexPath, tableView: tableView) } Util.playSound(systemSound: .Tap) } } // MARK: - shake override func canBecomeFirstResponder() -> Bool { return true } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if let event = event where event.subtype == .MotionShake { displayDeleteCompleted() } } // MARK: - buttons func settingsButtonPressed(button button: SettingViewController.Button) { switch button.detail { case .NotebookTitle: displayNotebookTitle() case .NotebookCollapse: notebook.collapseAll(tableView: tableView) case .NotebookUncollapse: notebook.uncollapseAll(tableView: tableView) case .NotebookHideReminder: displayToggleReminders(button: button) case .NotebookDeleteCompleted: displayDeleteCompleted() case .AppTutorial: displayAppTutorial() case .AppTimer: displayAppTimer(button: button) case .AppColor: displayAppColor() case .AppFeedback: displayAppFeedback() case .AppShare: displayAppShare() case .AccountEmail: displayAccountEmail() case .AccountPassword: displayAccountPassword() case .AccountDelete: displayAccountDelete() case .AccountLogout: attemptLogout() default: break } } private func displayToggleReminders(button button: SettingViewController.Button) { updateSettingsMenuButtonTitle(button: button, userDefaultRawKey: Constant.UserDefault.Key.IsRemindersHidden.rawValue) } func cellAccessoryButtonPressed(cell cell: UITableViewCell) { if let indexPath = tableView.indexPathForCell(cell) { let item = notebook.display[indexPath.row] if item.collapsed { notebook.uncollapse(indexPath: indexPath, tableView: tableView) } else { displayNoteDetail(indexPath: NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section), create: true) } } } func addButtonPressed(button: UIButton) { Util.animateButtonPress(button: button) displayNoteDetail(indexPath: NSIndexPath(forRow: 0, inSection: 0), create: true) } private func displayLogout() { let modal = ModalError() modal.message = "An error has occured and you will need to log back in" modal.show(controller: self) { output in self.logout() } } private func attemptLogout() { Remote.Auth.logout(controller: self, notebook: notebook) { error in if let error = error { let modal = ModalError() modal.message = error modal.show(controller: self) return } self.logout() } } private func logout() { Util.threadBackground { LocalNotification.sharedInstance.destroy() } Report.sharedInstance.track(event: "logout") dismissViewControllerAnimated(true, completion: nil) } // MARK: - modals private func displayNotebookTitle() { let modal = ModalTextField() modal.limit = 20 modal.placeholder = notebook.title modal.show(controller: self, dismissible: true) { output in if let title = output[ModalTextField.OutputKeys.Text.rawValue] as? String { self.notebook.title = title self.updateTitle() } } } private func displayReview() { Report.sharedInstance.track(event: "show_review") let modal = ModalReview() modal.show(controller: self) { output in if let selection = output[ModalReview.OutputKeys.Selection.rawValue] as? Int { Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewCount, val: 0) let modal = ModalConfirmation() if selection >= 3 { modal.message = "Can you help us by leaving a review?" modal.show(controller: self) { output in Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewApp, val: true) Report.sharedInstance.track(event: "sent_review") UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/app/?id=" + Constant.App.id)!) } } else { modal.message = "Can you tell us how we can improve?" modal.show(controller: self) { output in self.displayAppFeedback() } } } } } private func displayAppTutorial() { let modal = ModalTutorial() modal.show(controller: self, dismissible: true) } private func updateSettingsMenuButtonTitle(button button: SettingViewController.Button, userDefaultRawKey: String) { if let key = Constant.UserDefault.Key(rawValue: userDefaultRawKey) { let hide: Bool = Constant.UserDefault.get(key: key) as? Bool ?? false Constant.UserDefault.set(key: key, val: !hide) button.button.setTitle(button.detail.title, forState: .Normal) } } private func displayAppTimer(button button: SettingViewController.Button) { guard let navigationController = navigationController as? MenuNavigationController else { return Report.sharedInstance.log("unable to get the correct parent navigation controller of MenuNavigationController") } // handle alert text let timer = navigationController.timer let modal = ModalConfirmation() modal.message = timer.state == .On || timer.state == .Paused ? "Pomodoro Timer" : "Create a Pomodoro Timer to track your productivity?" modal.left = timer.state == .On ? "Stop" : timer.state == .Paused ? "Stop" : "Cancel" modal.right = timer.state == .On ? "Pause" : timer.state == .Paused ? "Resume" : "Start" modal.trackButtons = true modal.show(controller: self, dismissible: true) { output in if let selection = output[ModalConfirmation.OutputKeys.Selection.rawValue] as? Int { // operate timer if selection == 1 { switch timer.state { case .On: timer.pause() case .Off: timer.start() case .Paused: timer.start() } } else { switch timer.state { case .On, .Paused: timer.stop() case .Off: break } } // change settings side menu title let on = navigationController.timer.state != .Off let active = Constant.UserDefault.get(key: Constant.UserDefault.Key.IsTimerActive) as? Bool ?? false if on != active { Constant.UserDefault.set(key: Constant.UserDefault.Key.IsTimerActive, val: navigationController.timer.state != .Off) button.button.setTitle(button.detail.title, forState: .Normal) } } } } private func displayAppColor() { Constant.Color.toggleColor() dismissViewControllerAnimated(true, completion: nil) } private func displayDeleteCompleted() { if notebook.hasCompleted { let modal = ModalConfirmation() modal.message = "Permanently delete all completed?" modal.show(controller: self, dismissible: false) { (output) in self.notebook.deleteCompleted(tableView: self.tableView) } } } private func displayDeleteCell(indexPath indexPath: NSIndexPath) { let modal = ModalConfirmation() modal.message = "Permanently delete?" modal.show(controller: self, dismissible: false) { (output) in self.notebook.delete(indexPath: indexPath, tableView: self.tableView) } } private func displayReminder(indexPath indexPath: NSIndexPath) { let note = notebook.display[indexPath.row] if !note.completed { let modal = ModalReminder() modal.reminder = note.reminder ?? nil modal.show(controller: self, dismissible: true, completion: { (output) in if let id = output[ModalReminder.OutputKeys.ReminderType.rawValue] as? Int, let reminderType = ReminderType(rawValue: id) { if reminderType == .None { return } if reminderType == .Date { if let reminder = self.notebook.display[indexPath.row].reminder where reminder.type == .Date && reminder.date.timeIntervalSinceNow > 0 { // delete custom date self.createReminder(indexPath: indexPath, type: reminderType, date: nil) } else { // create custom date self.displayReminderDatePicker(indexPath: indexPath) } } else { // delete and create select date self.createReminder(indexPath: indexPath, type: reminderType, date: nil) } } }) } } private func displayReminderDatePicker(indexPath indexPath: NSIndexPath) { let modal = ModalDatePicker() modal.show(controller: self, dismissible: true) { (output) in if let date = output[ModalDatePicker.OutputKeys.Date.rawValue] as? NSDate { self.createReminder(indexPath: indexPath, type: .Date, date: date) } } } private func createReminder(indexPath indexPath: NSIndexPath, type: ReminderType, date: NSDate?) { notebook.reminder(indexPath: indexPath, controller: self, tableView: tableView, reminderType: type, date: date) { success, create in if success {} } } private func displayAppFeedback() { if MFMailComposeViewController.canSendMail() { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.setToRecipients(["[email protected]"]) mail.setSubject("I have feedback for your Organize app!") mail.setMessageBody("<p>Hey Ethan,</p></br>", isHTML: true) presentViewController(mail, animated: true, completion: nil) } else { let modal = ModalError() modal.message = "Please check your email configuration and try again" modal.show(controller: self) } } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) Util.playSound(systemSound: .Tap) if result.rawValue == 2 { Constant.UserDefault.set(key: Constant.UserDefault.Key.FeedbackApp, val: true) Report.sharedInstance.track(event: "sent_feedback") } } private func displayAppShare() { let shareContent: String = "Check out this app!\n\nI've been using it quite a bit and I think you'll like it too. Tell me what you think.\n\n" + Constant.App.deepLinkUrl let activityViewController: ActivityViewController = ActivityViewController(activityItems: [shareContent], applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop] presentViewController(activityViewController, animated: true, completion: nil) } private func displayAccountEmail() { let modal = ModalTextField() modal.placeholder = Remote.Auth.user?.email ?? "new email" modal.keyboardType = .EmailAddress modal.show(controller: self, dismissible: true) { (output) in if let email = output[ModalTextField.OutputKeys.Text.rawValue] as? String where email.isEmail { Remote.Auth.changeEmail(controller: self, email: email, completion: { error in // FIXME: catch error 17014 and force logout? (minor) // FIXME: if no wifi on simulator, causes a flash in modals because loading.hide happens before loading.show finshes (minor) let message = error ?? "Log back in with your new email" let modal = ModalError() modal.message = message modal.show(controller: self) { (output) in if let _ = error { // close } else { self.attemptLogout() } } }) } else { let modal = ModalError() modal.message = AccessBusinessLogic.ErrorMessage.EmailInvalid.message modal.show(controller: self) { (output) in // FIXME: pass previous text through self.displayAccountEmail() } } } } private func displayAccountPassword() { let modal = ModalTextField() modal.placeholder = "new password" modal.secureEntry = true modal.show(controller: self, dismissible: true) { (output) in if let password = output[ModalTextField.OutputKeys.Text.rawValue] as? String where password.isPassword { Remote.Auth.changePassword(controller: self, password: password, completion: { error in let message = error ?? "Log back in with your new email" let modal = ModalError() modal.message = message modal.show(controller: self) { (output) in if let _ = error { // close } else { self.attemptLogout() } } }) } else { let modal = ModalError() modal.message = AccessBusinessLogic.ErrorMessage.PasswordInvalid.message modal.show(controller: self, dismissible: true) { (output) in self.displayAccountEmail() } } } } private func displayAccountDelete() { let modal = ModalConfirmation() modal.message = "Permanently delete account and all data related to it?" modal.show(controller: self, dismissible: true) { (output) in Remote.Auth.delete(controller: self, completion: { (error) in if let error = error { let modal = ModalError() modal.message = error modal.show(controller: self) } else { self.logout() } }) } } private func displayUndo() { let modal = ModalConfirmation() modal.message = "Undo last action?" modal.show(controller: self, dismissible: false) { (output) in self.notebook.undo(tableView: self.tableView) } } private func displayNoteDetail(indexPath indexPath: NSIndexPath, create: Bool) { let note: Note? = create ? nil : notebook.display[indexPath.row] let modal = ModalNoteDetail() modal.note = note modal.show(controller: self, dismissible: false) { (output) in if let note = output[ModalNoteDetail.OutputKeys.Note.rawValue] as? Note { if create { self.notebook.create(indexPath: indexPath, tableView: self.tableView, note: note) } else { self.notebook.update(indexPath: indexPath, tableView: self.tableView, note: note) } } } } }
47493486a696cd65045dbf04780a5c26
38.076316
218
0.691551
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ChartAnnotations/AnnotationsChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // AnnotationsChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class AnnotationsChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) let yAxis = SCINumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) // Watermark let watermark = SCITextAnnotation() watermark.coordinateMode = .relative watermark.x1 = SCIGeneric(0.5) watermark.y1 = SCIGeneric(0.5) watermark.text = "Create \n Watermarks" watermark.horizontalAnchorPoint = .center watermark.verticalAnchorPoint = .center watermark.style.textColor = UIColor.fromARGBColorCode(0x22FFFFFF) watermark.style.textStyle.fontSize = 42 watermark.style.backgroundColor = UIColor.clear // Text annotations let textAnnotation1 = SCITextAnnotation() textAnnotation1.x1 = SCIGeneric(0.3) textAnnotation1.y1 = SCIGeneric(9.7) textAnnotation1.text = "Annotations are Easy!" textAnnotation1.style.textColor = UIColor.white textAnnotation1.style.textStyle.fontSize = 24 textAnnotation1.style.backgroundColor = UIColor.clear let textAnnotation2 = SCITextAnnotation() textAnnotation2.x1 = SCIGeneric(1.0) textAnnotation2.y1 = SCIGeneric(9.0) textAnnotation2.text = "You can create text" textAnnotation2.style.textColor = UIColor.white textAnnotation2.style.textStyle.fontSize = 10 textAnnotation2.style.backgroundColor = UIColor.clear // Text with Anchor Points let textAnnotation3 = SCITextAnnotation() textAnnotation3.x1 = SCIGeneric(5.0) textAnnotation3.y1 = SCIGeneric(8.0) textAnnotation3.text = "Anchor Center (x1, y1)" textAnnotation3.horizontalAnchorPoint = .center textAnnotation3.verticalAnchorPoint = .bottom textAnnotation3.style.textColor = UIColor.white textAnnotation3.style.textStyle.fontSize = 12 let textAnnotation4 = SCITextAnnotation() textAnnotation4.x1 = SCIGeneric(5.0) textAnnotation4.y1 = SCIGeneric(8.0) textAnnotation4.text = "Anchor Right" textAnnotation4.horizontalAnchorPoint = .right textAnnotation4.verticalAnchorPoint = .top textAnnotation4.style.textColor = UIColor.white textAnnotation4.style.textStyle.fontSize = 12 let textAnnotation5 = SCITextAnnotation() textAnnotation5.x1 = SCIGeneric(5.0) textAnnotation5.y1 = SCIGeneric(8.0) textAnnotation5.text = "or Anchor Left"; textAnnotation5.horizontalAnchorPoint = .left textAnnotation5.verticalAnchorPoint = .top textAnnotation5.style.textColor = UIColor.white textAnnotation5.style.textStyle.fontSize = 12 // Line and line arrow annotations let textAnnotation6 = SCITextAnnotation() textAnnotation6.x1 = SCIGeneric(0.3) textAnnotation6.y1 = SCIGeneric(6.1) textAnnotation6.text = "Draw Lines with \nor without Arrows" textAnnotation6.verticalAnchorPoint = .bottom textAnnotation6.style.textColor = UIColor.white textAnnotation6.style.textStyle.fontSize = 12 let lineAnnotation = SCILineAnnotation() lineAnnotation.x1 = SCIGeneric(1.0) lineAnnotation.y1 = SCIGeneric(4.0) lineAnnotation.x2 = SCIGeneric(2.0) lineAnnotation.y2 = SCIGeneric(6.0) lineAnnotation.style.linePen = SCISolidPenStyle(colorCode: 0xFF555555, withThickness: 2) // Should be line annotation with arrow here // Box annotations let textAnnotation7 = SCITextAnnotation() textAnnotation7.x1 = SCIGeneric(3.5) textAnnotation7.y1 = SCIGeneric(6.1) textAnnotation7.text = "Draw Boxes" textAnnotation7.verticalAnchorPoint = .bottom textAnnotation7.style.textColor = UIColor.white textAnnotation7.style.textStyle.fontSize = 12 let boxAnnotation1 = SCIBoxAnnotation() boxAnnotation1.x1 = SCIGeneric(3.5) boxAnnotation1.y1 = SCIGeneric(4.0) boxAnnotation1.x2 = SCIGeneric(5.0) boxAnnotation1.y2 = SCIGeneric(5.0) boxAnnotation1.style.fillBrush = SCILinearGradientBrushStyle(colorCodeStart: 0x550000FF, finish: 0x55FFFF00, direction: .vertical) boxAnnotation1.style.borderPen = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 1.0) let boxAnnotation2 = SCIBoxAnnotation() boxAnnotation2.x1 = SCIGeneric(4.0) boxAnnotation2.y1 = SCIGeneric(4.5) boxAnnotation2.x2 = SCIGeneric(5.5) boxAnnotation2.y2 = SCIGeneric(5.5) boxAnnotation2.style.fillBrush = SCISolidBrushStyle(colorCode: 0x55FF1919) boxAnnotation2.style.borderPen = SCISolidPenStyle(colorCode: 0xFFFF1919, withThickness: 1.0) let boxAnnotation3 = SCIBoxAnnotation() boxAnnotation3.x1 = SCIGeneric(4.5) boxAnnotation3.y1 = SCIGeneric(5.0) boxAnnotation3.x2 = SCIGeneric(6.0) boxAnnotation3.y2 = SCIGeneric(6.0) boxAnnotation3.style.fillBrush = SCISolidBrushStyle(colorCode: 0x55279B27) boxAnnotation3.style.borderPen = SCISolidPenStyle(colorCode: 0xFF279B27, withThickness: 1.0) // Custom shapes let textAnnotation8 = SCITextAnnotation() textAnnotation8.x1 = SCIGeneric(7.0) textAnnotation8.y1 = SCIGeneric(6.1) textAnnotation8.text = "Or Custom Shapes" textAnnotation8.verticalAnchorPoint = .bottom textAnnotation8.style.textColor = UIColor.white textAnnotation8.style.textStyle.fontSize = 12 let customAnnotationGreen = SCICustomAnnotation() customAnnotationGreen.customView = UIImageView(image: UIImage(named: "GreenArrow")) customAnnotationGreen.x1 = SCIGeneric(8) customAnnotationGreen.y1 = SCIGeneric(5.5) let customAnnotationRed = SCICustomAnnotation() customAnnotationRed.customView = UIImageView(image: UIImage(named: "RedArrow")) customAnnotationRed.x1 = SCIGeneric(7.5) customAnnotationRed.y1 = SCIGeneric(5) // Horizontal Line Annotations let horizontalLine = SCIHorizontalLineAnnotation() horizontalLine.x1 = SCIGeneric(5.0) horizontalLine.y1 = SCIGeneric(3.2) horizontalLine.horizontalAlignment = .right horizontalLine.style.linePen = SCISolidPenStyle(color: UIColor.orange, withThickness: 2) horizontalLine.add(self.createLabelWith(text: "Right Aligned, with text on left", labelPlacement: .topLeft, color: UIColor.orange, backColor: UIColor.clear)) let horizontalLine1 = SCIHorizontalLineAnnotation() horizontalLine1.y1 = SCIGeneric(7.5) horizontalLine1.y1 = SCIGeneric(2.8) horizontalLine1.style.linePen = SCISolidPenStyle(color: UIColor.orange, withThickness: 2) horizontalLine1.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.orange)) // Vertical Line annotations let verticalLine = SCIVerticalLineAnnotation() verticalLine.x1 = SCIGeneric(9.0) verticalLine.y1 = SCIGeneric(4.0) verticalLine.verticalAlignment = .bottom; verticalLine.style.linePen = SCISolidPenStyle(colorCode: 0xFFA52A2A, withThickness: 2) verticalLine.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.fromARGBColorCode(0xFFA52A2A))) let verticalLine1 = SCIVerticalLineAnnotation() verticalLine1.x1 = SCIGeneric(9.5) verticalLine1.y1 = SCIGeneric(10.0) verticalLine1.style.linePen = SCISolidPenStyle(colorCode: 0xFFA52A2A, withThickness: 2) verticalLine.add(self.createLabelWith(text: "", labelPlacement: .axis, color: UIColor.black, backColor: UIColor.fromARGBColorCode(0xFFA52A2A))) verticalLine.add(self.createLabelWith(text: "Bottom-aligned", labelPlacement: .topRight, color: UIColor.fromARGBColorCode(0xFFA52A2A), backColor: UIColor.clear)) self.surface.annotations = SCIAnnotationCollection(childAnnotations: [watermark, textAnnotation1, textAnnotation2, textAnnotation3, textAnnotation4, textAnnotation5, textAnnotation6, lineAnnotation, textAnnotation7, boxAnnotation1, boxAnnotation2, boxAnnotation3, textAnnotation8, customAnnotationGreen, customAnnotationRed, horizontalLine, horizontalLine1, verticalLine, verticalLine1]) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCIZoomPanModifier()]) } } fileprivate func createLabelWith(text: String, labelPlacement: SCILabelPlacement, color: UIColor, backColor: UIColor) -> SCILineAnnotationLabel { let lineAnnotationLabel = SCILineAnnotationLabel() lineAnnotationLabel.text = text lineAnnotationLabel.style.backgroundColor = backColor lineAnnotationLabel.style.labelPlacement = labelPlacement lineAnnotationLabel.style.textStyle.color = color return lineAnnotationLabel } }
391a7f6bec24cc23a81201b9e492408e
53.951456
173
0.623233
false
false
false
false
omochi/numsw
refs/heads/master
Sources/numsw/NDArray/NDArray.swift
mit
1
public struct NDArray<T> { private var _shape: [Int] public var shape: [Int] { get { return _shape } set { self = reshaped(newValue) } } public internal(set) var elements: [T] public init(shape: [Int], elements: [T]) { precondition(shape.reduce(1, *) == elements.count, "Shape and elements are not compatible.") self._shape = shape self.elements = elements } }
91b4b8e560bf8a1405b590a7baf46bbc
21.714286
100
0.526205
false
false
false
false
Parallels-MIPT/Coconut-Kit
refs/heads/master
CoconutKit/CoconutKit/ICloudDirectoryManager.swift
apache-2.0
1
// // ICloudDirectoryManager.swift // ICDocumentsSync-IOS // // Created by Malyshev Alexander on 31.07.15. // Copyright (c) 2015 SecurityQQ. All rights reserved. // import Foundation struct Const { static let documents = "Documents" static let directoryOperationQueueName = "directoryOperationQueue" static let storedUbiquityIdentityToken = "com.triangle.storedUbituityIdentityToken" } struct QueueManager { static let directoryQueue : NSOperationQueue = { var queue = NSOperationQueue() queue.maxConcurrentOperationCount = 1 queue.name = Const.directoryOperationQueueName return queue }() } @objc public class ICloudDirectoryManager: NSObject { public let coordinator : NSFileCoordinator public lazy var isUsingICloud : Bool = { return ICloudDirectoryManager.ubiquityContainerIdentityToken() != nil }() public unowned var directoryPresenter : NSFilePresenter public let directoryURL : NSURL public var iCloudURL : NSURL? public let directoryOperationQueue = QueueManager.directoryQueue public init(directoryURL : NSURL) { self.directoryPresenter = DirectoryFilePresenter(directoryURL: directoryURL, conflictManager: ConflictSolutionManager.defaultManager) self.directoryURL = directoryURL self.coordinator = NSFileCoordinator(filePresenter: directoryPresenter) super.init() NSFileCoordinator.addFilePresenter(directoryPresenter) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("ubiquityIdentityTokenDidChange:"), name: NSUbiquityIdentityDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) NSFileCoordinator.removeFilePresenter(directoryPresenter) } //MARK - storing iCloud token private static var storedUbiquityIdentityToken : protocol<NSCoding, NSCopying, NSObjectProtocol>? { if let ubiquityIdentityTokenArchive = NSUserDefaults.standardUserDefaults().objectForKey(Const.storedUbiquityIdentityToken) as? NSData, storedToken = NSKeyedUnarchiver.unarchiveObjectWithData(ubiquityIdentityTokenArchive) as? protocol<NSCoding, NSCopying, NSObjectProtocol> { return storedToken } return nil } private static func ubiquityContainerIdentityToken() -> protocol<NSCoding, NSCopying, NSObjectProtocol>? { if let token = NSFileManager.defaultManager().ubiquityIdentityToken { let archivedToken = NSKeyedArchiver.archivedDataWithRootObject(token) NSUserDefaults.standardUserDefaults().setObject(archivedToken, forKey: Const.storedUbiquityIdentityToken) return token } return nil } func ubiquityIdentityTokenDidChange(notification: NSNotification) { if (NSFileManager.defaultManager().ubiquityIdentityToken == nil) { directoryOperationQueue.cancelAllOperations() } else { moveDirectoryToiCloud() } } //MARK - ICloudDirectory public func getICloudDirectoryURLAndPerformHandler(handler : (NSURL -> Void)) { if (iCloudURL == nil) { let ubiqContainerURLOperation = UbiquitousContainerURLOperation { self.iCloudURL = $0 } directoryOperationQueue.addOperation(ubiqContainerURLOperation) directoryOperationQueue.addOperationWithBlock { [unowned self] in let documentsDirectory = self.iCloudURL?.URLByAppendingPathComponent(Const.documents, isDirectory: true) self.iCloudURL = documentsDirectory handler(self.iCloudURL!) } } else { directoryOperationQueue.addOperationWithBlock { [unowned self] in handler(self.iCloudURL!) } } } //MARK - Moving to iCloud public func moveDirectoryToiCloud() { changeDirectoryUbiquitous(true) } public func removeDirectoryFromICloud() { changeDirectoryUbiquitous(false) } public func moveSubitemToICloud(filename : String, typeOfFile : String) { changeSubitemUbiquitous(true, filename: filename, typeOfFile: typeOfFile) } public func removeSubitemFromICloud(filename: String, typeOfFile : String) { changeSubitemUbiquitous(false, filename: filename, typeOfFile: typeOfFile) } private func changeDirectoryUbiquitous(isUbiquitous: Bool) { if isUsingICloud { let urlHandler : [NSURL] -> Void = { [unowned self](urls) in for url: NSURL in urls { if let filename = url.URLByDeletingLastPathComponent?.lastPathComponent, typeOfFile = url.pathExtension { self.changeSubitemUbiquitous(isUbiquitous, filename: filename, typeOfFile: typeOfFile) } } } if isUbiquitous { let readDirOp = ReadDirectoryOperation(filePresenter: directoryPresenter, directoryURL: directoryURL, errorHandler: defaultFileOperationErrorHandler, urlHandler: urlHandler) directoryOperationQueue.addOperation(readDirOp) } else { let handler : NSURL -> Void = { [unowned self](iCloudURL) in let readDirOp = ReadDirectoryOperation(filePresenter: self.directoryPresenter, directoryURL: iCloudURL, errorHandler: defaultFileOperationErrorHandler, urlHandler: urlHandler) self.directoryOperationQueue.addOperation(readDirOp) } getICloudDirectoryURLAndPerformHandler(handler) } } } private func changeSubitemUbiquitous(isUbiquitous: Bool, filename: String, typeOfFile: String) { let movingHandler : NSURL -> Void = { [unowned self](iCloudURL) in let newURL : NSURL let oldURL : NSURL if isUbiquitous { newURL = iCloudURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile) oldURL = self.directoryURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile) } else { newURL = self.directoryURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile) oldURL = iCloudURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(typeOfFile) } let movingOperation = WriteFileForMovingOperation(newURL: newURL, filePresenter: self.directoryPresenter, fileURL: oldURL) self.directoryOperationQueue.addOperation(movingOperation) } getICloudDirectoryURLAndPerformHandler(movingHandler) } }
f624662685ac9d310cd55e6fedee073b
43.411765
195
0.687077
false
false
false
false
gregomni/swift
refs/heads/main
test/ModuleInterface/opaque-result-types.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -typecheck -module-name OpaqueResultTypes -emit-module-interface-path %t/OpaqueResultTypes.swiftinterface %s // RUN: %FileCheck %s < %t/OpaqueResultTypes.swiftinterface // RUN: %target-swift-frontend -I %t -typecheck -verify %S/Inputs/opaque-result-types-client.swift public protocol Foo {} extension Int: Foo {} // CHECK-LABEL: public func foo(_: Swift.Int) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 1738 } // CHECK-LABEL: @inlinable public func foo(_: Swift.String) -> some OpaqueResultTypes.Foo { @available(SwiftStdlib 5.1, *) @inlinable public func foo(_: String) -> some Foo { return 679 } // CHECK-LABEL: public func foo<T>(_ x: T) -> some OpaqueResultTypes.Foo where T : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<T: Foo>(_ x: T) -> some Foo { return x } public protocol AssocTypeInference { associatedtype Assoc: Foo associatedtype AssocProperty: Foo associatedtype AssocSubscript: Foo func foo(_: Int) -> Assoc var prop: AssocProperty { get } subscript() -> AssocSubscript { get } } @available(SwiftStdlib 5.1, *) public struct Bar<T>: AssocTypeInference { public init() {} // CHECK-LABEL: public func foo(_: Swift.Int) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } // CHECK-LABEL: public func foo<U>(_ x: U) -> some OpaqueResultTypes.Foo where U : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<U: Foo>(_ x: U) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public struct Bas: AssocTypeInference { public init() {} // CHECK-LABEL: public func foo(_: Swift.Int) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } // CHECK-LABEL: public func foo<U>(_ x: U) -> some OpaqueResultTypes.Foo where U : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<U: Foo>(_ x: U) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } // CHECK-LABEL: public typealias Assoc = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> // CHECK-LABEL: public typealias AssocProperty = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> // CHECK-LABEL: public typealias AssocSubscript = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> } @available(SwiftStdlib 5.1, *) public struct Bass<U: Foo>: AssocTypeInference { public init() {} // CHECK-LABEL: public func foo(_: Swift.Int) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } // CHECK-LABEL: public func foo(_ x: U) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_ x: U) -> some Foo { return x } // CHECK-LABEL: public func foo<V>(_ x: V) -> some OpaqueResultTypes.Foo where V : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<V: Foo>(_ x: V) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } // CHECK-LABEL: public typealias Assoc = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T, U> // CHECK-LABEL: public typealias AssocProperty = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T, U> // CHECK-LABEL: public typealias AssocSubscript = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T, U> } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } // CHECK-LABEL: public typealias Assoc = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> // CHECK-LABEL: public typealias AssocProperty = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> // CHECK-LABEL: public typealias AssocSubscript = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<T> } @available(SwiftStdlib 5.1, *) public struct Zim: AssocTypeInference { public init() {} @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } // CHECK-LABEL: public func foo<U>(_ x: U) -> some OpaqueResultTypes.Foo where U : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<U: Foo>(_ x: U) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public struct Zang: AssocTypeInference { public init() {} @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } // CHECK-LABEL: public func foo<U>(_ x: U) -> some OpaqueResultTypes.Foo where U : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<U: Foo>(_ x: U) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } } @available(SwiftStdlib 5.1, *) public struct Zung<U: Foo>: AssocTypeInference { public init() {} // CHECK-LABEL: public func foo(_: Swift.Int) -> some OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo(_: Int) -> some Foo { return 20721 } @available(SwiftStdlib 5.1, *) public func foo(_: String) -> some Foo { return 219 } @available(SwiftStdlib 5.1, *) public func foo(_ x: U) -> some Foo { return x } // CHECK-LABEL: public func foo<V>(_ x: V) -> some OpaqueResultTypes.Foo where V : OpaqueResultTypes.Foo @available(SwiftStdlib 5.1, *) public func foo<V: Foo>(_ x: V) -> some Foo { return x } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } // CHECK-LABEL: public typealias Assoc = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<U> // CHECK-LABEL: public typealias AssocProperty = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<U> // CHECK-LABEL: public typealias AssocSubscript = @_opaqueReturnTypeOf("{{.*}}", 0) {{.*}}<U> } @available(SwiftStdlib 5.1, *) public var prop: some Foo { return 123 } @available(SwiftStdlib 5.1, *) public subscript() -> some Foo { return 123 } }
69b6754e19bb514232903cb561c1b35a
27.788618
139
0.616775
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/Library/Eureka/Source/Rows/SegmentedRow.swift
mit
1
// // SegmentedRow.swift // Eureka // // Created by Martin Barreto on 2/23/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation //MARK: SegmentedCell open class SegmentedCell<T: Equatable> : Cell<T>, CellType { open var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, for: .horizontal) return textLabel } lazy open var segmentedControl : UISegmentedControl = { let result = UISegmentedControl() result.translatesAutoresizingMaskIntoConstraints = false result.setContentHuggingPriority(250, for: .horizontal) return result }() fileprivate var dynamicConstraints = [NSLayoutConstraint]() required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { segmentedControl.removeTarget(self, action: nil, for: .allEvents) titleLabel?.removeObserver(self, forKeyPath: "text") imageView?.removeObserver(self, forKeyPath: "image") } open override func setup() { super.setup() height = { BaseRow.estimatedRowHeight } selectionStyle = .none contentView.addSubview(titleLabel!) contentView.addSubview(segmentedControl) titleLabel?.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil) imageView?.addObserver(self, forKeyPath: "image", options: [.old, .new], context: nil) segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), for: .valueChanged) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } open override func update() { super.update() detailTextLabel?.text = nil updateSegmentedControl() segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment segmentedControl.isEnabled = !row.isDisabled } func valueChanged() { row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex] } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let changeType = change, let _ = keyPath, ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) && (changeType[NSKeyValueChangeKey.kindKey] as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue{ setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } func updateSegmentedControl() { segmentedControl.removeAllSegments() items().enumerated().forEach { segmentedControl.insertSegment(withTitle: $0.element, at: $0.offset, animated: false) } } open override func updateConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["segmentedControl": segmentedControl] var hasImageView = false var hasTitleLabel = false if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView hasImageView = true } if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["titleLabel"] = titleLabel hasTitleLabel = true dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: 0.3, constant: 0.0)) if hasImageView && hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if hasImageView && !hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if !hasImageView && hasTitleLabel { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } else { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } func items() -> [String] {// or create protocol for options var result = [String]() for object in (row as! SegmentedRow<T>).options { result.append(row.displayValueFor?(object) ?? "") } return result } func selectedIndex() -> Int? { guard let value = row.value else { return nil } return (row as! SegmentedRow<T>).options.index(of: value) } } //MARK: SegmentedRow /// An options row where the user can select an option from an UISegmentedControl public final class SegmentedRow<T: Equatable>: OptionsRow<T, SegmentedCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
d7a2be1e32adea343bed5752643de038
40.992908
248
0.660868
false
false
false
false
KrishMunot/swift
refs/heads/master
stdlib/public/core/String.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // 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 SwiftShims // FIXME: complexity documentation for most of methods on String is ought to be // qualified with "amortized" at least, as Characters are variable-length. /// An arbitrary Unicode string value. /// /// Unicode-Correct /// =============== /// /// Swift strings are designed to be Unicode-correct. In particular, /// the APIs make it easy to write code that works correctly, and does /// not surprise end-users, regardless of where you venture in the /// Unicode character space. For example, the `==` operator checks /// for [Unicode canonical /// equivalence](http://www.unicode.org/glossary/#deterministic_comparison), /// so two different representations of the same string will always /// compare equal. /// /// Locale-Insensitive /// ================== /// /// The fundamental operations on Swift strings are not sensitive to /// locale settings. That's because, for example, the validity of a /// `Dictionary<String, T>` in a running program depends on a given /// string comparison having a single, stable result. Therefore, /// Swift always uses the default, /// un-[tailored](http://www.unicode.org/glossary/#tailorable) Unicode /// algorithms for basic string operations. /// /// Importing `Foundation` endows swift strings with the full power of /// the `NSString` API, which allows you to choose more complex /// locale-sensitive operations explicitly. /// /// Value Semantics /// =============== /// /// Each string variable, `let` binding, or stored property has an /// independent value, so mutations to the string are not observable /// through its copies: /// /// var a = "foo" /// var b = a /// b.append("bar") /// print("a=\(a), b=\(b)") // a=foo, b=foobar /// /// Strings use Copy-on-Write so that their data is only copied /// lazily, upon mutation, when more than one string instance is using /// the same buffer. Therefore, the first in any sequence of mutating /// operations may cost `O(N)` time and space, where `N` is the length /// of the string's (unspecified) underlying representation. /// /// Views /// ===== /// /// `String` is not itself a collection of anything. Instead, it has /// properties that present the string's contents as meaningful /// collections: /// /// - `characters`: a collection of `Character` ([extended grapheme /// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster)) /// elements, a unit of text that is meaningful to most humans. /// /// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode /// scalar /// values](http://www.unicode.org/glossary/#unicode_scalar_value)) /// the 21-bit codes that are the basic unit of Unicode. These /// values are equivalent to UTF-32 code units. /// /// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit /// elements of the string's UTF-16 encoding. /// /// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit /// elements of the string's UTF-8 encoding. /// /// Growth and Capacity /// =================== /// /// When a string's contiguous storage fills up, new storage must be /// allocated and characters must be moved to the new storage. /// `String` uses an exponential growth strategy that makes `append` a /// constant time operation *when amortized over many invocations*. /// /// Objective-C Bridge /// ================== /// /// `String` is bridged to Objective-C as `NSString`, and a `String` /// that originated in Objective-C may store its characters in an /// `NSString`. Since any arbitrary subclass of `NSString` can /// become a `String`, there are no guarantees about representation or /// efficiency in this case. Since `NSString` is immutable, it is /// just as though the storage was shared by some copy: the first in /// any sequence of mutating operations causes elements to be copied /// into unique, contiguous storage which may cost `O(N)` time and /// space, where `N` is the length of the string representation (or /// more, if the underlying `NSString` has unusual performance /// characteristics). @_fixed_layout public struct String { /// An empty `String`. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { @warn_unused_result public // @testable static func _fromWellFormedCodeUnitSequence< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( _ encoding: Encoding.Type, input: Input ) -> String { return String._fromCodeUnitSequence(encoding, input: input)! } @warn_unused_result public // @testable static func _fromCodeUnitSequence< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( _ encoding: Encoding.Type, input: Input ) -> String? { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: false) if let stringBuffer = stringBufferOptional { return String(_storage: stringBuffer) } else { return nil } } @warn_unused_result public // @testable static func _fromCodeUnitSequenceWithRepair< Encoding: UnicodeCodec, Input: Collection where Input.Iterator.Element == Encoding.CodeUnit >( _ encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _BuiltinUnicodeScalarLiteralConvertible { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : UnicodeScalarLiteralConvertible { /// Create an instance initialized to `value`. public init(unicodeScalarLiteral value: String) { self = value } } extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } extension String : ExtendedGraphemeClusterLiteralConvertible { /// Create an instance initialized to `value`. public init(extendedGraphemeClusterLiteral value: String) { self = value } } extension String : _BuiltinUTF16StringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { self = String( _StringCore( baseAddress: OpaquePointer(start), count: Int(utf16CodeUnitCount), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _BuiltinStringLiteralConvertible { @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: OpaquePointer(start), count: Int(utf8CodeUnitCount), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } } extension String : StringLiteralConvertible { /// Create an instance initialized to `value`. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escaped(asASCII: false) } result += "\"" return result } } extension String { /// Returns the number of code units occupied by this string /// in the given encoding. @warn_unused_result func _encodedLength< Encoding: UnicodeCodec >(_ encoding: Encoding.Type) -> Int { var codeUnitCount = 0 let output: (Encoding.CodeUnit) -> Void = { _ in codeUnitCount += 1 } self._encode(encoding, output: output) return codeUnitCount } // FIXME: this function does not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode< Encoding: UnicodeCodec >(_ encoding: Encoding.Type, @noescape output: (Encoding.CodeUnit) -> Void) { return _core.encode(encoding, output: output) } } #if _runtime(_ObjC) /// Compare two strings using the Unicode collation algorithm in the /// deterministic comparison mode. (The strings which are equivalent according /// to their NFD form are considered equal. Strings which are equivalent /// according to the plain Unicode collation algorithm are additionally ordered /// based on their NFD.) /// /// See Unicode Technical Standard #10. /// /// The behavior is equivalent to `NSString.compare()` with default options. /// /// - returns: /// * an unspecified value less than zero if `lhs < rhs`, /// * zero if `lhs == rhs`, /// * an unspecified value greater than zero if `lhs > rhs`. @_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation") public func _stdlib_compareNSStringDeterministicUnicodeCollation( _ lhs: AnyObject, _ rhs: AnyObject ) -> Int32 @_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollationPtr") public func _stdlib_compareNSStringDeterministicUnicodeCollationPointer( _ lhs: OpaquePointer, _ rhs: OpaquePointer ) -> Int32 #endif extension String : Equatable { } @warn_unused_result public func ==(lhs: String, rhs: String) -> Bool { if lhs._core.isASCII && rhs._core.isASCII { if lhs._core.count != rhs._core.count { return false } return _swift_stdlib_memcmp( lhs._core.startASCII, rhs._core.startASCII, rhs._core.count) == 0 } return lhs._compareString(rhs) == 0 } extension String : Comparable { } extension String { #if _runtime(_ObjC) /// This is consistent with Foundation, but incorrect as defined by Unicode. /// Unicode weights some ASCII punctuation in a different order than ASCII /// value. Such as: /// /// 0022 ; [*02FF.0020.0002] # QUOTATION MARK /// 0023 ; [*038B.0020.0002] # NUMBER SIGN /// 0025 ; [*038C.0020.0002] # PERCENT SIGN /// 0026 ; [*0389.0020.0002] # AMPERSAND /// 0027 ; [*02F8.0020.0002] # APOSTROPHE /// /// - Precondition: Both `self` and `rhs` are ASCII strings. @warn_unused_result public // @testable func _compareASCII(_ rhs: String) -> Int { var compare = Int(_swift_stdlib_memcmp( self._core.startASCII, rhs._core.startASCII, min(self._core.count, rhs._core.count))) if compare == 0 { compare = self._core.count - rhs._core.count } // This efficiently normalizes the result to -1, 0, or 1 to match the // behavior of NSString's compare function. return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0) } #endif /// Compares two strings with the Unicode Collation Algorithm. @warn_unused_result @inline(never) @_semantics("stdlib_binary_only") // Hide the CF/ICU dependency public // @testable func _compareDeterministicUnicodeCollation(_ rhs: String) -> Int { // Note: this operation should be consistent with equality comparison of // Character. #if _runtime(_ObjC) if self._core.hasContiguousStorage && rhs._core.hasContiguousStorage { let lhsStr = _NSContiguousString(self._core) let rhsStr = _NSContiguousString(rhs._core) let res = lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) { return Int( _stdlib_compareNSStringDeterministicUnicodeCollationPointer($0, $1)) } return res } return Int(_stdlib_compareNSStringDeterministicUnicodeCollation( _bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl())) #else switch (_core.isASCII, rhs._core.isASCII) { case (true, false): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf8_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (false, true): // Just invert it and recurse for this case. return -rhs._compareDeterministicUnicodeCollation(self) case (false, false): let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16) let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf16_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (true, true): let lhsPtr = UnsafePointer<Int8>(_core.startASCII) let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII) return Int(_swift_stdlib_unicode_compare_utf8_utf8( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) } #endif } @warn_unused_result public // @testable func _compareString(_ rhs: String) -> Int { #if _runtime(_ObjC) // We only want to perform this optimization on objc runtimes. Elsewhere, // we will make it follow the unicode collation algorithm even for ASCII. if (_core.isASCII && rhs._core.isASCII) { return _compareASCII(rhs) } #endif return _compareDeterministicUnicodeCollation(rhs) } } @warn_unused_result public func <(lhs: String, rhs: String) -> Bool { return lhs._compareString(rhs) < 0 } // Support for copy-on-write extension String { /// Append the elements of `other` to `self`. public mutating func append(_ other: String) { _core.append(other._core) } /// Append `x` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(_ x: UnicodeScalar) { _core.append(x) } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringHashValue") func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int @warn_unused_result @_silgen_name("swift_stdlib_NSStringHashValuePointer") func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int #endif extension String : Hashable { /// 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 { #if _runtime(_ObjC) // Mix random bits into NSString's hash so that clients don't rely on // Swift.String.hashValue and NSString.hash being the same. #if arch(i386) || arch(arm) let hashOffset = Int(bitPattern: 0x88dd_cc21) #else let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21) #endif // If we have a contiguous string then we can use the stack optimization. let core = self._core let isASCII = core.isASCII if core.hasContiguousStorage { let stackAllocated = _NSContiguousString(core) return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer { return _stdlib_NSStringHashValuePointer($0, isASCII ) } } else { let cocoaString = unsafeBitCast( self._bridgeToObjectiveCImpl(), to: _NSStringCore.self) return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII) } #else if self._core.isASCII { return _swift_stdlib_unicode_hash_ascii( UnsafeMutablePointer<Int8>(_core.startASCII), Int32(_core.count)) } else { return _swift_stdlib_unicode_hash( UnsafeMutablePointer<UInt16>(_core.startUTF16), Int32(_core.count)) } #endif } } @warn_unused_result @effects(readonly) @_semantics("string.concat") public func + (lhs: String, rhs: String) -> String { var lhs = lhs if (lhs.isEmpty) { return rhs } lhs._core.append(rhs._core) return lhs } // String append public func += (lhs: inout String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } extension String { /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( _ resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8CodeUnitCount: Int ) { resultStorage.initialize(with: String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount))) } } extension String { public typealias Index = CharacterView.Index /// The position of the first `Character` in `self.characters` if /// `self` is non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return characters.startIndex } /// The "past the end" position in `self.characters`. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return characters.endIndex } /// Access the `Character` at `position`. /// /// - Precondition: `position` is a valid position in `self.characters` /// and `position != endIndex`. public subscript(i: Index) -> Character { return characters[i] } } @warn_unused_result public func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base == rhs._base } @warn_unused_result public func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._base < rhs._base } extension String { /// Return the characters within the given `bounds`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(bounds: Range<Index>) -> String { return String(characters[bounds]) } } extension String { public mutating func reserveCapacity(_ n: Int) { withMutableCharacters { (v: inout CharacterView) in v.reserveCapacity(n) } } public mutating func append(_ c: Character) { withMutableCharacters { (v: inout CharacterView) in v.append(c) } } public mutating func append< S : Sequence where S.Iterator.Element == Character >(contentsOf newElements: S) { withMutableCharacters { (v: inout CharacterView) in v.append(contentsOf: newElements) } } /// Create an instance containing `characters`. public init< S : Sequence where S.Iterator.Element == Character >(_ characters: S) { self._core = CharacterView(characters)._core } } extension Sequence where Iterator.Element == String { /// Interpose the `separator` between elements of `self`, then concatenate /// the result. For example: /// /// ["foo", "bar", "baz"].joined(separator: "-|-") // "foo-|-bar-|-baz" @warn_unused_result public func joined(separator: String) -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { () -> Int in var r = 0 for chunk in self { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize == 0 { for x in self { result.append(x) } return result } var iter = makeIterator() if let first = iter.next() { result.append(first) while let next = iter.next() { result.append(separator) result.append(next) } } return result } } extension String { /// Replace the characters within `bounds` with the elements of /// `replacement`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange< C: Collection where C.Iterator.Element == Character >( _ bounds: Range<Index>, with newElements: C ) { withMutableCharacters { (v: inout CharacterView) in v.replaceSubrange(bounds, with: newElements) } } /// Replace the text in `bounds` with `replacement`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange( _ bounds: Range<Index>, with newElements: String ) { replaceSubrange(bounds, with: newElements.characters) } /// Insert `newElement` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func insert(_ newElement: Character, at i: Index) { withMutableCharacters { (v: inout CharacterView) in v.insert(newElement, at: i) } } /// Insert `newElements` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count + newElements.count`). public mutating func insert< S : Collection where S.Iterator.Element == Character >(contentsOf newElements: S, at i: Index) { withMutableCharacters { (v: inout CharacterView) in v.insert(contentsOf: newElements, at: i) } } /// Remove and return the `Character` at position `i`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). @discardableResult public mutating func remove(at i: Index) -> Character { return withMutableCharacters { (v: inout CharacterView) in v.remove(at: i) } } /// Remove the characters in `bounds`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). public mutating func removeSubrange(_ bounds: Range<Index>) { withMutableCharacters { (v: inout CharacterView) in v.removeSubrange(bounds) } } /// Replace `self` with the empty string. /// /// Invalidates all indices with respect to `self`. /// /// - parameter keepCapacity: If `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { withMutableCharacters { (v: inout CharacterView) in v.removeAll(keepingCapacity: keepCapacity) } } } #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString @warn_unused_result @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString #else @warn_unused_result internal func _nativeUnicodeLowercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } @warn_unused_result internal func _nativeUnicodeUppercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Try to write it out to the same length. let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } /// Return `self` converted to lower case. /// /// - Complexity: O(n) public func lowercased() -> String { if self._core.isASCII { let count = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<count { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isUpper & 0x1) << 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest[i] = value &+ UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } /// Return `self` converted to upper case. /// /// - Complexity: O(n) public func uppercased() -> String { if self._core.isASCII { let count = self._core.count let source = self._core.startASCII let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = UnsafeMutablePointer<UInt8>(buffer.start) for i in 0..<count { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable >> UInt64(((value &- 1) & 0b0111_1111) >> 1) let add = (isLower & 0x1) << 5 dest[i] = value &- UInt8(truncatingBitPattern: add) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } } // Index conversions extension String.Index { /// Construct the position in `characters` that corresponds exactly to /// `unicodeScalarIndex`. If no such position exists, the result is `nil`. /// /// - Precondition: `unicodeScalarIndex` is an element of /// `characters.unicodeScalars.indices`. public init?( _ unicodeScalarIndex: String.UnicodeScalarIndex, within characters: String ) { if !unicodeScalarIndex._isOnGraphemeClusterBoundary { return nil } self.init(_base: unicodeScalarIndex) } /// Construct the position in `characters` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf16Index` is an element of /// `characters.utf16.indices`. public init?( _ utf16Index: String.UTF16Index, within characters: String ) { if let me = utf16Index.samePosition( in: characters.unicodeScalars )?.samePosition(in: characters) { self = me } else { return nil } } /// Construct the position in `characters` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf8Index` is an element of /// `characters.utf8.indices`. public init?( _ utf8Index: String.UTF8Index, within characters: String ) { if let me = utf8Index.samePosition( in: characters.unicodeScalars )?.samePosition(in: characters) { self = me } else { return nil } } /// Returns the position in `utf8` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf8).indices`. @warn_unused_result public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in `utf16` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf16).indices`. @warn_unused_result public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in `unicodeScalars` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(unicodeScalars).indices`. @warn_unused_result public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarView.Index { return String.UnicodeScalarView.Index(self, within: unicodeScalars) } } extension String { @available(*, unavailable, renamed: "append") public mutating func appendContentsOf(_ other: String) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "append(contentsOf:)") public mutating func appendContentsOf< S : Sequence where S.Iterator.Element == Character >(_ newElements: S) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "insert(contentsOf:at:)") public mutating func insertContentsOf< S : Collection where S.Iterator.Element == Character >(_ newElements: S, at i: Index) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange< C : Collection where C.Iterator.Element == Character >( _ subRange: Range<Index>, with newElements: C ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange( _ subRange: Range<Index>, with newElements: String ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "removeAt") public mutating func removeAtIndex(_ i: Index) -> Character { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "removeSubrange") public mutating func removeRange(_ subRange: Range<Index>) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lowercased()") public var lowercaseString: String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased()") public var uppercaseString: String { fatalError("unavailable function can't be called") } } extension Sequence where Iterator.Element == String { @available(*, unavailable, renamed: "joined") public func joinWithSeparator(_ separator: String) -> String { fatalError("unavailable function can't be called") } }
a68812a1c21f87795572b7295485d60e
31.159963
94
0.670904
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/RecordVoice/JCRecordingView.swift
mit
1
// // JCRecordingView.swift // JChatSwift // // Created by oshumini on 16/2/19. // Copyright © 2016年 HXHG. All rights reserved. // import UIKit internal let voiceRecordResaueString = "松开手指,取消发送" internal let voiceRecordPauseString = "手指上滑,取消发送" class JCRecordingView: UIView { var remiadeLable: UILabel! var cancelRecordImageView: UIImageView! var recordingHUDImageView: UIImageView! var errorTipsView: UIImageView! var timeLable: UILabel! var tipsLable: UILabel! var peakPower:Float! var isRecording = false func dismissCompled(_ completed: (_ finish:Bool) -> Void) { } override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func _init() { backgroundColor = UIColor.black.withAlphaComponent(0.5) layer.masksToBounds = true layer.cornerRadius = 5 remiadeLable = UILabel() remiadeLable.textColor = UIColor.white remiadeLable.layer.cornerRadius = 2.5 remiadeLable.layer.masksToBounds = true remiadeLable.font = UIFont.systemFont(ofSize: 12) remiadeLable.text = voiceRecordPauseString remiadeLable.textAlignment = .center addSubview(remiadeLable) timeLable = UILabel() timeLable.textColor = UIColor(netHex: 0x2DD0CF) timeLable.font = UIFont.systemFont(ofSize: 12) timeLable.text = "······ 0.00 ······" timeLable.textAlignment = .center addSubview(timeLable) tipsLable = UILabel() tipsLable.textColor = UIColor(netHex: 0x2DD0CF) tipsLable.font = UIFont.systemFont(ofSize: 62) tipsLable.textAlignment = .center tipsLable.isHidden = true addSubview(tipsLable) recordingHUDImageView = UIImageView() recordingHUDImageView.image = UIImage.loadImage("com_icon_record") addSubview(recordingHUDImageView) errorTipsView = UIImageView() errorTipsView.image = UIImage.loadImage("com_icon_record_error") errorTipsView.isHidden = true addSubview(errorTipsView) cancelRecordImageView = UIImageView() cancelRecordImageView.image = UIImage.loadImage("com_icon_record_cancel") cancelRecordImageView.contentMode = .scaleToFill addSubview(cancelRecordImageView) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .top, .equal, self, .top, 21.5)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .width, .equal, nil, .notAnAttribute, 43)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .top, .equal, self, .top, 27.5)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .width, .equal, nil, .notAnAttribute, 5)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .top, .equal, self, .top, 21.5)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .width, .equal, nil, .notAnAttribute, 43)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .height, .equal, nil, .notAnAttribute, 19)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .top, .equal, recordingHUDImageView, .bottom, 25.5)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .right, .equal, self, .right, -10)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .left, .equal, self, .left, 10)) addConstraint(_JCLayoutConstraintMake(timeLable, .height, .equal, nil, .notAnAttribute, 16.5)) addConstraint(_JCLayoutConstraintMake(timeLable, .top, .equal, recordingHUDImageView, .bottom, 5)) addConstraint(_JCLayoutConstraintMake(timeLable, .right, .equal, self, .right)) addConstraint(_JCLayoutConstraintMake(timeLable, .left, .equal, self, .left)) addConstraint(_JCLayoutConstraintMake(tipsLable, .height, .equal, nil, .notAnAttribute, 86.5)) addConstraint(_JCLayoutConstraintMake(tipsLable, .top, .equal, self, .top, 9.5)) addConstraint(_JCLayoutConstraintMake(tipsLable, .right, .equal, self, .right)) addConstraint(_JCLayoutConstraintMake(tipsLable, .left, .equal, self, .left)) } func startRecordingHUDAtView(_ view:UIView) { view.addSubview(self) self.center = view.center configRecoding(true) } func pauseRecord() { configRecoding(true) remiadeLable.backgroundColor = UIColor.clear remiadeLable.text = voiceRecordPauseString } func resaueRecord() { configRecoding(false) remiadeLable.backgroundColor = UIColor(netHex: 0x7E1D22) remiadeLable.text = voiceRecordResaueString } func stopRecordCompleted(_ completed: (_ finish:Bool) -> Void) { dismissCompled(completed) } func cancelRecordCompleted(_ completed: (_ finish:Bool) -> Void) { dismissCompled(completed) } func dismissCompleted(_ completed:@escaping (_ finish:Bool) -> Void) { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { () -> Void in self.alpha = 0.0 }) { (finished:Bool) -> Void in super.removeFromSuperview() completed(finished) } } func configRecoding(_ recording: Bool) { isRecording = recording recordingHUDImageView.isHidden = !recording cancelRecordImageView.isHidden = recording } func setTime(_ time: TimeInterval) { let t = Int(time) if t > 49 { tipsLable.isHidden = false timeLable.isHidden = true cancelRecordImageView.isHidden = true recordingHUDImageView.isHidden = true tipsLable.text = "\(60 - t)" } else { tipsLable.isHidden = true timeLable.isHidden = false if isRecording { recordingHUDImageView.isHidden = false } else { cancelRecordImageView.isHidden = false } } if t >= 60 { timeLable.text = "······ 1.00 ······" } else if t > 9 { timeLable.text = "······ 0.\(t) ······" } else { timeLable.text = "······ 0.0\(t) ······" } } func setPeakPower(_ peakPower: Float) { self.peakPower = peakPower } func showErrorTips() { recordingHUDImageView.isHidden = true errorTipsView.isHidden = false timeLable.isHidden = true remiadeLable.text = "说话时间太短" } }
fc4a4aaaebe7e630e6276cca8d06d49e
37.768421
112
0.64051
false
false
false
false
larcus94/Spectral
refs/heads/master
Spectral/Spectral/Spectral.swift
mit
1
// // Spectral.swift // Spectral // // Created by Laurin Brandner on 27/06/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // #if os(iOS) import UIKit typealias Color = UIColor #elseif os(OSX) import Cocoa typealias Color = NSColor #endif extension Color { public var hexValue: Int { var rF: CGFloat = 0 var gF: CGFloat = 0 var bF: CGFloat = 0 var aF: CGFloat = 0 getRed(&rF, green: &gF, blue: &bF, alpha: &aF) let r = Int(rF*255) let g = Int(gF*255) let b = Int(bF*255) let a = Int(aF*255) return r << 24 + g << 16 + b << 8 + a } private convenience init(hex4 value: Int, alpha: CGFloat?) { let a = alpha ?? CGFloat(value & 0x000F) self.init(hex3: value >> 4, alpha: a/15) } private convenience init(hex3 value: Int, alpha: CGFloat) { let r = (value & 0xF00) >> 8 let g = (value & 0x0F0) >> 4 let b = value & 0x00F self.init(red: CGFloat(r)/15, green: CGFloat(g)/15, blue: CGFloat(b)/15, alpha: alpha) } private convenience init(hex8 value: Int, alpha: CGFloat?) { let a = alpha ?? CGFloat(value & 0x000000FF) self.init(hex6: (value >> 8), alpha: a/255) } private convenience init(hex6 value: Int, alpha: CGFloat) { let r = (value & 0xFF0000) >> 16 let g = (value & 0x00FF00) >> 8 let b = value & 0x0000FF self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: alpha) } public convenience init(hex value: Int, alpha: CGFloat? = nil) { if value <= 0xFFF { self.init(hex3: value, alpha: alpha ?? 1) } else if value <= 0xFFFF { self.init(hex4: value, alpha: alpha) } else if value <= 0xFFFFFF { self.init(hex6: value, alpha: alpha ?? 1) } else { self.init(hex8: value, alpha: alpha) } } }
8e097fe8fe067443206e374334de69a9
24.876543
97
0.517653
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNMModel/ArrayExtensions.swift
gpl-2.0
1
// // ArrayExtensions.swift // denm_utility // // Created by James Bean on 8/12/15. // Copyright © 2015 James Bean. All rights reserved. // import Foundation public extension Array { var second: Element? { get { return self[1] as Element } } func sum<T: Arithmetic>() -> T { return self.map { $0 as! T }.reduce(T.zero()) { T.add($0, $1) } } func containsElementsWithValuesGreaterThanValue<T: Comparable>(value: T) -> Bool { for el in self { if el as! T > value { return true } } return false } // find more elegant solution func mean<T: Arithmetic>() -> T { if self[0] is Int { let sum: Int = self.sum() let count: Int = self.count return T.divide(sum as! T, count as! T) } else if self[0] is Float { let sumAsFloat: Float = self.sum() let countAsFloat = Float(self.count) return T.divide(sumAsFloat as! T, countAsFloat as! T) } else if self[0] is Double { let sumAsDouble: Double = self.sum() let countAsDouble = Double(self.count) return T.divide(sumAsDouble as! T, countAsDouble as! T) } return T.zero() } func variance<T: Arithmetic>() -> T { var distancesSquared: [T] = [] let mean: T = self.mean() for el in self { let distance: T = T.subtract(el as! T, mean) distancesSquared.append(T.multiply(distance, distance)) } return distancesSquared.mean() } func evenness<T: Arithmetic>() -> T { var amountEven: Float = 0 var amountOdd: Float = 0 for el in self { if T.isEven(el as! T) { amountEven++ } else { amountOdd++ } } return T.zero() } func cumulative<T: Arithmetic>() -> [(value: T, position: T)] { let typedSelf: [T] = self.map { $0 as! T } var newSelf: [(value: T, position: T)] = [] var cumulative: T = T.zero() for val in typedSelf { cumulative = T.add(cumulative, val) let pair: (value: T, position: T) = (value: val, position: cumulative) newSelf.append(pair) } return newSelf } func indexOf<T: Equatable>(value: T) -> Int? { for (index, el) in self.enumerate() { if el as! T == value { return index } } return nil } func indexOfObject(object: AnyObject) -> Int? { for (index, el) in self.enumerate() { if el as? AnyObject === object { return index } } return nil } func unique<T: Equatable>() -> [T] { var buffer: [T] = [] var added: [T] = [] for el in self { if !added.contains(el as! T) { buffer.append(el as! T) added.append(el as! T) } } return buffer } func random<T: Equatable>() -> T { let randomIndex: Int = Int(arc4random_uniform(UInt32(self.count))) return self[randomIndex] as! T } mutating func removeFirst() { assert(self.count > 0, "can't remove the first if there is nothing there") self.removeAtIndex(0) } mutating func removeFirst(amount amount: Int) { assert(self.count >= amount, "can't remove more than what's there") for _ in 0..<amount { self.removeAtIndex(0) } } mutating func removeLast(amount amount: Int) { assert(self.count >= amount, "can't remove more than what's there") for _ in 0..<amount { self.removeLast() } } mutating func remove<T: Equatable>(element: T) { let index: Int? = indexOf(element) if index != nil { removeAtIndex(index!) } } mutating func removeObject(object: AnyObject) { let index: Int? = indexOfObject(object) if index != nil { removeAtIndex(index!) } } func containsObject(object: AnyObject) -> Bool { if let _ = indexOfObject(object) { return true } return false } } public func ==<T: Equatable, U: Equatable> (tuple1:(T,U),tuple2:(T,U)) -> Bool { return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1) } public func intersection<T: Equatable>(array0: [T], array1: [T]) -> [T] { let intersection = array0.filter { array1.contains($0) } return intersection } public func closest(array: [Float], val: Float) -> Float { var cur: Float = array[0] var diff: Float = abs(val - cur) for i in array { let newDiff = abs(val - i) if newDiff < diff { diff = newDiff; cur = i } } return cur } public func gcd(array: [Int]) -> Int { var x: Float = abs(Float(array[0])) for el in array { var y: Float = abs(Float(el)) while (x > 0 && y > 0) { if x > y { x %= y } else { y %= x } } x += y } return Int(x) } public func getClosestPowerOfTwo(multiplier multiplier: Int, value: Int) -> Int { var potential: [Float] = [] for exponent in -4..<4 { potential.append(Float(multiplier) * pow(2.0, Float(exponent))) } var closestVal: Float = closest(potential, val: Float(value)) var newValue = value while closestVal % 1.0 != 0 { closestVal *= 2.0; newValue *= 2 } return Int(closestVal) }
a713699b1ad37be7242fe4333556a93a
29.517045
86
0.544507
false
false
false
false
JGiola/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/sr12723.swift
apache-2.0
5
// RUN: %target-swift-emit-silgen %s -verify func SR12723_thin(_: (@convention(thin) () -> Void) -> Void) {} func SR12723_block(_: (@convention(block) () -> Void) -> Void) {} func SR12723_c(_: (@convention(c) () -> Void) -> Void) {} func SR12723_function(_: () -> Void) {} func context() { SR12723_c(SR12723_function) SR12723_block(SR12723_function) SR12723_thin(SR12723_function) } struct SR12723_C { let function: (@convention(c) () -> Void) -> Void } struct SR12723_Thin { let function: (@convention(thin) () -> Void) -> Void } struct SR12723_Block { let function: (@convention(block) () -> Void) -> Void } func proxy(_ f: (() -> Void) -> Void) { let a = 1 f { print(a) } } func cContext() { let c = SR12723_C { app in app() } proxy(c.function) // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = c.function // OK let _ : (@convention(thin) () -> Void) -> Void = c.function // OK let _ : (() -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func thinContext() { let thin = SR12723_Thin { app in app() } proxy(thin.function) // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = thin.function // OK let _ : (@convention(thin) () -> Void) -> Void = thin.function // OK let _ : (() -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func blockContext() { let block = SR12723_Block { app in app() } proxy(block.function) let _ : (@convention(block) () -> Void) -> Void = block.function // OK let _ : (@convention(c) () -> Void) -> Void = block.function // OK let _ : (@convention(thin) () -> Void) -> Void = block.function // OK let _ : (() -> Void) -> Void = block.function // OK }
d5b614826d964a8dd49ea2d41295af8d
38.310345
168
0.587719
false
false
false
false
nakajijapan/NKJPhotoSliderController
refs/heads/master
Example/NKJPhotoSliderControllerUITests/NKJPhotoSliderControllerUITests.swift
mit
1
// // NKJPhotoSliderControllerUITests.swift // NKJPhotoSliderControllerUITests // // Created by nakajijapan on 2015/10/29. // Copyright 2015 nakajijapan. All rights reserved. // import XCTest class NKJPhotoSliderControllerUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { super.tearDown() XCUIApplication().terminate() } func existsPhotoSliderScrollView(_ app: XCUIApplication) { sleep(1) XCTAssertEqual(app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element.exists, false) } func testPushCloseButtonExample() { let app = XCUIApplication() app.otherElements["rootView"].tap() XCTAssertEqual(app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element.exists, true) app.buttons["NKJPhotoSliderControllerClose"].tap() self.existsPhotoSliderScrollView(app) } func testSwitchImage() { let app = XCUIApplication() app.otherElements["rootView"].tap() let element = app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element(boundBy: 0) element.swipeLeft() element.swipeLeft() element.swipeLeft() element.swipeRight() element.swipeRight() element.swipeRight() app.buttons["NKJPhotoSliderControllerClose"].tap() self.existsPhotoSliderScrollView(app) } func testCloseWithSwipingUpImage() { let app = XCUIApplication() app.otherElements["rootView"].tap() let element = app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element(boundBy: 0) element.swipeUp() self.existsPhotoSliderScrollView(app) } func testCloseWithSwipingDownImage() { let app = XCUIApplication() app.otherElements["rootView"].tap() let element = app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element(boundBy: 0) element.swipeDown() self.existsPhotoSliderScrollView(app) } func testRightRotation() { let app = XCUIApplication() app.otherElements["rootView"].tap() let element = app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element(boundBy: 0) element.swipeLeft() element.swipeLeft() XCUIDevice.shared().orientation = .landscapeRight XCUIDevice.shared().orientation = .portraitUpsideDown XCUIDevice.shared().orientation = .landscapeLeft XCUIDevice.shared().orientation = .portrait app.buttons["NKJPhotoSliderControllerClose"].tap() } func testZooming() { XCUIDevice.shared().orientation = .portrait let app = XCUIApplication() app.otherElements["rootView"].tap() let element = app.scrollViews.matching(identifier: "NKJPhotoSliderScrollView").element(boundBy: 0) element.doubleTap() element.swipeUp() element.swipeDown() element.doubleTap() app.buttons["NKJPhotoSliderControllerClose"].tap() self.existsPhotoSliderScrollView(app) } }
f71d26adcaae07f00b47f989ffd580ce
29.256637
110
0.630301
false
true
false
false
CallMeMrAlex/DYTV
refs/heads/master
DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Home(首页)/Controller/FunnyViewController.swift
mit
1
// // FunnyViewController.swift // DYTV-AlexanderZ-Swift // // Created by Alexander Zou on 2016/10/18. // Copyright © 2016年 Alexander Zou. All rights reserved. // import UIKit private let kTopMargin : CGFloat = 8 class FunnyViewController: BaseAnchorViewController { fileprivate lazy var funnyViewModel : FunnyViewModel = FunnyViewModel() } extension FunnyViewController { override func setupUI() { super.setupUI() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize.zero collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0) } } extension FunnyViewController { override func loadData() { baseViewModel = funnyViewModel funnyViewModel.loadFunnyData { self.collectionView.reloadData() self.loadDataFinished() } } }
04d1432a183a1b8f9e7123eff422e4be
21.659091
97
0.64995
false
false
false
false
googleads/googleads-mobile-ios-examples
refs/heads/main
Swift/admanager/AdaptiveBannerExample/AdaptiveBannerExample/ViewController.swift
apache-2.0
1
// // Copyright (C) 2019 Google, Inc. // // 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 GoogleMobileAds import UIKit let reservationAdUnitID = "/30497360/adaptive_banner_test_iu/reservation" let backfillAdUnitID = "/30497360/adaptive_banner_test_iu/backfill" class ViewController: UIViewController { @IBOutlet weak var bannerView: GAMBannerView! @IBOutlet weak var iuSwitch: UISwitch! @IBOutlet weak var iuLabel: UILabel! var adUnitID: String { return iuSwitch.isOn ? reservationAdUnitID : backfillAdUnitID } var adUnitLabel: String { return adUnitID == reservationAdUnitID ? "Reservation Ad Unit" : "Backfill Ad Unit" } override func viewDidLoad() { super.viewDidLoad() bannerView.rootViewController = self bannerView.backgroundColor = UIColor.gray updateLabel() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillTransition( to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator ) { coordinator.animate(alongsideTransition: { _ in self.loadBannerAd(nil) }) } @IBAction func adUnitIDSwitchChanged(_ sender: Any) { updateLabel() } func updateLabel() { iuLabel.text = adUnitLabel } @IBAction func loadBannerAd(_ sender: Any?) { let frame = { () -> CGRect in if #available(iOS 11.0, *) { return view.frame.inset(by: view.safeAreaInsets) } else { return view.frame } }() let viewWidth = frame.size.width // Replace this ad unit ID with your own ad unit ID. bannerView.adUnitID = adUnitID // Here the current interface orientation is used. Use // GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth or // GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth if you prefer to load an ad of a // particular orientation, let adaptiveSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth) // Note that Google may serve any reservation ads that that are smaller than // the adaptive size as outlined here - https://support.google.com/admanager/answer/9464128. // The returned ad will be centered in the ad view. bannerView.adSize = adaptiveSize bannerView.load(GAMRequest()) } }
dd3a53bb7179654c54e5c596c17a9149
30
96
0.71828
false
false
false
false
JGiola/swift
refs/heads/main
test/Constraints/tuple_arguments.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift -swift-version 5 // See test/Compatibility/tuple_arguments_4.swift for some // Swift 4-specific tests. func concrete(_ x: Int) {} func concreteLabeled(x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} do { concrete(3) concrete((3)) concreteLabeled(x: 3) concreteLabeled(x: (3)) concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}} // expected-error@-1 {{cannot convert value of type '(x: Int)' to expected argument type 'Int'}} concreteTwo(3, 4) concreteTwo((3, 4)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} do { generic(3) generic(3, 4) // expected-error {{extra argument in call}} generic((3)) generic((3, 4)) genericLabeled(x: 3) genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} genericLabeled(x: (3)) genericLabeled(x: (3, 4)) genericTwo(3, 4) genericTwo((3, 4)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } var function: (Int) -> () var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () do { function(3) function((3)) functionTwo(3, 4) functionTwo((3, 4)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } struct Concrete {} extension Concrete { func concrete(_ x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} } do { let s = Concrete() s.concrete(3) s.concrete((3)) s.concreteTwo(3, 4) s.concreteTwo((3, 4)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } extension Concrete { func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} } do { let s = Concrete() s.generic(3) s.generic(3, 4) // expected-error {{extra argument in call}} s.generic((3)) s.generic((3, 4)) s.genericLabeled(x: 3) s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.genericLabeled(x: (3)) s.genericLabeled(x: (3, 4)) s.genericTwo(3, 4) s.genericTwo((3, 4)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } extension Concrete { mutating func mutatingConcrete(_ x: Int) {} mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}} mutating func mutatingConcreteTuple(_ x: (Int, Int)) {} } do { var s = Concrete() s.mutatingConcrete(3) s.mutatingConcrete((3)) s.mutatingConcreteTwo(3, 4) s.mutatingConcreteTwo((3, 4)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } extension Concrete { mutating func mutatingGeneric<T>(_ x: T) {} mutating func mutatingGenericLabeled<T>(x: T) {} mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {} } do { var s = Concrete() s.mutatingGeneric(3) s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}} s.mutatingGeneric((3)) s.mutatingGeneric((3, 4)) s.mutatingGenericLabeled(x: 3) s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.mutatingGenericLabeled(x: (3)) s.mutatingGenericLabeled(x: (3, 4)) s.mutatingGenericTwo(3, 4) s.mutatingGenericTwo((3, 4)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } extension Concrete { var function: (Int) -> () { return concrete } var functionTwo: (Int, Int) -> () { return concreteTwo } // expected-note 5 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () { return concreteTuple } } do { let s = Concrete() s.function(3) s.function((3)) s.functionTwo(3, 4) s.functionTwo((3, 4)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTuple(3, 4) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}} s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}} s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } struct InitTwo { init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init(_:_:)' declared here}} } struct InitTuple { init(_ x: (Int, Int)) {} } struct InitLabeledTuple { init(x: (Int, Int)) {} } do { _ = InitTwo(3, 4) _ = InitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((3, 4)) _ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = InitLabeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } struct SubscriptTwo { subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct SubscriptTuple { subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } } } struct SubscriptLabeledTuple { subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } } } do { let s1 = SubscriptTwo() _ = s1[3, 4] _ = s1[(3, 4)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} let s2 = SubscriptTuple() _ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(3, 4)] } do { let a = 3 let b = 4 let d = (a, b) let s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s1[d] // expected-error {{subscript expects 2 separate arguments}} let s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] let s3 = SubscriptLabeledTuple() _ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} _ = s3[x: (3, 4)] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s1[d] // expected-error {{subscript expects 2 separate arguments}} var s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] } enum Enum { case two(Int, Int) // expected-note 6 {{'two' declared here}} case tuple((Int, Int)) case labeledTuple(x: (Int, Int)) } do { _ = Enum.two(3, 4) _ = Enum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((3, 4)) _ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}} _ = Enum.labeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } struct Generic<T> {} extension Generic { func generic(_ x: T) {} func genericLabeled(x: T) {} func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}} func genericTuple(_ x: (T, T)) {} } do { let s = Generic<Double>() s.generic(3.0) s.generic((3.0)) s.genericLabeled(x: 3.0) s.genericLabeled(x: (3.0)) s.genericTwo(3.0, 4.0) s.genericTwo((3.0, 4.0)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{25-26=}} s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}} s.genericTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}} sTwo.generic((3.0, 4.0)) sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.genericLabeled(x: (3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } extension Generic { mutating func mutatingGeneric(_ x: T) {} mutating func mutatingGenericLabeled(x: T) {} mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple(_ x: (T, T)) {} } do { var s = Generic<Double>() s.mutatingGeneric(3.0) s.mutatingGeneric((3.0)) s.mutatingGenericLabeled(x: 3.0) s.mutatingGenericLabeled(x: (3.0)) s.mutatingGenericTwo(3.0, 4.0) s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{33-34=}} s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.mutatingGenericTuple((3.0, 4.0)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.mutatingGeneric((3.0, 4.0)) sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.mutatingGenericLabeled(x: (3.0, 4.0)) } do { var s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{29-30=}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } extension Generic { var genericFunction: (T) -> () { return generic } var genericFunctionTwo: (T, T) -> () { return genericTwo } // expected-note 3 {{'genericFunctionTwo' declared here}} var genericFunctionTuple: ((T, T)) -> () { return genericTuple } } do { let s = Generic<Double>() s.genericFunction(3.0) s.genericFunction((3.0)) s.genericFunctionTwo(3.0, 4.0) s.genericFunctionTwo((3.0, 4.0)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{33-34=}} s.genericFunctionTuple(3.0, 4.0) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.genericFunctionTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(3.0, 4.0) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.genericFunction((3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } struct GenericInit<T> { init(_ x: T) {} } struct GenericInitLabeled<T> { init(x: T) {} } struct GenericInitTwo<T> { init(_ x: T, _ y: T) {} // expected-note 10 {{'init(_:_:)' declared here}} } struct GenericInitTuple<T> { init(_ x: (T, T)) {} } struct GenericInitLabeledTuple<T> { init(x: (T, T)) {} } do { _ = GenericInit(3, 4) // expected-error {{extra argument in call}} _ = GenericInit((3, 4)) _ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled(x: (3, 4)) _ = GenericInitTwo(3, 4) _ = GenericInitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((3, 4)) _ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} _ = GenericInitLabeledTuple(x: (3, 4)) } do { _ = GenericInit<(Int, Int)>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((3, 4)) _ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInitLabeled<(Int, Int)>(x: (3, 4)) _ = GenericInitTwo<Int>(3, 4) _ = GenericInitTwo<Int>((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((3, 4)) _ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInitLabeledTuple<Int>(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } struct GenericSubscript<T> { subscript(_ x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeled<T> { subscript(x x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptTwo<T> { subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct GenericSubscriptLabeledTuple<T> { subscript(x x: (T, T)) -> Int { get { return 0 } set { } } } struct GenericSubscriptTuple<T> { subscript(_ x: (T, T)) -> Int { get { return 0 } set { } } } do { let s1 = GenericSubscript<(Double, Double)>() _ = s1[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}} _ = s1[(3.0, 4.0)] let s1a = GenericSubscriptLabeled<(Double, Double)>() _ = s1a [x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{14-14=(}} {{23-23=)}} _ = s1a [x: (3.0, 4.0)] let s2 = GenericSubscriptTwo<Double>() _ = s2[3.0, 4.0] _ = s2[(3.0, 4.0)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{19-20=}} let s3 = GenericSubscriptTuple<Double>() _ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}} _ = s3[(3.0, 4.0)] let s3a = GenericSubscriptLabeledTuple<Double>() _ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{13-13=(}} {{22-22=)}} _ = s3a[x: (3.0, 4.0)] } do { let a = 3.0 let b = 4.0 let d = (a, b) let s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s1[(a, b)] _ = s1[d] let s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s2[d] // expected-error {{subscript expects 2 separate arguments}} let s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s1[(a, b)] _ = s1[d] var s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s2[d] // expected-error {{subscript expects 2 separate arguments}} var s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } enum GenericEnum<T> { case one(T) case labeled(x: T) case two(T, T) // expected-note 10 {{'two' declared here}} case tuple((T, T)) } do { _ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.one((3, 4)) _ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled(x: (3, 4)) _ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum.two(3, 4) _ = GenericEnum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((3, 4)) } do { _ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((3, 4)) _ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled(x: (3, 4)) _ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum<Int>.two(3, 4) _ = GenericEnum<Int>.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } protocol Protocol { associatedtype Element } extension Protocol { func requirement(_ x: Element) {} func requirementLabeled(x: Element) {} func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}} func requirementTuple(_ x: (Element, Element)) {} } struct GenericConforms<T> : Protocol { typealias Element = T } do { let s = GenericConforms<Double>() s.requirement(3.0) s.requirement((3.0)) s.requirementLabeled(x: 3.0) s.requirementLabeled(x: (3.0)) s.requirementTwo(3.0, 4.0) s.requirementTwo((3.0, 4.0)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{29-30=}} s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{30-30=)}} s.requirementTuple((3.0, 4.0)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{28-28=)}} sTwo.requirement((3.0, 4.0)) sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{29-29=(}} {{38-38=)}} sTwo.requirementLabeled(x: (3.0, 4.0)) } do { let s = GenericConforms<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } do { var s = GenericConforms<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) var sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } extension Protocol { func takesClosure(_ fn: (Element) -> ()) {} func takesClosureTwo(_ fn: (Element, Element) -> ()) {} func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {} } do { let s = GenericConforms<Double>() s.takesClosure({ _ = $0 }) s.takesClosure({ x in }) s.takesClosure({ (x: Double) in }) s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ _ = $0; _ = $1 }) s.takesClosureTwo({ (x, y) in }) s.takesClosureTwo({ (x: Double, y:Double) in }) s.takesClosureTuple({ _ = $0 }) s.takesClosureTuple({ x in }) s.takesClosureTuple({ (x: (Double, Double)) in }) s.takesClosureTuple({ _ = $0; _ = $1 }) s.takesClosureTuple({ (x, y) in }) s.takesClosureTuple({ (x: Double, y:Double) in }) let sTwo = GenericConforms<(Double, Double)>() sTwo.takesClosure({ _ = $0 }) sTwo.takesClosure({ x in }) sTwo.takesClosure({ (x: (Double, Double)) in }) sTwo.takesClosure({ _ = $0; _ = $1 }) sTwo.takesClosure({ (x, y) in }) sTwo.takesClosure({ (x: Double, y: Double) in }) } do { let _: ((Int, Int)) -> () = { _ = $0 } let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) } let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) } let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }} let _: ((Int, Int)) -> () = { x, y in } // expected-error@-1 {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{40-40= let (x, y) = arg; }} let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0, $1) } let _: (Int, Int) -> () = { t, u in _ = (t, u) } } // rdar://problem/28952837 - argument labels ignored when calling function // with single 'Any' parameter func takesAny(_: Any) {} enum HasAnyCase { case any(_: Any) } do { let fn: (Any) -> () = { _ in } fn(123) fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}} takesAny(123) takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}} _ = HasAnyCase.any(123) _ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}} } // rdar://problem/29739905 - protocol extension methods on Array had // ParenType sugar stripped off the element type func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()], f2: [(Bool, Bool) -> ()], c: Bool) { let p = (c, c) f1.forEach { block in block(p) block((c, c)) block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}} } f2.forEach { block in // expected-note@-1 {{'block' declared here}} block(p) // expected-error {{parameter 'block' expects 2 separate arguments}} } f2.forEach { block in // expected-note@-1 {{'block' declared here}} block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}} block(c, c) } f2.forEach { block in block(c, c) } f2.forEach { (block: ((Bool, Bool)) -> ()) in // expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> Void' to expected argument type '(@escaping (Bool, Bool) -> ()) throws -> Void'}} block(p) block((c, c)) block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} } f2.forEach { (block: (Bool, Bool) -> ()) in // expected-note@-1 {{'block' declared here}} block(p) // expected-error {{parameter 'block' expects 2 separate arguments}} } f2.forEach { (block: (Bool, Bool) -> ()) in // expected-note@-1 {{'block' declared here}} block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}} block(c, c) } f2.forEach { (block: (Bool, Bool) -> ()) in block(c, c) } } // expected-error@+1 {{cannot create a single-element tuple with an element label}} func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) { // TODO: Error could be improved. // expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}} completion((didAdjust: true)) } // SR-4378 final public class MutableProperty<Value> { public init(_ initialValue: Value) {} } enum DataSourcePage<T> { case notLoaded } let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: .notLoaded, totalCount: 0 )) let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage.notLoaded, totalCount: 0 )) let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage<Int>.notLoaded, totalCount: 0 )) // SR-4745 let sr4745 = [1, 2] let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" } // SR-4738 let sr4738 = (1, (2, 3)) [sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-note 2 {{'x' declared here}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{20-20=_: }} // expected-error@-3 {{cannot find 'y' in scope; did you mean 'x'?}} // expected-error@-4 {{cannot find 'z' in scope; did you mean 'x'?}} // rdar://problem/31892961 let r31892961_1 = [1: 1, 2: 2] r31892961_1.forEach { (k, v) in print(k + v) } let r31892961_2 = [1, 2, 3] let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }} val + 1 // expected-error@-1 {{cannot find 'val' in scope}} } let r31892961_3 = (x: 1, y: 42) _ = [r31892961_3].map { (x: Int, y: Int) in x + y } _ = [r31892961_3].map { (x, y: Int) in x + y } let r31892961_4 = (1, 2) _ = [r31892961_4].map { x, y in x + y } let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4))) [r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y } // expected-note {{'x' declared here}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }} // expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}} let r31892961_6 = (x: 1, (y: 2, z: 4)) [r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y } // expected-note {{'x' declared here}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }} // expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}} // rdar://problem/32214649 -- these regressed in Swift 4 mode // with SE-0110 because of a problem in associated type inference func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] { return a.map(f) } func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] { return a.filter(f) } func r32214649_3<X>(_ a: [X]) -> [X] { return a.filter { _ in return true } } // rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters func rdar32301091_1(_ :((Int, Int) -> ())!) {} rdar32301091_1 { _ in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }} func rdar32301091_2(_ :(Int, Int) -> ()) {} rdar32301091_2 { _ in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }} rdar32301091_2 { x in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }} func rdar32875953() { let myDictionary = ["hi":1] myDictionary.forEach { print("\($0) -> \($1)") } myDictionary.forEach { key, value in print("\(key) -> \(value)") } myDictionary.forEach { (key, value) in print("\(key) -> \(value)") } let array1 = [1] let array2 = [2] _ = zip(array1, array2).map(+) } struct SR_5199 {} extension Sequence where Iterator.Element == (key: String, value: String?) { func f() -> [SR_5199] { return self.map { (key, value) in SR_5199() // Ok } } } func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] { let x: [Int] = records.map { _ in let i = 1 return i } let y: [Int] = other.map { _ in let i = 1 return i } return x + y } func itsFalse(_: Int) -> Bool? { return false } func rdar33159366(s: AnySequence<Int>) { _ = s.compactMap(itsFalse) let a = Array(s) _ = a.compactMap(itsFalse) } func sr5429<T>(t: T) { _ = AnySequence([t]).first(where: { (t: T) in true }) } extension Concrete { typealias T = (Int, Int) typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } extension Generic { typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } func rdar33239714() { Concrete().opt1 { x, y in } Concrete().opt1 { (x, y) in } Concrete().opt2 { x, y in } Concrete().opt2 { (x, y) in } Concrete().opt3 { x, y in } Concrete().opt3 { (x, y) in } Concrete().optAliasT { x, y in } Concrete().optAliasT { (x, y) in } Concrete().optAliasF { x, y in } Concrete().optAliasF { (x, y) in } Generic<(Int, Int)>().opt1 { x, y in } Generic<(Int, Int)>().opt1 { (x, y) in } Generic<(Int, Int)>().opt2 { x, y in } Generic<(Int, Int)>().opt2 { (x, y) in } Generic<(Int, Int)>().opt3 { x, y in } Generic<(Int, Int)>().opt3 { (x, y) in } Generic<(Int, Int)>().optAliasT { x, y in } Generic<(Int, Int)>().optAliasT { (x, y) in } Generic<(Int, Int)>().optAliasF { x, y in } Generic<(Int, Int)>().optAliasF { (x, y) in } } // rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above" do { func foo(_: (() -> Void)?) {} func bar() -> ((()) -> Void)? { return nil } foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} } // https://bugs.swift.org/browse/SR-6509 public extension Optional { func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? { return self.flatMap { value in transform.map { $0(value) } } } func apply<Value, Result>(_ value: Value?) -> Result? where Wrapped == (Value) -> Result { return value.apply(self) } } // https://bugs.swift.org/browse/SR-6837 // FIXME: Can't overload local functions so these must be top-level func takePairOverload(_ pair: (Int, Int?)) {} func takePairOverload(_: () -> ()) {} do { func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {} func takePair(_ pair: (Int, Int?)) {} takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}} takeFn(fn: takePairOverload) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}} takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} } // https://bugs.swift.org/browse/SR-6796 do { func f(a: (() -> Void)? = nil) {} func log<T>() -> ((T) -> Void)? { return nil } f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} func logNoOptional<T>() -> (T) -> Void { } f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '() -> Void'}} func g() {} g(()) // expected-error {{argument passed to call that takes no arguments}} func h(_: ()) {} // expected-note {{'h' declared here}} h() // expected-error {{missing argument for parameter #1 in call}} } // https://bugs.swift.org/browse/SR-7191 class Mappable<T> { init(_: T) { } func map<U>(_ body: (T) -> U) -> U { fatalError() } } let x = Mappable(()) x.map { (_: Void) in return () } x.map { (_: ()) in () } // https://bugs.swift.org/browse/SR-9470 do { func f(_: Int...) {} let _ = [(1, 2, 3)].map(f) // expected-error {{no exact matches in call to instance method 'map'}} // expected-note@-1 {{found candidate with type '(((Int, Int, Int)) throws -> _) throws -> Array<_>'}} } // rdar://problem/48443263 - cannot convert value of type '() -> Void' to expected argument type '(_) -> Void' protocol P_48443263 { associatedtype V } func rdar48443263() { func foo<T : P_48443263>(_: T, _: (T.V) -> Void) {} struct S1 : P_48443263 { typealias V = Void } struct S2: P_48443263 { typealias V = Int } func bar(_ s1: S1, _ s2: S2, _ fn: () -> Void) { foo(s1, fn) // Ok because s.V is Void foo(s2, fn) // expected-error {{cannot convert value of type '() -> Void' to expected argument type '(S2.V) -> Void' (aka '(Int) -> ()')}} } } func autoclosureSplat() { func takeFn<T>(_: (T) -> ()) {} takeFn { (fn: @autoclosure () -> Int) in } // This type checks because we find a solution T:= @escaping () -> Int and // wrap the closure in a function conversion. takeFn { (fn: @autoclosure () -> Int, x: Int) in } // expected-error@-1 {{contextual closure type '(() -> Int) -> ()' expects 1 argument, but 2 were used in closure body}} // expected-error@-2 {{converting non-escaping value to 'T' may allow it to escape}} takeFn { (fn: @autoclosure @escaping () -> Int) in } // FIXME: It looks like matchFunctionTypes() does not check @autoclosure at all. // Perhaps this is intentional, but we should document it eventually. In the // interim, this test serves as "documentation"; if it fails, please investigate why // instead of changing the test. takeFn { (fn: @autoclosure @escaping () -> Int, x: Int) in } // expected-error@-1 {{contextual closure type '(@escaping () -> Int) -> ()' expects 1 argument, but 2 were used in closure body}} } func noescapeSplat() { func takesFn<T>(_ fn: (T) -> ()) -> T {} func takesEscaping(_: @escaping () -> Int) {} do { let t = takesFn { (fn: () -> Int) in } takesEscaping(t) // This type checks because we find a solution T:= (@escaping () -> Int). } do { let t = takesFn { (fn: () -> Int, x: Int) in } // expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}} takesEscaping(t.0) } } func variadicSplat() { func takesFnWithVarg(fn: (Int, Int...) -> Void) {} takesFnWithVarg { x in // expected-error {{contextual closure type '(Int, Int...) -> Void' expects 2 arguments, but 1 was used in closure body}} _ = x.1.count } takesFnWithVarg { x, y in _ = y.count } }
04f0c4a319396f2981ad5fb5387a5b89
35.676143
253
0.633813
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Items/Rating/TableRatingItem.swift
mit
1
class TableRatingItem: TableItem { private let trustYou: HDKTrustyou private let shortItems: Bool private let shouldShowSeparator: Bool private let moreHandler: (() -> Void)? init(trustYou: HDKTrustyou, shortItems: Bool, moreHandler: (() -> Void)?, shouldShowSeparator: Bool) { self.trustYou = trustYou self.shortItems = shortItems self.shouldShowSeparator = shouldShowSeparator self.moreHandler = moreHandler } override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: HLHotelDetailsTableRatingCell.hl_reuseIdentifier(), for: indexPath) as! HLHotelDetailsTableRatingCell cell.shortItems = shortItems cell.moreHandler = moreHandler cell.update(withTrustYou: trustYou, tableWidth: tableView.bounds.size.width - HLHotelDetailsTableRatingCell.kHorizontalMargin * 2) cell.shouldShowSeparator = shouldShowSeparator return cell } override func cellHeight(tableWidth: CGFloat) -> CGFloat { let width = tableWidth - HLHotelDetailsTableRatingCell.kHorizontalMargin * 2 return HLHotelDetailsTableRatingCell.estimatedHeight(shortDetails: shortItems, trustyou: trustYou, width: width, shouldShowSeparator: shouldShowSeparator) } }
7d48375e53387725aea04a67665a240c
47
166
0.739583
false
false
false
false
dongdongSwift/guoke
refs/heads/master
gouke/果壳/searchViewController.swift
mit
1
// // searchViewController.swift // 果壳 // // Created by qianfeng on 2016/11/7. // Copyright © 2016年 张冬. All rights reserved. // import UIKit import Alamofire class searchViewController: UIViewController { var customNavBar:UIView? var searchView:SearchList? var searchBar:UITextField? var keyWordsData:keyWordsModel?{ didSet{ initKeyWords() } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor=UIColor.whiteColor() initUI() loadData() } func loadData(){ Alamofire.request(.GET, keywordsUrl).responseData{ [weak self](response) in guard response.result.error == nil else{ return } self!.keyWordsData=keyWordsModel.parseData(response.result.value!) } } func initKeyWords(){ let array=keyWordsData?.result![0].items var x:CGFloat=20 let y:CGFloat=84 let h:CGFloat=25 var row:CGFloat=0 for i in 0..<array!.count{ let w=NSString(string: array![i].text!).boundingRectWithSize(CGSizeMake(screenWidth-20*2, 40), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(18)], context: nil).size.width+20 if (x+w)<=(screenWidth-20) { }else{ row+=1 x=20 } let label=UIButton(frame: CGRectMake(x, y+row*(h+20), w, h)) label.userInteractionEnabled=true label.tag=600+i label.layer.borderWidth=1 label.layer.borderColor=UIColor.brownColor().CGColor label.layer.cornerRadius=5 label.layer.masksToBounds=true label.setTitle(array![i].text!, forState: .Normal) label.setTitleColor(UIColor.brownColor(), forState: .Normal) label.titleLabel?.text=array![i].text! label.titleLabel?.textAlignment = .Center // label.textAlignment = .Center // label.text=array![i].text! x+=w+20 view.addSubview(label) label.addTarget(self, action: #selector(tapAction(_:)), forControlEvents:.TouchUpInside) // let tap=UITapGestureRecognizer(target: self, action: #selector(tapAction(_:))) // tap.numberOfTapsRequired=1 // tap.numberOfTouchesRequired=1 // label.addGestureRecognizer(tap) } } func tapAction(tap:UIButton){ let index=tap.tag-600 let key=keyWordsData?.result![0].items![index].text searchBar?.text=key if searchBar!.isFirstResponder(){ searchBar?.resignFirstResponder()}else{ showList(String(format: searchUrl, "%d",(self.searchBar?.text)!)) } // showSingleton.shareShow.show { [weak self](a) in // self!.showList(String(format: searchUrl, "%d",(self!.searchBar?.text)!)) // } // struct Static { // static var onceToken: dispatch_once_t = 0 // // } // dispatch_once(&Static.onceToken) { // self.showList(String(format: searchUrl, "%d",(self.searchBar?.text)!)) // } // showList(String(format: searchUrl, "%d",(self.searchBar?.text)!)) } func showList(url:String?){ searchView=SearchList(frame: CGRect(x: 0, y: 64, width: screenWidth, height: screenHeight-64), url: url) self.view.addSubview(searchView!) // searchBar?.resignFirstResponder() } func initUI(){ automaticallyAdjustsScrollViewInsets=false customNavBar=UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 64)) customNavBar?.backgroundColor=UIColor.brownColor() self.view.addSubview(customNavBar!) let leftbtn=UIButton.createBtn(UIImage(named:"bar_back_icon")) let rightbtn1=UIButton.createBtn(UIImage(named:"search_ic")) leftbtn.frame=CGRect(x: 5, y: 27, width: 32, height: 32) rightbtn1.frame=CGRect(x: screenWidth-45, y: 27, width: 40, height: 32) leftbtn.tag=104 rightbtn1.tag=105 customNavBar?.addSubview(leftbtn) customNavBar?.addSubview(rightbtn1) leftbtn.addTarget(self, action: #selector(btnClick(_:)), forControlEvents: .TouchUpInside) rightbtn1.addTarget(self, action: #selector(btnClick(_:)), forControlEvents: .TouchUpInside) searchBar=UITextField(frame: CGRect(x: 0, y: 24, width: 200, height: 40)) searchBar?.center.x=(customNavBar?.center.x)! searchBar?.textColor=UIColor.whiteColor() searchBar?.delegate=self searchBar?.attributedPlaceholder=NSAttributedString(string: " 请输入关键词", attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()]) searchBar?.returnKeyType = .Search searchBar?.tintColor=UIColor.whiteColor() searchBar?.clearButtonMode = .Always searchBar?.borderStyle = .None searchBar?.becomeFirstResponder() customNavBar?.addSubview(searchBar!) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardDidHide(_:)), name:UIKeyboardDidHideNotification, object: nil) } func btnClick(btn:UIButton){ if btn.tag==104{ navigationController?.popViewControllerAnimated(true) }else if btn.tag==105{ print("11") if searchBar?.text != ""{ if (searchBar!.isFirstResponder()){ searchBar?.resignFirstResponder() }else{ showList(String(format: searchUrl, "%d",(searchBar?.text)!)) } } } } // 键盘隐藏执行的方法 func keyboardDidHide(not:NSNotification){ if searchBar?.text != ""{ print("keyhide") showList(String(format: searchUrl, "%d",(searchBar?.text)!))}else{ } // searchBar?.resignFirstResponder() } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension searchViewController:UITextFieldDelegate{ func textFieldShouldReturn(textField: UITextField) -> Bool { searchBar?.resignFirstResponder() return true } func textFieldShouldClear(textField: UITextField) -> Bool{ searchView?.removeFromSuperview() searchBar?.resignFirstResponder() return true } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { searchBar?.resignFirstResponder() } }
3b724b56e4be8b38b127802099695294
34.813725
233
0.603012
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/ZDOpenSourceSwiftDemo/Playgrounds/Playground_Codable.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play /*: + [Swift4 终极解析方案:基础篇](http://www.rockerhx.com/2017/09/25/2017-09-25-Swift4-Codable-Basic/) + [Swift4 终极解析方案:进阶篇](http://www.rockerhx.com/2017/09/26/2017-09-26-Swift4-Codable-Ultimate/) */ import UIKit import Foundation var str = "Hello, playground" //------------------------------------------------ struct Person: Codable { let name: String let age: UInt let gender: String let weibo: URL // 只有在 CodingKeys 中指定的属性名才会进行编码; // 如果使用了 CodingKeys,那些没有在 CodingKeys 中声明的属性就必须要要有一个默认值 // 对于可能为nil的字段,归解档时需要用encodeIfPresent、decodeIfPresent归解档 enum CodingKeys: String, CodingKey { case name = "fullName" case gender = "sex" case weibo = "twitter" case age } } extension Person { // 该对象又有三种类型: //Keyed Container:键值对字典类型 //Unkeyed Container:数值类型 //Single Value Container:仅仅输出 raw value init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) age = try container.decode(UInt.self, forKey: CodingKeys.age) gender = try container.decode(String.self, forKey: CodingKeys.gender) weibo = try container.decode(URL.self, forKey: CodingKeys.weibo) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(age, forKey: .age) try container.encode(gender, forKey: .gender) try container.encode(weibo, forKey: .weibo) } } let person = Person(name: "符现超", age: 28, gender: "男", weibo: URL(string: "http://img05.tooopen.com/images/20160121/tooopen_sy_155168162826.jpg")!) let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(person) let encodeString = String(data: data, encoding: .utf8) ?? "" print("对象转json字符串: " + encodeString) let jsonData1 = """ { "fullName": "Federico Zanetello", "age": 26, "sex": "femal" "twitter": "http://twitter.com/zntfdr" } """.data(using: .utf8); let decoder = JSONDecoder() let myStruct1 = try decoder.decode(Person.self, from: jsonData1!) print(myStruct1) ////------------------自定义映射------------------------------ // //enum MyStructKeys: String, CodingKey { // case name = "fullName" // case myId = "id" // case myTwitter = "twitter" //} // //let decoder = JSONDecoder() //let container = try decoder.container(keyedBy: MyStructKeys.self) //------------------------------------------------ enum BeerStyle: String, Codable { case ipa case stout case kolsch } struct Beer: Codable { let name: String let brewery: String let style: BeerStyle } let jsonData2 = """ { "name": "Endeavor", "abv": 8.9, "brewery": "Saint Arnold", "style": "ipa" } """.data(using: .utf8) let myStruct2 = try JSONDecoder().decode(Beer.self, from: jsonData2!) print(myStruct2)
21b574c22ebd2a3cff26fc93060410e7
26.718182
147
0.631355
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TargetSelectionPage/TargetSelectionPageState.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import ToolKit enum TargetSelectionPageStep: Equatable { // TODO: QR Scanning Step case initial case complete case qrScanner case closed var addToBackStack: Bool { switch self { case .closed, .complete, .initial, .qrScanner: return false } } } struct TargetSelectionPageState: Equatable, StateType { static let empty = TargetSelectionPageState() var nextEnabled: Bool = false var isGoingBack: Bool = false var inputValidated: TargetSelectionInputValidation = .empty var sourceAccount: BlockchainAccount? var availableTargets: [TransactionTarget] = [] var destination: TransactionTarget? { didSet { Logger.shared.debug("TransactionTarget: \(String(describing: destination))") } } var stepsBackStack: [TargetSelectionPageStep] = [] var step: TargetSelectionPageStep = .initial { didSet { isGoingBack = false } } var inputRequiresAddressValidation: Bool { inputValidated.requiresValidation } // TODO: Handle alternate destination type // of an address static func == (lhs: TargetSelectionPageState, rhs: TargetSelectionPageState) -> Bool { lhs.nextEnabled == rhs.nextEnabled && lhs.destination?.label == rhs.destination?.label && lhs.sourceAccount?.identifier == rhs.sourceAccount?.identifier && lhs.step == rhs.step && lhs.stepsBackStack == rhs.stepsBackStack && lhs.inputValidated == rhs.inputValidated && lhs.isGoingBack == rhs.isGoingBack && lhs.availableTargets.map(\.label) == rhs.availableTargets.map(\.label) } } extension TargetSelectionPageState { func withUpdatedBackstack(oldState: TargetSelectionPageState) -> TargetSelectionPageState { if oldState.step != step, oldState.step.addToBackStack { var newState = self var newStack = oldState.stepsBackStack newStack.append(oldState.step) newState.stepsBackStack = newStack return newState } return self } }
f5958d27343391d516000f34e473a7d3
28.934211
95
0.638681
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
AwesomeMedia/Classes/Custom Class/AMAVPlayerItem.swift
mit
1
import AVFoundation // MARK: - Responsible for handling the KVO operations that happen on the AVPlayerItem. public enum AwesomeMediaPlayerItemKeyPaths: String { case playbackLikelyToKeepUp case playbackBufferFull case playbackBufferEmpty case status case timeControlStatus } public class AMAVPlayerItem: AVPlayerItem { private var observersKeyPath = [String: NSObject?]() private var keysPathArray: [AwesomeMediaPlayerItemKeyPaths] = [.playbackLikelyToKeepUp, .playbackBufferFull, .playbackBufferEmpty, .status, .timeControlStatus] deinit { for (keyPath, observer) in observersKeyPath { if let observer = observer { self.removeObserver(observer, forKeyPath: keyPath) } } } override public func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) { super.addObserver(observer, forKeyPath: keyPath, options: options, context: context) if let keyPathRaw = AwesomeMediaPlayerItemKeyPaths(rawValue: keyPath), keysPathArray.contains(keyPathRaw) { if let obj = observersKeyPath[keyPath] as? NSObject { self.removeObserver(obj, forKeyPath: keyPath) observersKeyPath[keyPath] = observer } else { observersKeyPath[keyPath] = observer } } } override public func removeObserver(_ observer: NSObject, forKeyPath keyPath: String, context: UnsafeMutableRawPointer?) { super.removeObserver(observer, forKeyPath: keyPath, context: context) observersKeyPath[keyPath] = nil } public override func removeObserver(_ observer: NSObject, forKeyPath keyPath: String) { super.removeObserver(observer, forKeyPath: keyPath) observersKeyPath[keyPath] = nil } }
2dff2df1acca71a3a0e81eb145cdcdd6
39.510638
165
0.690651
false
false
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/Array<UITextField>+WMFAllFieldsFilled.swift
mit
1
// MARK: - Extension for arrays comprised of UITextFields extension Array where Element: UITextField { /// Determines whether all UITextFields in this array have had text characters entered into them. /// /// - Returns: Bool indicating whether all UITextFields in this array have had text characters entered into them. func wmf_allFieldsFilled() -> Bool { let emptyElement: UITextField? = first { (element) -> Bool in guard let text = element.text else { return true } return text.count == 0 } return emptyElement == nil } }
ee138f66ec8eb64947baae52eaf7fc51
37.875
117
0.635048
false
false
false
false
amyjoscelyn/w3r
refs/heads/master
Wither/Wither/Game.swift
mit
1
// // Game.swift // Wither // // Created by Amy Joscelyn on 6/30/16. // Copyright © 2016 Amy Joscelyn. All rights reserved. // import Foundation class Game { let player: Player let aiPlayer: AIPlayer let gameDataStore = GameDataStore.sharedInstance var savePlayerCards: [Card] = [] var saveAICards: [Card] = [] var discardPlayerCards: [Card] = [] var discardAICards: [Card] = [] init() { self.player = Player.init() self.aiPlayer = AIPlayer.init() } func startGame() { self.player.deck.shuffle() self.aiPlayer.deck.shuffle() } func drawHands() { let playerDeckCount = self.player.deck.cards.count let aiPlayerDeckCount = self.aiPlayer.deck.cards.count if playerDeckCount >= 3 && aiPlayerDeckCount >= 3 { // print("PLAYERS HAVE THREE OR MORE CARDS IN HAND") self.player.fillHand() self.aiPlayer.fillHand() } else if playerDeckCount > 0 && aiPlayerDeckCount > 0 { // print("IT'S DOWN TO THE END!!!! (less than three cards in a player's hand)") self.player.fillHandWithSingleCard() self.aiPlayer.fillHandWithSingleCard() } else { print("[inside drawHands()] PLAYER DECK COUNT: \(playerDeckCount) || AI DECK COUNT: \(aiPlayerDeckCount)") print("~~==ooo==~~ game is over! ~~==ooo==~~") } } func twoCardFaceOff(playerCard: Card, aiPlayerCard: Card) -> String { var cardWinner = "" if playerCard.cardValue > aiPlayerCard.cardValue { cardWinner = "Player" } else if playerCard.cardValue < aiPlayerCard.cardValue { cardWinner = "AI" } else { cardWinner = "War" } return cardWinner } func trackCard() { let column = self.player.columnOfHighestCard() print("GameVC column with highest card: \(column)") self.gameDataStore.playerCardTrackerArray.append(column) } func war() {//what happens when there are no more cards left to draw? self.player.dealCardForWar() self.aiPlayer.dealCardForWar() } func warIsDone() { self.player.clearCardsForWar() self.aiPlayer.clearCardsForWar() } func endRound() { self.player.clearHandValues() self.aiPlayer.clearHandValues() self.discardCards() self.saveCards() } func discardCards() { self.player.discard.appendContentsOf(self.discardPlayerCards) self.aiPlayer.discard.appendContentsOf(self.discardAICards) self.discardPlayerCards.removeAll() self.discardAICards.removeAll() } func saveCards() { self.player.deck.cards.appendContentsOf(self.savePlayerCards) self.aiPlayer.deck.cards.appendContentsOf(self.saveAICards) self.savePlayerCards.removeAll() self.saveAICards.removeAll() } }
27770e4bc0395936b69d1726af10b58a
24.723577
118
0.575403
false
false
false
false
PureSwift/BluetoothLinux
refs/heads/master
Sources/BluetoothLinux/HCI/HCIDeviceEvent.swift
mit
1
// // HCIDeviceEvent.swift // // // Created by Alsey Coleman Miller on 16/10/21. // /// HCI dev events public enum HCIDeviceEvent: CInt { case register = 1 case unregister = 2 case up = 3 case down = 4 case suspend = 5 case resume = 6 }
10c045fb3a95a6f8f5949fe6da39f064
17.705882
48
0.506289
false
false
false
false
lparry/Lighting
refs/heads/master
Widget/Color+NSColor.swift
gpl-3.0
2
// // Created by Tate Johnson on 26/07/2015. // Copyright (c) 2015 Tate Johnson. All rights reserved. // import AppKit import LIFXHTTPKit extension Color { // Based on https://github.com/LIFX/LIFXKit/blob/master/LIFXKit/Extensions/Categories-UIKit/UIColor+LFXExtensions.m // which was based on http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ public func toNSColor() -> NSColor { if isWhite { var red: Float = 0.0 var green: Float = 0.0 var blue: Float = 0.0 if kelvin <= 6600 { red = 1.0 } else { red = Float(1.292936186062745) * powf(Float(kelvin) / Float(100.0) - Float(60.0), Float(-0.1332047592)) } if kelvin <= 6600 { green = Float(0.39008157876902) * logf(Float(kelvin) / Float(100.0)) - Float(0.631841443788627) } else { green = Float(1.129890860895294) * powf(Float(kelvin) / Float(100.0) - Float(60.0), Float(-0.0755148492)) } if kelvin >= 6600 { blue = 1.0 } else { if kelvin <= 1900 { blue = 0.0 } else { blue = Float(0.543206789110196) * logf(Float(kelvin) / Float(100.0) - Float(10.0)) - Float(1.19625408914) } } if red < 0.0 { red = 0.0 } else if red > 1.0 { red = 1.0 } if green < 0.0 { green = 0.0 } else if green > 1.0 { green = 1.0 } if blue < 0.0 { blue = 0.0 } else if blue > 1.0 { blue = 1.0 } return NSColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: 1.0) } else { return NSColor(hue: CGFloat(hue) / 360.0, saturation: CGFloat(saturation), brightness: 1.0, alpha: 1.0) } } }
1fa494ecc98b3dbf51992d6782e9077f
25.295082
116
0.607855
false
false
false
false
Arcovv/CleanArchitectureRxSwift
refs/heads/master
Network/Entries/Comment+Mapping.swift
mit
1
// // Comment+Mapping.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Domain import ObjectMapper extension Comment: ImmutableMappable { // JSON -> Object public init(map: Map) throws { body = try map.value("body") email = try map.value("email") name = try map.value("name") postId = try map.value("postId", using: UidTransform()) uid = try map.value("id", using: UidTransform()) } }
f1403bbd38ab227e8ca49f4ebc5be231
23.545455
63
0.62963
false
false
false
false
Antuaaan/ECWeather
refs/heads/master
ECWeather/Pods/SwiftSky/Source/Url.swift
mit
1
// // Url.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Foundation import CoreLocation struct ApiUrl { private let base = "https://api.darksky.net/forecast" let url : URL init(_ location: Location, date : Date?, exclude : [DataType]) { var urlString = "\(base)/\(SwiftSky.secret ?? "NO_API_KEY")/\(location.latitude),\(location.longitude)" if let time = date { let timeString = String(format: "%.0f", time.timeIntervalSince1970) urlString.append(",\(timeString)") } var builder = URLComponents(string: urlString) var items : [URLQueryItem] = [ URLQueryItem(name: "lang", value: SwiftSky.language.shortcode), URLQueryItem(name: "units", value: SwiftSky.units.shortcode) ] if SwiftSky.hourAmount == .hundredSixtyEight { items.append(URLQueryItem(name: "extend", value: "hourly")) } if !exclude.isEmpty { var excludeString = "" for type in exclude { if !excludeString.isEmpty { excludeString.append(",") } excludeString.append(type.rawValue) } items.append(URLQueryItem(name: "exclude", value: excludeString)) } builder?.queryItems = items url = builder!.url! } }
aefc08e00590dd4c60ce444f01b9b381
29.583333
111
0.569482
false
false
false
false
AnasAlhasani/Metallica
refs/heads/master
Metallica/Views/AlbumView.swift
mit
1
// // AlbumView.swift // Metallica // // Created by Anas on 9/26/17. // Copyright © 2017 Anas Alhasani. All rights reserved. // import UIKit class AlbumView: UIView { @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var dateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() imageView.layer.cornerRadius = 10 imageView.layer.masksToBounds = true } var album: Album? { didSet{ if let album = album { imageView.image = album.image titleLabel.text = album.title dateLabel.text = album.date } } } private func prepareForAnimation(viewWidth width: CGFloat) { imageView.center.x += width titleLabel.center.x += width dateLabel.center.x += width } func setViewsHidden(_ isHidden: Bool) { imageView.isHidden = isHidden titleLabel.isHidden = isHidden dateLabel.isHidden = isHidden } func startAnimation(direction: ScrollDirection) { let viewWidth = direction == .right ? bounds.width: -bounds.width setViewsHidden(false) prepareForAnimation(viewWidth: viewWidth) UIView.animate(withDuration: 0.6) { [weak self] in guard let strongSelf = self else { return } strongSelf.imageView.center.x -= viewWidth } UIView.animate(withDuration: 0.6, delay: 0.2, options: [], animations: { [weak self] in guard let strongSelf = self else { return } strongSelf.titleLabel.center.x -= viewWidth }, completion: nil) UIView.animate(withDuration: 0.6, delay: 0.3, options: [], animations: { [weak self] in guard let strongSelf = self else { return } strongSelf.dateLabel.center.x -= viewWidth }, completion: nil) } }
7c23d766f91551b57f32bdd9f479da04
28.028986
95
0.595607
false
false
false
false
cuappdev/podcast-ios
refs/heads/master
Recast/Discover/DiscoverViewController.swift
mit
1
// // DiscoverViewController.swift // Recast // // Created by Jaewon Sim on 11/7/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit import SnapKit enum EpisodeDuration: String, CaseIterable { case asap = "Gotta Go ASAP" case moment = "A Moment to Spare" case relax = "Kick Back & Relax" case longRide = "In for a Long Ride" /// The range of the duration of the podcast, in minutes. /// /// - Returns: A tuple in the form of (inclusive lower bound, exclusive upper bound), i.e. [first,second). var durationRange: (Int, Int) { switch self { case .asap: return (10, 15) case .moment: return (20, 30) case .relax: return (40, 50) case .longRide: return (60, 90) } } var faceImage: UIImage { switch self { case .asap: return #imageLiteral(resourceName: "red") case .moment: return #imageLiteral(resourceName: "yellow") case .relax: return #imageLiteral(resourceName: "blue") case .longRide: return #imageLiteral(resourceName: "green") } } } class DiscoverViewController: UIViewController { // MARK: - Variables var titleLabel: UILabel! var durationSelectorCollectionView: UICollectionView! var durationSelectorPageControl: UIPageControl! let durationSelectorReuse = "durationSelectorReuse" // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black titleLabel = UILabel() titleLabel.text = "How much time do you have right now?" titleLabel.font = .systemFont(ofSize: 24, weight: .medium) titleLabel.textColor = .white titleLabel.lineBreakMode = .byWordWrapping titleLabel.numberOfLines = 2 view.addSubview(titleLabel) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: view.frame.width, height: view.frame.width * 2/3) durationSelectorCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) durationSelectorCollectionView.delegate = self durationSelectorCollectionView.dataSource = self durationSelectorCollectionView.backgroundColor = .black durationSelectorCollectionView.showsVerticalScrollIndicator = false durationSelectorCollectionView.showsHorizontalScrollIndicator = false durationSelectorCollectionView.isPagingEnabled = true view.addSubview(durationSelectorCollectionView) durationSelectorCollectionView.register(DiscoverCollectionViewCell.self, forCellWithReuseIdentifier: durationSelectorReuse) durationSelectorPageControl = UIPageControl() durationSelectorPageControl.numberOfPages = durationSelectorCollectionView.numberOfItems(inSection: 0) view.addSubview(durationSelectorPageControl) setUpConstraints() } func setUpConstraints() { // MARK: Layout constants let searchBarTitleLabelHorizontalSpacing: CGFloat = 10.3 let titleLabelCollectionViewHorizontalSpacing: CGFloat = 28.7 let collectionViewPageControlVerticalSpacing: CGFloat = 12 let titleLabelSideInset: CGFloat = 33 let collectionViewHeight: CGFloat = 450 titleLabel.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(searchBarTitleLabelHorizontalSpacing) make.leading.trailing.equalTo(view.safeAreaLayoutGuide).inset(titleLabelSideInset) } durationSelectorCollectionView.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(titleLabelCollectionViewHorizontalSpacing) make.height.equalTo(collectionViewHeight) make.leading.trailing.equalToSuperview() } durationSelectorPageControl.snp.makeConstraints { make in make.top.equalTo(durationSelectorCollectionView.snp.bottom).offset(collectionViewPageControlVerticalSpacing) make.centerX.equalTo(durationSelectorCollectionView) } } } // MARK: - CV Delegate extension DiscoverViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollViewOffsetRatio = scrollView.contentOffset.x / scrollView.frame.width durationSelectorPageControl.currentPage = Int(scrollViewOffsetRatio) } } // MARK: - CV Data Source extension DiscoverViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return EpisodeDuration.allCases.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // swiftlint:disable:next force_cast let cell = collectionView.dequeueReusableCell(withReuseIdentifier: durationSelectorReuse, for: indexPath) as! DiscoverCollectionViewCell cell.faceImageView.image = EpisodeDuration.allCases[indexPath.item].faceImage cell.durationDescriptionLabel.text = EpisodeDuration.allCases[indexPath.item].rawValue let durationRange = EpisodeDuration.allCases[indexPath.item].durationRange cell.minutesLabel.text = "\(durationRange.0) - \(durationRange.1) mins" return cell } }
18a0248c69490234ca9087b9c08555b1
38.926471
144
0.717864
false
false
false
false
PseudoSudoLP/Bane
refs/heads/master
Carthage/Checkouts/PromiseKit/Tests/Promises:A+ Specs/2.2.4.swift
apache-2.0
2
import PromiseKit import XCTest class Test224: XCTestCase { // 2.2.4: `onFulfilled` or `onRejected` must not be called until // the execution context stack contains only platform code func test2241() { // `then` returns before the promise becomes fulfilled or rejected suiteFulfilled(1) { (promise, exes, dummy)->() in var thenHasReturned = false promise.then { _->() in XCTAssert(thenHasReturned) exes[0].fulfill() } thenHasReturned = true } suiteRejected(1) { (promise, exes, memo)->() in var catchHasReturned = false promise.catch { _->() in XCTAssert(catchHasReturned) exes[0].fulfill() } catchHasReturned = true } } // Clean-stack execution ordering tests (fulfillment case) func test2242_1() { // when `onFulfilled` is added immediately before the promise is fulfilled let (promise, fulfiller, _) = Promise<Int>.defer() var onFulfilledCalled = false fulfiller(dummy) promise.then{ _->() in onFulfilledCalled = true } XCTAssertFalse(onFulfilledCalled) } func test2242_2() { // when one `onFulfilled` is added inside another `onFulfilled` let promise = Promise(dummy) var firstOnFulfilledFinished = false let ex = expectationWithDescription("") promise.then { _->() in promise.then { _->() in XCTAssert(firstOnFulfilledFinished) ex.fulfill() } firstOnFulfilledFinished = true } waitForExpectationsWithTimeout(1, handler: nil) } func test2242_3() { // when `onFulfilled` is added inside an `onRejected` let err = NSError(domain: "a", code: 1, userInfo: nil) let resolved = Promise(dummy) let rejected = Promise<Int>(dammy) var firstOnRejectedFinished = false let ex = expectationWithDescription("") rejected.catch { _->() in resolved.then { _->() in XCTAssert(firstOnRejectedFinished) ex.fulfill() } firstOnRejectedFinished = true } waitForExpectationsWithTimeout(1, handler: nil) } func test2242_4() { // when the promise is fulfilled asynchronously let (promise, fulfiller, _) = Promise<Int>.defer() var firstStackFinished = false let ex = expectationWithDescription("") later { fulfiller(dummy) firstStackFinished = true } promise.then { _->() in XCTAssert(firstStackFinished) ex.fulfill() } waitForExpectationsWithTimeout(1, handler: nil) } // Clean-stack execution ordering tests (rejection case) func test2243() { // when `onRejected` is added immediately before the promise is rejected let (promise, _, rejecter) = Promise<Int>.defer() var onRejectedCalled = false promise.catch{ _->() in onRejectedCalled = true } rejecter(dammy) XCTAssertFalse(onRejectedCalled) } func test2244() { // when `onRejected` is added immediately after the promise is rejected let (promise, _, rejecter) = Promise<Int>.defer() var onRejectedCalled = false rejecter(dammy) promise.catch{ _->() in onRejectedCalled = true } XCTAssertFalse(onRejectedCalled) } func test2245() { // when `onRejected` is added inside an `onFulfilled` let resolved = Promise(dummy) let rejected = Promise<Int>(dammy) var firstOnFulfilledFinished = false let ex = expectationWithDescription("") resolved.then{ _->() in rejected.catch{ _->() in XCTAssert(firstOnFulfilledFinished) ex.fulfill() } firstOnFulfilledFinished = true } waitForExpectationsWithTimeout(1, handler: nil) } func test2246() { // when one `onRejected` is added inside another `onRejected` let promise = Promise<Int>(dammy) var firstOnRejectedFinished = false let ex = expectationWithDescription("") promise.catch{ _->() in promise.catch{ _->() in XCTAssertTrue(firstOnRejectedFinished) ex.fulfill() } firstOnRejectedFinished = true } waitForExpectationsWithTimeout(1, handler: nil) } func test2247() { // when the promise is rejected asynchronously let (promise, _, rejecter) = Promise<Int>.defer() var firstStackFinished = false let ex = expectationWithDescription("") later { rejecter(dammy) firstStackFinished = true } promise.catch{ _->() in XCTAssert(firstStackFinished) ex.fulfill() } waitForExpectationsWithTimeout(1, handler: nil) } }
29312c668544f8d372eb37cf9fe09bd2
28.855491
82
0.566699
false
true
false
false
TotemTraining/PracticaliOSAppSecurity
refs/heads/master
V1/Keymaster/Keymaster/CategoriesCollectionViewController.swift
mit
5
// // CategoriesCollectionViewController.swift // Keymaster // // Created by Chris Forant on 4/22/15. // Copyright (c) 2015 Totem. All rights reserved. // import UIKit let reuseIdentifier = "Cell" let highlightColor = UIColor(red:0.99, green:0.67, blue:0.16, alpha:1) class CategoriesCollectionViewController: UICollectionViewController { let categories = ["Household" , "Finance", "Computer", "Mobile", "Email", "Shopping", "User Accounts", "Secrets", "Music", "ID", "Biometrics", "Media"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "SEGUE_ENTRIES": let vc = segue.destinationViewController as! EntriesViewController if let selectedIndex = (collectionView?.indexPathsForSelectedItems().last as? NSIndexPath)?.row { vc.category = categories[selectedIndex] } default: return } } } } // MARK: - Collection View Datasource extension CategoriesCollectionViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return count(categories) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCell // Configure the cell cell.categoryImageView.image = UIImage(named: categories[indexPath.row]) cell.categoryImageView.highlightedImage = UIImage(named: categories[indexPath.row])?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionHeader", forIndexPath: indexPath) as! SectionHeaderView case UICollectionElementKindSectionFooter: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionFooter", forIndexPath: indexPath) as! SectionFooterView default: return UICollectionReusableView() } } override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) cell?.contentView.backgroundColor = highlightColor } override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) cell?.contentView.backgroundColor = UIColor.clearColor() } }
b2c617891089f07772c2f81557255308
42.320513
202
0.717964
false
false
false
false
NOTIFIT/notifit-ios-swift-sdk
refs/heads/master
Pod/Classes/NTFConstants.swift
mit
1
// // NTFConstants.swift // Pods // // Created by Tomas Sykora, jr. on 17/03/16. // // import UIKit import Foundation struct NTFConstants { struct api { struct router { static let baseURL = "http://notifit.io/api/" static let register = NTFConstants.api.router.baseURL + "DeviceApple" static let logState = NTFConstants.api.router.baseURL + "ApplicationState" static let keyValue = NTFConstants.api.router.baseURL + "KeyValues" } static let applicationState = "state" } struct value { static let communicationToken = "Communication-Token" static let projectToken = "ProjectToken" static let applicationToken = "ApplicationToken" } struct state { static let launch = "Launch" static let resignActive = "ResignActive" static let enterBackground = "EnterBackground" static let enterForeground = "EnterForeground" static let becomeActive = "BecomeActive" static let terminate = "Terminate" } } enum NTFMethod: String { case POST = "POST" case PUT = "PUT" } enum NTFAppState: String { case LAUNCH = "Launch" case RESIGNACTIVE = "ResignActive" case ENTERBACKGROUND = "EnterBackground" case ENTERFOREGROUND = "EnterForeground" case BECOMEACTIVE = "BecomeActive" case TERMINATE = "Terminate" }
c346a8ff889f39c09a491c3366a19fd0
26.215686
86
0.653929
false
false
false
false
SteveRohrlack/CitySimCore
refs/heads/master
src/Model/City/CityMap.swift
mit
1
/// /// CityMap.swift /// CitySimCore /// /// Created by Steve Rohrlack on 13.05.16. /// Copyright © 2016 Steve Rohrlack. All rights reserved. /// import Foundation import GameplayKit /** CityMap encapsules all aspects of working with the simulation's underlying map data. It provides a high level api to add and remove tiles. The CityMap consist of multiple layers - TileLayer holding all visible tiles - StatisticlayersContainer holding all statistical layers Additionaly, the CityMap contains a Graph representation of Locations that are RessourceCyrrying. CityMap emits events, see CityMapEvent: - AddTile: when a tile was successfully added, payload: new tile - RemoveTile: when a tile was successfully removed, payload: removed tile */ public struct CityMap: EventEmitting { typealias EventNameType = CityMapEvent /// Container holding event subscribers var eventSubscribers: [EventNameType: [EventSubscribing]] = [:] /// height of the map / height of all layers public private(set) var height: Int /// width of the map / width of all layers public private(set) var width: Int /// the tile layer public var tileLayer: TileLayer /// Container holding statistical layers public var statisticsLayerContainer: StatisticlayersContainer /// pathfinding graph var trafficLayer: GKGridGraph /** Constructur - parameter height: height of the map / height of all layers - parameter width: width of the map / width of all layers */ init(height: Int, width: Int) { self.width = width self.height = height self.tileLayer = TileLayer(rows: height, columns: width) self.statisticsLayerContainer = StatisticlayersContainer(height: height, width: width) self.trafficLayer = GKGridGraph(fromGridStartingAt: vector_int2(0, 0), width: Int32(width), height: Int32(height), diagonalsAllowed: false) //empty graph if let nodes = self.trafficLayer.nodes { self.trafficLayer.removeNodes(nodes) } } // MARK: add, remove /** convenience method to check if a tile can be added to the tile layer also checks dependencies for tiles to be added: must be placed near road - parameter tile: tile to be added throws: CityMapError.TileCantFit if the new tile doesn't fit into the tile layer throws: CityMapError.CannotAddBecauseNotEmpty if the desired tile location is already in use throws: CityMapError.PlaceNearStreet if the tile should be placed adjecant to a street ploppable and isn't */ func canAdd(tile newTile: Tileable) throws { /// check if new tile can fit into the map guard newTile.originY >= 0 && newTile.originX >= 0 && newTile.maxY < height && newTile.maxX < width else { throw CityMapError.TileCantFit } /// check if desired location is already in use let locationUsedByTiles = tileLayer.usedByTilesAt(location: newTile) guard locationUsedByTiles.count == 0 else { throw CityMapError.CannotAddBecauseNotEmpty } /// check if tile should be placed near a street guard newTile is PlaceNearStreet else { return } let check = newTile + 1 let checkLocationUsedByTiles = tileLayer.usedByTilesAt(location: check) let adjecantStreet = checkLocationUsedByTiles.contains { (tile: Tileable) in guard case .Ploppable(let ploppType) = tile.type where ploppType == .Street else { return false } return true } if !adjecantStreet { throw CityMapError.PlaceNearStreet } } /** private method to add a tile - parameter tile: the tile to be added emits the event "AddTile" throws: TileLayerError if there was a problem throws: unspecified error if the event "AddTile" throws */ private mutating func add(tile tile: Tileable) throws { try canAdd(tile: tile) try tileLayer.add(tile: tile) /// adding map statistics for supporting tile if let mapStatistical = tile as? MapStatistical { statisticsLayerContainer.addStatistics( at: tile, statistical: mapStatistical ) } /// adding graph nodes for supporting tile if tile is RessourceCarrying { trafficLayer.add(location: tile) } /// emit event try emit(event: CityMapEvent.AddTile, payload: tile) } // MARK: remove, info /** checks if removing all tiles specified by the given location is possible - parameter location: location throws CityMapError.TileNotRemoveable if a tile requested to be removed is of type "TileNotRemoveable" */ public func canRemoveAt(location location: Locateable) throws { let tilesToRemove = tileLayer.usedByTilesAt(location: location) for tile in tilesToRemove { if tile is NotRemoveable { throw CityMapError.TileNotRemoveable } } } /** removes all tiles specified by the given location - parameter location: location emits the event "RemoveTile" throws CityMapError.TileNotRemoveable if a tile requested to be removed is of type "TileNotRemoveable" throws: unspecified error if the event "RemoveTile" throws */ public mutating func removeAt(location location: Locateable) throws { let tilesToRemove = tileLayer.usedByTilesAt(location: location) for tile in tilesToRemove { if tile is NotRemoveable { throw CityMapError.TileNotRemoveable } tileLayer.remove(tile: tile) /// removing map statistics for supporting tile if let mapStatistical = tile as? MapStatistical { statisticsLayerContainer.removeStatistics( at: tile, statistical: mapStatistical ) } /// removing graph nodes for supporting tile if tile is RessourceCarrying { trafficLayer.remove(location: tile) } /// emit event try emit(event: CityMapEvent.RemoveTile, payload: tile) } } /** convenience method to retrieve a list of tiles specified by the given location - parameter location: location - returns: list of tiles contained in location */ public func infoAt(location location: Locateable) -> [Tileable] { return tileLayer.usedByTilesAt(location: location) } // MARK: zone, plopp, prop /** add a "Zone" (zoneable) to the tile layer - parameter zone: the zone to add throws: TileLayerError if there was a problem */ public mutating func zone(zone zone: Zoneable) throws { try add(tile: zone) } /** add a "Plopp" (ploppable) to the tile layer - parameter plopp: the ploppable to add throws: TileLayerError if there was a problem */ public mutating func plopp(plopp plopp: Ploppable) throws { try add(tile: plopp) } /** add a "Prop" (propable) to the tile layer - parameter prop: the propable to add throws: TileLayerError if there was a problem */ public mutating func prop(prop prop: Propable) throws { try add(tile: prop) } }
918b8b763d0d9c8ecc299183e482c822
29.964427
147
0.620883
false
false
false
false
britez/sdk-ios
refs/heads/master
sdk_ios_v2/Models/PaymentTokenResponse.swift
mit
1
// // PaymentToken.swift // import Foundation open class PaymentTokenResponse: JSONEncodable { public var id: String? public var status: String? public var cardNumberLength: Double? public var dateCreated: String? public var bin: String? public var lastFourDigits: String? public var securityCodeLength: Double? public var expirationMonth: Double? public var expirationYear: Double? public var dateDue: String? public var cardholder: CardHolder? public init() {} // MARK: JSONEncodable open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id nillableDictionary["status"] = self.status nillableDictionary["card_number_length"] = self.cardNumberLength nillableDictionary["date_created"] = self.dateCreated nillableDictionary["bin"] = self.bin nillableDictionary["last_four_digits"] = self.lastFourDigits nillableDictionary["security_code_length"] = self.securityCodeLength nillableDictionary["expiration_month"] = self.expirationMonth nillableDictionary["expiration_year"] = self.expirationYear nillableDictionary["date_due"] = self.dateDue nillableDictionary["cardholder"] = self.cardholder?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } open func toString() -> String { var paymentTokenText = "[\n" paymentTokenText += "id: \(self.id!) \n" paymentTokenText += "status: \(self.status!) \n" paymentTokenText += "bin: \(self.bin!) \n" paymentTokenText += "lastFourDigits: \(self.lastFourDigits!) \n" paymentTokenText += "dateCreated \(self.dateCreated!) \n" paymentTokenText += "dateDue \(self.dateDue!) \n" paymentTokenText += "]" return paymentTokenText } }
dfbb3ac9d7011f66dba4550ce60ac414
33.241379
85
0.650554
false
false
false
false
lennet/CycleHack_AR
refs/heads/master
CycleHack_AR/Model/GeoFeatureCollection.swift
mit
1
// // GeoFeatureCollection.swift // CycleHack_AR // // Created by Leo Thomas on 16.09.17. // Copyright © 2017 CycleHackBer. All rights reserved. // import Foundation struct StreetFeatureCollection: Codable { var type: String var features: [GeoFeature<Street, [[[Double]]]>] } extension StreetFeatureCollection { init() { let path = Bundle.main.path(forResource: "streets", ofType: "geojson") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) self = try! JSONDecoder().decode(StreetFeatureCollection.self, from: data) } } struct PointFeatureCollection: Codable { var type: String var features: [GeoFeature<Point, [Double]>] } extension PointFeatureCollection { init() { let path = Bundle.main.path(forResource: "points", ofType: "geojson") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) self = try! JSONDecoder().decode(PointFeatureCollection.self, from: data) } } struct GeoFeatureCollection<T: Codable, P: Codable>: Codable { var type: String var features: [GeoFeature<T, P>] }
f9545cc93ab71c715c4665f2137901a3
24.545455
82
0.66726
false
false
false
false
orta/SignalKit
refs/heads/master
SignalKitTests/Extensions/UIKit/UISlider+SignalTests.swift
mit
1
// // UISlider+SignalTests.swift // SignalKit // // Created by Yanko Dimitrov on 8/16/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import XCTest class UISlider_SignalTests: XCTestCase { var slider: MockSlider! var signalsBag: SignalBag! override func setUp() { super.setUp() signalsBag = SignalBag() slider = MockSlider() slider.maximumValue = 20 } func testObserveValueChanges() { var result: Float = 0 slider.observe().valueChanges .next { result = $0 } .addTo(signalsBag) slider.value = 10 slider.sendActionsForControlEvents(.ValueChanged) XCTAssertEqual(result, 10, "Should observe for value changes in UISlider") } func testObserveCurrentValue() { var result: Float = 0 slider.value = 10 slider.observe().valueChanges .next { result = $0 } .addTo(signalsBag) XCTAssertEqual(result, 10, "Should dispatch the current value from UISlider") } func testBindToValue() { let signal = MockSignal<Float>() signal.dispatch(5) signal.bindTo(valueIn: slider).addTo(signalsBag) XCTAssertEqual(slider.value, 5, "Should bind a Float value to the value property of UISlider") } }
ef5f88739e4b5354e756aace22745b67
22.934426
102
0.566438
false
true
false
false
Roommate-App/roomy
refs/heads/acceptance
eXoSnapshots/SnapshotHelper.swift
lgpl-3.0
4
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication) { Snapshot.setupSnapshot(app) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication) { Snapshot.app = app do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { print(error) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } print("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work sleep(1) // Waiting for the animation to be finished (kind of) #if os(OSX) XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard let app = self.app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let screenshot = app.windows.firstMatch.screenshot() guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") do { try screenshot.pngRepresentation.write(to: path) } catch let error { print("Problem writing screenshot: \(name) to \(path)") print(error) } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif let networkLoadingIndicator = XCUIApplication().otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else #if arch(i386) || arch(x86_64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasWhiteListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasWhiteListedIdentifier: Bool { let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return whiteListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { let deviceWidth = XCUIApplication().frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.9]
255a5d21fbbcd0cadea4d3a4a2d7bd81
36.873188
158
0.640103
false
false
false
false
quangvu1994/Exchange
refs/heads/master
Exchange/View/RequestTableViewCell.swift
mit
1
// // RequestTableViewCell.swift // Exchange // // Created by Quang Vu on 7/17/17. // Copyright © 2017 Quang Vu. All rights reserved. // import UIKit class RequestTableViewCell: UITableViewCell { @IBOutlet weak var poster: UILabel! @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var briefDescription: UILabel! @IBOutlet weak var status: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code itemImage.layer.masksToBounds = true itemImage.layer.cornerRadius = 3 } func setStatus(status: String) { self.status.text = status if status == "Accepted" { self.status.textColor = UIColor(red: 121/255, green: 189/255, blue: 143/255, alpha: 1.0) } else if status == "Rejected" { self.status.textColor = UIColor(red: 220/255, green: 53/255, blue: 34/255, alpha: 1.0) } else { self.status.textColor = UIColor(red: 79/255, green: 146/255, blue: 193/255, alpha: 1.0) } } }
1db0bc9dcb28913018ad59f0f0332382
28.416667
100
0.624174
false
false
false
false
M-Hamed/photo-editor
refs/heads/master
iOSPhotoEditor/PhotoEditor+UITextView.swift
mit
2
// // PhotoEditor+UITextView.swift // Pods // // Created by Mohamed Hamed on 6/16/17. // // import Foundation import UIKit extension PhotoEditorViewController: UITextViewDelegate { public func textViewDidChange(_ textView: UITextView) { let rotation = atan2(textView.transform.b, textView.transform.a) if rotation == 0 { let oldFrame = textView.frame let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height:CGFloat.greatestFiniteMagnitude)) textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height) } } public func textViewDidBeginEditing(_ textView: UITextView) { isTyping = true lastTextViewTransform = textView.transform lastTextViewTransCenter = textView.center lastTextViewFont = textView.font! activeTextView = textView textView.superview?.bringSubviewToFront(textView) textView.font = UIFont(name: "Helvetica", size: 30) UIView.animate(withDuration: 0.3, animations: { textView.transform = CGAffineTransform.identity textView.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 5) }, completion: nil) } public func textViewDidEndEditing(_ textView: UITextView) { guard lastTextViewTransform != nil && lastTextViewTransCenter != nil && lastTextViewFont != nil else { return } activeTextView = nil textView.font = self.lastTextViewFont! UIView.animate(withDuration: 0.3, animations: { textView.transform = self.lastTextViewTransform! textView.center = self.lastTextViewTransCenter! }, completion: nil) } }
de964d0289ed505aab49c4e267768794
35.566038
120
0.604231
false
false
false
false
mapzen/ios
refs/heads/master
MapzenSDK/Themes.swift
apache-2.0
1
// // Themes.swift // ios-sdk // // Created by Matt Smollinger on 9/28/17. // Copyright © 2017 Mapzen. All rights reserved. // import Foundation /** This is the foundational code for custom stylesheet and theme support. This area will likely be the focus of updates & changes over the next several releases, so we would recommend avoiding implementing your own custom stylesheet classes until we have further vetted this implementation. Documentation will be written once we've solidified on the protocol requirements and implementation details. We do however welcome suggestions / improvements to this API on our github at https://github.com/mapzen/ios */ @objc(MZStyleSheet) public protocol StyleSheet : class { @objc var fileLocation: URL? { get } @objc var remoteFileLocation: URL? { get } @objc var styleSheetRoot: String { get } @objc var houseStylesRoot: String { get } @objc var styleSheetFileName: String { get } @objc var importString: String { get } @objc var relativePath: String { get } @objc var mapStyle: MapStyle { get } @objc var yamlString: String { get } @objc var detailLevel: Int { get set } @objc var labelLevel: Int { get set } @objc var currentColor: String { get set } @objc var availableColors: [ String ] { get } @objc var availableDetailLevels: Int { get } @objc var availableLabelLevels: Int { get } } @objc(MZBaseStyle) open class BaseStyle: NSObject, StyleSheet { @objc open var detailLevel: Int = 0 @objc open var labelLevel: Int = 0 @objc open var currentColor: String = "" @objc open var mapStyle: MapStyle { get { return .none } } @objc open var styleSheetFileName: String { get { return "" } } @objc open var styleSheetRoot: String { get { return "" } } @objc open var fileLocation: URL? { get { return Bundle.houseStylesBundle()?.url(forResource: relativePath, withExtension: "yaml") } } @objc open var remoteFileLocation: URL? { get { return nil } } @objc open var houseStylesRoot: String { get { return "housestyles.bundle/" } } @objc open var importString: String { get { return "{ import: [ \(relativePath).yaml, \(yamlString) ] }" } } @objc open var relativePath: String { get { return "\(styleSheetRoot)\(styleSheetFileName)" } } @objc open var yamlString: String { get { return "" } } @objc open var availableColors: [String] { get { return [] } } @objc open var availableDetailLevels: Int { get { return 0 } } @objc open var availableLabelLevels: Int { get { return 0 } } } //MARK:- Bubble Wrap @objc(MZBubbleWrapStyle) open class BubbleWrapStyle: BaseStyle { public override init() { super.init() defer { currentColor = "" // Not used for Bubble Wrap labelLevel = 5 detailLevel = 0 // Not used for Bubble Wrap } } @objc open override var mapStyle: MapStyle { get { return .bubbleWrap } } @objc open override var styleSheetFileName: String { get { return "bubble-wrap-style" } } @objc open override var styleSheetRoot: String { get { return "bubble-wrap/" } } @objc override open var availableLabelLevels: Int { get { return 12 } } @objc override open var yamlString: String { get { return "\(styleSheetRoot)themes/label-\(labelLevel).yaml" } } } //MARK:- Cinnnabar @objc(MZCinnabarStyle) open class CinnabarStyle: BaseStyle { public override init() { super.init() defer { currentColor = "" // Not used for Cinnabar labelLevel = 5 detailLevel = 0 // Not used for Cinnabar } } @objc open override var mapStyle: MapStyle { get { return .cinnabar } } @objc override open var styleSheetFileName: String { get { return "cinnabar-style" } } @objc override open var styleSheetRoot: String { get { return "cinnabar/" } } @objc override open var availableLabelLevels: Int { get { return 12 } } @objc override open var yamlString: String { get { return "\(styleSheetRoot)themes/label-\(labelLevel).yaml" } } } //MARK:- Refill @objc(MZRefillStyle) open class RefillStyle: BaseStyle { public override init() { super.init() defer { currentColor = "black" labelLevel = 5 detailLevel = 10 } } @objc open override var mapStyle: MapStyle { get { return .refill } } @objc override open var styleSheetFileName: String { get { return "refill-style" } } @objc override open var styleSheetRoot: String { get { return "refill/" } } @objc override open var availableLabelLevels: Int { get { return 12 } } @objc override open var availableDetailLevels: Int { get { return 12 } } @objc override open var availableColors: [String] { get { return ["black", "blue-gray", "blue", "brown-orange", "gray-gold", "gray", "high-contrast", "inverted", "pink-yellow", "pink", "purple-green", "sepia", "zinc"] } } @objc override open var yamlString: String { get { return "\(styleSheetRoot)themes/label-\(labelLevel).yaml, \(styleSheetRoot)themes/detail-\(detailLevel).yaml, \(styleSheetRoot)themes/color-\(currentColor).yaml" } } } //MARK:- Zinc @objc(MZZincStyle) open class ZincStyle: RefillStyle { public override init() { super.init() defer { currentColor = "zinc" } } @objc open override var mapStyle: MapStyle { get { return .zinc } } } //MARK:- Walkabout @objc(MZWalkaboutStyle) open class WalkaboutStyle: BaseStyle { public override init() { super.init() defer { currentColor = "" // Not used for Walkabout labelLevel = 5 detailLevel = 0 // Not used for Walkabout } } @objc open override var mapStyle: MapStyle { get { return .walkabout } } @objc override open var styleSheetFileName: String{ get { return "walkabout-style" } } @objc override open var styleSheetRoot: String { get { return "walkabout/" } } @objc override open var availableLabelLevels: Int { get { return 12 } } @objc override open var yamlString: String { get { return "\(styleSheetRoot)themes/label-\(labelLevel).yaml" } } }
477e11ecc9d74e7fdd94221e61c19572
19.470032
397
0.627678
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
refs/heads/master
Sources/Shared/UserAgent.swift
mit
1
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import Foundation import UIKit // eg. "com.shopgun.ios.sdk/1.0.1 (com.shopgun.ios.myApp/3.2.1) [iPad; iOS 11.5.2; Scale/2.00]" internal func userAgent() -> String { var userAgent = "" // add the sdk id/version let sdkBundle = Bundle(for: Logger.self) userAgent += sdkBundle.userAgent ?? "" // append the app id/version let appBundle = Bundle.main if let appUA = appBundle.userAgent { userAgent += " (\(appUA))" } // append the device info userAgent += " [\(UIDevice.current.model); iOS \(UIDevice.current.systemVersion); Scale/\(String(format: "%0.2f", UIScreen.main.scale))]" return userAgent } extension Bundle { var userAgent: String? { guard let bundleId = self.bundleIdentifier else { return nil } var userAgent = bundleId if let appVersion = self.infoDictionary?["CFBundleShortVersionString"] as? String { userAgent += "/\(appVersion)" } return userAgent } }
696a570e1314deec8501214a98978e09
25.87234
141
0.522565
false
false
false
false
apple/swift
refs/heads/main
test/Parse/operator_decl_designated_types.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -enable-operator-designated-types precedencegroup LowPrecedence { associativity: right } precedencegroup MediumPrecedence { associativity: left higherThan: LowPrecedence } protocol PrefixMagicOperatorProtocol { } protocol PostfixMagicOperatorProtocol { } protocol InfixMagicOperatorProtocol { } prefix operator ^^ : PrefixMagicOperatorProtocol // expected-warning@-1 {{designated types are no longer used by the compiler; please remove the designated type list from this operator declaration}} {{20-49=}} infix operator <*< : MediumPrecedence, InfixMagicOperatorProtocol // expected-warning@-1 {{designated types are no longer used by the compiler}} {{39-67=}} postfix operator ^^ : PostfixMagicOperatorProtocol // expected-warning@-1 {{designated types are no longer used by the compiler}} {{21-51=}} infix operator ^*^ prefix operator *^^ postfix operator ^^* infix operator **>> : UndeclaredPrecedence // expected-warning@-1 {{designated types are no longer used by the compiler}} {{21-43=}} infix operator **+> : MediumPrecedence, UndeclaredProtocol // expected-warning@-1 {{designated types are no longer used by the compiler}} {{39-59=}} prefix operator *+*> : MediumPrecedence // expected-warning@-1 {{designated types are no longer used by the compiler}} {{22-40=}} postfix operator ++*> : MediumPrecedence // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-41=}} prefix operator *++> : UndeclaredProtocol // expected-warning@-1 {{designated types are no longer used by the compiler}} {{22-42=}} postfix operator +*+> : UndeclaredProtocol // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-43=}} struct Struct {} class Class {} infix operator *>*> : Struct // expected-warning@-1 {{designated types are no longer used by the compiler}} {{21-29=}} infix operator >**> : Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{21-28=}} prefix operator **>> : Struct // expected-warning@-1 {{designated types are no longer used by the compiler}} {{22-30=}} prefix operator *>*> : Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{22-29=}} postfix operator >*>* : Struct // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-31=}} postfix operator >>** : Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-30=}} infix operator <*<<< : MediumPrecedence, & // expected-warning@-1 {{designated types are no longer used by the compiler}} {{41-44=}} infix operator **^^ : MediumPrecedence // expected-note {{previous operator declaration here}} infix operator **^^ : InfixMagicOperatorProtocol // expected-error {{operator redeclared}} // expected-warning@-1 {{designated types are no longer used by the compiler}} {{21-50=}} infix operator ^%*%^ : MediumPrecedence, Struct, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{40-55=}} infix operator ^%*%% : Struct, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{30-37=}} // expected-warning@-2 {{designated types are no longer used by the compiler}} {{22-30=}} prefix operator %^*^^ : Struct, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-38=}} postfix operator ^^*^% : Struct, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{24-39=}} prefix operator %%*^^ : LowPrecedence, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{23-45=}} postfix operator ^^*%% : MediumPrecedence, Class // expected-warning@-1 {{designated types are no longer used by the compiler}} {{24-49=}} infix operator <*<>*> : AdditionPrecedence, // expected-warning@-1 {{designated types are no longer used by the compiler}} {{43-44=}}
a6bb75db3c52dc9e695ee6ec8aac7019
43.556818
160
0.720735
false
false
false
false
material-motion/material-motion-swift
refs/heads/develop
Pods/MaterialMotion/src/transitions/TransitionController.swift
apache-2.0
2
/* Copyright 2016-present The Material Motion Authors. 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 extension UIViewController { private struct AssociatedKeys { static var transitionController = "MDMTransitionController" } /** A transition controller may be used to implement custom Material Motion transitions. The transition controller is lazily created upon access. If the view controller's transitioningDelegate is nil when the controller is created, then the controller will also be set to the transitioningDelegate property. */ public var transitionController: TransitionController { get { if let controller = objc_getAssociatedObject(self, &AssociatedKeys.transitionController) as? TransitionController { return controller } let controller = TransitionController(viewController: self) objc_setAssociatedObject(self, &AssociatedKeys.transitionController, controller, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if transitioningDelegate == nil { transitioningDelegate = controller.transitioningDelegate } return controller } } } /** A TransitionController is the bridging object between UIKit's view controller transitioning APIs and Material Motion transitions. This class is not meant to be instantiated directly. */ public final class TransitionController { /** An instance of the directorClass will be created to describe the motion for this transition controller's transitions. If no directorClass is provided then a default UIKit transition will be used. Must be a subclass of MDMTransition. */ public var transition: Transition? { set { _transitioningDelegate.transition = newValue if let presentationTransition = newValue as? TransitionWithPresentation, let modalPresentationStyle = presentationTransition.defaultModalPresentationStyle() { _transitioningDelegate.associatedViewController?.modalPresentationStyle = modalPresentationStyle } } get { return _transitioningDelegate.transition } } /** The presentation controller to be used during this transition. Will be read from and cached when the view controller is first presented. Changes made to this property after presentation will be ignored. */ public var presentationController: UIPresentationController? { set { _transitioningDelegate.presentationController = newValue } get { return _transitioningDelegate.presentationController } } /** Start a dismiss transition when the given gesture recognizer enters its began or recognized state. The provided gesture recognizer will be made available to the transition instance via the TransitionContext's `gestureRecognizers` property. */ public func dismissWhenGestureRecognizerBegins(_ gestureRecognizer: UIGestureRecognizer) { _transitioningDelegate.dismisser.dismissWhenGestureRecognizerBegins(gestureRecognizer) } /** Will not allow the provided gesture recognizer to recognize simultaneously with other gesture recognizers. This method assumes that the provided gesture recognizer's delegate has been assigned to the transition controller's gesture delegate. */ public func disableSimultaneousRecognition(of gestureRecognizer: UIGestureRecognizer) { _transitioningDelegate.dismisser.disableSimultaneousRecognition(of: gestureRecognizer) } /** Returns a gesture recognizer delegate that will allow the gesture recognizer to begin only if the provided scroll view is scrolled to the top of its content. The returned delegate implements gestureRecognizerShouldBegin. */ public func topEdgeDismisserDelegate(for scrollView: UIScrollView) -> UIGestureRecognizerDelegate { return _transitioningDelegate.dismisser.topEdgeDismisserDelegate(for: scrollView) } /** The set of gesture recognizers that will be provided to the transition via the TransitionContext instance. */ public var gestureRecognizers: Set<UIGestureRecognizer> { set { _transitioningDelegate.gestureDelegate.gestureRecognizers = newValue } get { return _transitioningDelegate.gestureDelegate.gestureRecognizers } } /** The transitioning delegate managed by this controller. This object can be assigned to the view controller's transitioningDelegate. This is done automatically when a view controller's `transitionController` is first accessed. */ public var transitioningDelegate: UIViewControllerTransitioningDelegate { return _transitioningDelegate } /** The gesture recognizer delegate managed by this controller. */ public var gestureDelegate: UIGestureRecognizerDelegate { return _transitioningDelegate.gestureDelegate } init(viewController: UIViewController) { _transitioningDelegate = TransitioningDelegate(viewController: viewController) } fileprivate let _transitioningDelegate: TransitioningDelegate } private final class TransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { init(viewController: UIViewController) { self.associatedViewController = viewController self.dismisser = ViewControllerDismisser(gestureDelegate: self.gestureDelegate) super.init() self.dismisser.delegate = self } var ctx: TransitionContext? var transition: Transition? let dismisser: ViewControllerDismisser let gestureDelegate = GestureDelegate() var presentationController: UIPresentationController? weak var associatedViewController: UIViewController? func prepareForTransition(withSource: UIViewController, back: UIViewController, fore: UIViewController, direction: TransitionDirection) { // It's possible for a backward transition to be initiated while a forward transition is active. // We prefer the most recent transition in this case by blowing away the existing transition. if direction == .backward { ctx = nil } assert(ctx == nil, "A transition is already active.") if let transition = transition { if direction == .forward, let selfDismissingDirector = transition as? SelfDismissingTransition { selfDismissingDirector.willPresent(fore: fore, dismisser: dismisser) } ctx = TransitionContext(transition: transition, direction: direction, back: back, fore: fore, gestureRecognizers: gestureDelegate.gestureRecognizers, presentationController: presentationController) ctx?.delegate = self } } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { prepareForTransition(withSource: source, back: presenting, fore: presented, direction: .forward) return ctx } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // The source is sadly lost by the time we get to dismissing the view controller, so we do our // best to infer what the source might have been. // // If the presenting view controller is a nav controller it's pretty likely that the view // controller was presented from its last view controller. Making this assumption is generally // harmless and only affects the view retriever search (by starting one view controller lower than // we otherwise would by using the navigation controller as the source). let source: UIViewController if let navController = dismissed.presentingViewController as? UINavigationController { source = navController.viewControllers.last! } else { source = dismissed.presentingViewController! } prepareForTransition(withSource: source, back: dismissed.presentingViewController!, fore: dismissed, direction: .backward) return ctx } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if animator === ctx && isInteractive() { return ctx } return nil } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if animator === ctx && isInteractive() { return ctx } return nil } func isInteractive() -> Bool { return gestureDelegate.gestureRecognizers.filter { $0.state == .began || $0.state == .changed }.count > 0 } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { guard let transitionWithPresentation = transition as? TransitionWithPresentation else { return nil } if let presentationController = presentationController { return presentationController } presentationController = transitionWithPresentation.presentationController(forPresented: presented, presenting: presenting, source: source) return presentationController } } extension TransitioningDelegate: ViewControllerDismisserDelegate { func dismiss() { guard let associatedViewController = associatedViewController else { return } if associatedViewController.presentingViewController == nil { return } if associatedViewController.isBeingDismissed || associatedViewController.isBeingPresented { return } associatedViewController.dismiss(animated: true) } } extension TransitioningDelegate: TransitionDelegate { func transitionDidComplete(withContext ctx: TransitionContext) { if ctx === self.ctx { self.ctx = nil } } }
ad2ddc69d65a6aa2d87f364a92414504
36.623239
159
0.72934
false
false
false
false
russbishop/swift
refs/heads/master
test/IRGen/objc_protocol_extended_method_types.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation // CHECK: [[NSNUMBER:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSNumber\2224@0:8@\22NSNumber\2216\00" // CHECK: [[NSOBJECT:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSObject\2224@0:8@\22NSObject\2216\00" // CHECK: [[NSSTRING:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSString\2224@0:8@\22NSString\2216\00" // CHECK: [[NSMUTABLESTRING:@.*]] = private unnamed_addr constant [28 x i8] c"v24@0:8@\22NSMutableString\2216\00" // CHECK: [[INIT:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK: [[NSMUTABLEARRAY_GET:@.*]] = private unnamed_addr constant [24 x i8] c"@\22NSMutableArray\2216@0:8\00" // CHECK: [[NSMUTABLEARRAY_SET:@.*]] = private unnamed_addr constant [27 x i8] c"v24@0:8@\22NSMutableArray\2216\00" // CHECK: [[SUBSCRIPT:@.*]] = private unnamed_addr constant [11 x i8] c"q24@0:8q16\00" // CHECK-LABEL: @_PROTOCOL_METHOD_TYPES__TtP35objc_protocol_extended_method_types1P_ = private constant { [16 x i8*] } { [16 x i8*] [ // -- required instance methods: // -- requiredInstanceMethod // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSNUMBER]], i64 0, i64 0), // -- requiredInstanceProperty getter // CHECK: i8* getelementptr inbounds ([24 x i8], [24 x i8]* [[NSMUTABLEARRAY_GET]], i64 0, i64 0), // -- requiredInstanceProperty setter // CHECK: i8* getelementptr inbounds ([27 x i8], [27 x i8]* [[NSMUTABLEARRAY_SET]], i64 0, i64 0), // -- requiredROInstanceProperty getter // CHECK: i8* getelementptr inbounds ([24 x i8], [24 x i8]* [[NSMUTABLEARRAY_GET]], i64 0, i64 0), // -- requiredInstanceMethod2 // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSNUMBER]], i64 0, i64 0), // -- requiredInstanceProperty2 getter // CHECK: i8* getelementptr inbounds ([24 x i8], [24 x i8]* [[NSMUTABLEARRAY_GET]], i64 0, i64 0), // -- requiredInstanceProperty2 setter // CHECK: i8* getelementptr inbounds ([27 x i8], [27 x i8]* [[NSMUTABLEARRAY_SET]], i64 0, i64 0), // -- requiredROInstanceProperty2 getter // CHECK: i8* getelementptr inbounds ([24 x i8], [24 x i8]* [[NSMUTABLEARRAY_GET]], i64 0, i64 0), // -- subscript getter // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SUBSCRIPT]], i64 0, i64 0), // -- init // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[INIT]], i64 0, i64 0), // -- required class methods: // -- requiredClassMethod // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSSTRING]], i64 0, i64 0), // -- requiredClassMethod2 // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSSTRING]], i64 0, i64 0), // -- optional instance methods: // -- optionalInstanceMethod // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSOBJECT]], i64 0, i64 0), // -- optionalInstanceMethod2 // CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[NSOBJECT]], i64 0, i64 0), // -- optional class methods: // -- optionalClassMethod // CHECK: i8* getelementptr inbounds ([28 x i8], [28 x i8]* [[NSMUTABLESTRING]], i64 0, i64 0), // -- optionalClassMethod2 // CHECK: i8* getelementptr inbounds ([28 x i8], [28 x i8]* [[NSMUTABLESTRING]], i64 0, i64 0) // CHECK: ] @objc protocol P { func requiredInstanceMethod(_ o: NSNumber) -> NSNumber @objc optional func optionalInstanceMethod(_ o: NSObject) -> NSObject static func requiredClassMethod(_ o: NSString) -> NSString @objc optional static func optionalClassMethod(_ o: NSMutableString) var requiredInstanceProperty: NSMutableArray { get set } var requiredROInstanceProperty: NSMutableArray { get } func requiredInstanceMethod2(_ o: NSNumber) -> NSNumber @objc optional func optionalInstanceMethod2(_ o: NSObject) -> NSObject static func requiredClassMethod2(_ o: NSString) -> NSString @objc optional static func optionalClassMethod2(_ o: NSMutableString) var requiredInstanceProperty2: NSMutableArray { get set } var requiredROInstanceProperty2: NSMutableArray { get } subscript(x: Int) -> Int { get } init() }
bd00b1841f3f5573ffa4a1d6cbd015cd
55.233766
133
0.654503
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica Models/Habitica ModelsTests/Test Models/TestFlags.swift
gpl-3.0
1
// // TestFlags.swift // Habitica ModelsTests // // Created by Phillip Thelen on 28.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation @testable import Habitica_Models class TestFlags: FlagsProtocol { var armoireEmpty: Bool = false var cronCount: Int = 0 var rebirthEnabled: Bool = false var communityGuidelinesAccepted: Bool = false var hasNewStuff: Bool = false var armoireOpened: Bool = false var chatRevoked: Bool = false var classSelected: Bool = false var itemsEnabled: Bool = false }
cfdca6146936b9393dca666ab3d130eb
24.681818
55
0.707965
false
true
false
false
zmian/xcore.swift
refs/heads/main
Sources/Xcore/Cocoa/Components/UIImage/ImageFetcher/CompositeImageFetcher.swift
mit
1
// // Xcore // Copyright © 2018 Xcore // MIT license, see LICENSE file for details // import UIKit final class CompositeImageFetcher: ImageFetcher, ExpressibleByArrayLiteral { /// The registered list of fetchers. private var fetchers: [ImageFetcher] = [] init(_ fetchers: [ImageFetcher]) { self.fetchers = fetchers } init(arrayLiteral elements: ImageFetcher...) { self.fetchers = elements } /// Add given fetcher if it's not already included in the collection. /// /// - Note: This method ensures there are no duplicate fetchers. func add(_ fetcher: ImageFetcher) { guard !fetchers.contains(where: { $0.id == fetcher.id }) else { return } fetchers.append(fetcher) } /// Add list of given fetchers if they are not already included in the /// collection. /// /// - Note: This method ensures there are no duplicate fetchers. func add(_ fetchers: [ImageFetcher]) { fetchers.forEach(add) } /// Removes the given fetcher. func remove(_ fetcher: ImageFetcher) { let ids = fetchers.map(\.id) guard let index = ids.firstIndex(of: fetcher.id) else { return } fetchers.remove(at: index) } } extension CompositeImageFetcher { var id: String { fetchers.map(\.id).joined(separator: "_") } func canHandle(_ image: ImageRepresentable) -> Bool { image.imageSource.isValid } func fetch( _ image: ImageRepresentable, in imageView: UIImageView?, _ callback: @escaping ResultBlock ) { guard image.imageSource.isValid else { #if DEBUG Console.error("Unable to fetch image because of invalid image source.") #endif callback(.failure(ImageFetcherError.notFound)) return } // 1. Reverse fetchers so the third-party fetchers are always prioritized over // built-in ones. // 2. Find the first one that can handle the request. // 3. Fetch the requested image. guard let fetcher = fetchers.reversed().first(where: { $0.canHandle(image) }) else { callback(.failure(ImageFetcherError.notFound)) return } imageView?.imageRepresentableSource = image.imageSource fetcher.fetch(image, in: imageView, callback) } func removeCache() { fetchers.forEach { $0.removeCache() } } }
43da9e3950c69e37b0c35937c4ad310d
26.677778
92
0.607387
false
false
false
false
Leo19/swift_begin
refs/heads/master
test-swift/Closure.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" /** * author:Leo * version:Swift 2.0 */ // 将一个闭包赋值给一个变量 var firstClosure = { (a: Int ,b: Int) -> Int in return a + b } var result = firstClosure(10,15) // 定义一个简单的函数,和闭包做对比 func function1(a: Int , b: Int) -> Int{ return a - b } var func_result = function1(20, b: 19) // 闭包可以作为一个函数参数来写,参数类型+返回值类型就确定了一个闭包的类型,既firstClosure func function2(paramClosure: (pa: Int,pb: Int) -> Int){ let result = paramClosure(pa: 19,pb: 19) print(result) } function2(firstClosure) //func function3(a3: Int,b3: Int){ // (pa: Int,pb: Int) -> Int in // return 0 //} // 这个map方法是在数组中有定义,源码里多处用到泛型,我们这里用闭包重写实现功能 let digitNames = [0:"零", 1:"一", 2:"二", 3:"三", 4:"四", 5:"五", 6:"六", 7:"七", 8:"八", 9:"九", 10:"拾"] let numbers = [10,15,289] numbers.map{ (var number) -> String in var output = "" while number > 0{ output = digitNames[number % 10]! + output print(output) number /= 10 } return output }
96f490d9094da4591408b117d2a298b5
19.096154
95
0.602871
false
false
false
false
mozilla-mobile/focus-ios
refs/heads/main
Blockzilla/UIComponents/AutocompleteTextField.swift
mpl-2.0
1
// 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 // This code is loosely based on https://github.com/Antol/APAutocompleteTextField import UIKit /// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate, /// callers must use this instead. protocol AutocompleteTextFieldDelegate: AnyObject { func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField) func autocompletePasteAndGo(_ autocompleteTextField: AutocompleteTextField) func autocompleteTextFieldShouldBeginEditing(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldShouldEndEditing(_ autocompleteTextField: AutocompleteTextField) -> Bool } public class AutocompleteTextField: UITextField, UITextFieldDelegate { var autocompleteDelegate: AutocompleteTextFieldDelegate? // AutocompleteTextLabel repersents the actual autocomplete text. // The textfields "text" property only contains the entered text, while this label holds the autocomplete text // This makes sure that the autocomplete doesnt mess with keyboard suggestions provided by third party keyboards. private var autocompleteTextLabel: UILabel? private var hideCursor: Bool = false private let copyShortcutKey = "c" var isSelectionActive: Bool { return autocompleteTextLabel != nil } // This variable is a solution to get the right behavior for refocusing // the AutocompleteTextField. The initial transition into Overlay Mode // doesn't involve the user interacting with AutocompleteTextField. // Thus, we update shouldApplyCompletion in touchesBegin() to reflect whether // the highlight is active and then the text field is updated accordingly // in touchesEnd() (eg. applyCompletion() is called or not) fileprivate var notifyTextChanged: (() -> Void)? private var lastReplacement: String? public override var text: String? { didSet { super.text = text self.textDidChange(self) } } public override var accessibilityValue: String? { get { return (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") } set(value) { super.accessibilityValue = value } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { super.delegate = self super.addTarget(self, action: #selector(AutocompleteTextField.textDidChange), for: .editingChanged) notifyTextChanged = debounce(0.1, action: { [weak self] in guard let self = self else { return } if self.isEditing { self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.normalizeString(self.text ?? "")) } }) } public override var keyCommands: [UIKeyCommand]? { let commands = [ UIKeyCommand(input: copyShortcutKey, modifierFlags: .command, action: #selector(self.handleKeyCommand(sender:))) ] let arrowKeysCommands = [ UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))), UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))), UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))) ] // In iOS 15+, certain keys events are delivered to the text input or focus systems first, unless specified otherwise if #available(iOS 15, *) { arrowKeysCommands.forEach { $0.wantsPriorityOverSystemBehavior = true } } return arrowKeysCommands + commands } @objc func handleKeyCommand(sender: UIKeyCommand) { guard let input = sender.input else { return } switch input { case UIKeyCommand.inputLeftArrow: if isSelectionActive { applyCompletion() // Set the current position to the beginning of the text. selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument) } else if let range = selectedTextRange { if range.start == beginningOfDocument { break } guard let cursorPosition = position(from: range.start, offset: -1) else { break } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } case UIKeyCommand.inputRightArrow: if isSelectionActive { applyCompletion() // Set the current position to the end of the text. selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } else if let range = selectedTextRange { if range.end == endOfDocument { break } guard let cursorPosition = position(from: range.end, offset: 1) else { break } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } case UIKeyCommand.inputEscape: autocompleteDelegate?.autocompleteTextFieldDidCancel(self) case copyShortcutKey: if isSelectionActive { UIPasteboard.general.string = self.autocompleteTextLabel?.text } else { if let selectedTextRange = self.selectedTextRange { UIPasteboard.general.string = self.text(in: selectedTextRange) } } default: break } } fileprivate func normalizeString(_ string: String) -> String { return string.lowercased().stringByTrimmingLeadingCharactersInSet(CharacterSet.whitespaces) } /// Commits the completion by setting the text and removing the highlight. fileprivate func applyCompletion() { // Clear the current completion, then set the text without the attributed style. let text = (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") let didRemoveCompletion = removeCompletion() self.text = text hideCursor = false // Move the cursor to the end of the completion. if didRemoveCompletion { selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } } /// Removes the autocomplete-highlighted. Returns true if a completion was actually removed @objc @discardableResult fileprivate func removeCompletion() -> Bool { let hasActiveCompletion = isSelectionActive autocompleteTextLabel?.removeFromSuperview() autocompleteTextLabel = nil return hasActiveCompletion } @objc fileprivate func clear() { text = "" removeCompletion() autocompleteDelegate?.autocompleteTextField(self, didEnterText: "") } // `shouldChangeCharactersInRange` is called before the text changes, and textDidChange is called after. // Since the text has changed, remove the completion here, and textDidChange will fire the callback to // get the new autocompletion. public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // This happens when you begin typing overtop the old highlighted // text immediately after focusing the text field. We need to trigger // a `didEnterText` that looks like a `clear()` so that the SearchLoader // can reset itself since it will only lookup results if the new text is // longer than the previous text. if lastReplacement == nil { autocompleteDelegate?.autocompleteTextField(self, didEnterText: "") } lastReplacement = string return true } func setAutocompleteSuggestion(_ suggestion: String?) { let text = self.text ?? "" guard let suggestion = suggestion, isEditing && markedTextRange == nil else { hideCursor = false return } let normalized = normalizeString(text) guard suggestion.hasPrefix(normalized) && normalized.count < suggestion.count else { hideCursor = false return } let suggestionText = String(suggestion[suggestion.index(suggestion.startIndex, offsetBy: normalized.count)...]) let autocompleteText = NSMutableAttributedString(string: suggestionText) let color = UIColor.accent.withAlphaComponent(0.4) autocompleteText.addAttribute(NSAttributedString.Key.backgroundColor, value: color, range: NSRange(location: 0, length: suggestionText.count)) autocompleteTextLabel?.removeFromSuperview() // should be nil. But just in case autocompleteTextLabel = createAutocompleteLabelWith(autocompleteText) if let l = autocompleteTextLabel { addSubview(l) hideCursor = true forceResetCursor() } } public override func caretRect(for position: UITextPosition) -> CGRect { return hideCursor ? CGRect.zero : super.caretRect(for: position) } private func createAutocompleteLabelWith(_ autocompleteText: NSAttributedString) -> UILabel { let label = UILabel() var frame = self.bounds label.attributedText = autocompleteText label.font = self.font label.accessibilityIdentifier = "autocomplete" label.textColor = self.textColor label.textAlignment = .left let enteredTextSize = self.attributedText?.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil) frame.origin.x = (enteredTextSize?.width.rounded() ?? 0) + textRect(forBounds: bounds).origin.x frame.size.width = self.frame.size.width - clearButtonRect(forBounds: self.frame).size.width - frame.origin.x frame.size.height = self.frame.size.height label.frame = frame return label } public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return autocompleteDelegate?.autocompleteTextFieldShouldBeginEditing(self) ?? true } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { applyCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldEndEditing(self) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { applyCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true } public func textFieldShouldClear(_ textField: UITextField) -> Bool { removeCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true } public override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { // Clear the autocompletion if any provisionally inserted text has been // entered (e.g., a partial composition from a Japanese keyboard). removeCompletion() super.setMarkedText(markedText, selectedRange: selectedRange) } func setTextWithoutSearching(_ text: String) { super.text = text hideCursor = autocompleteTextLabel != nil removeCompletion() } @objc func textDidChange(_ textField: UITextField) { hideCursor = autocompleteTextLabel != nil removeCompletion() let isKeyboardReplacingText = lastReplacement != nil if isKeyboardReplacingText, markedTextRange == nil { notifyTextChanged?() } else { hideCursor = false } } // Reset the cursor to the end of the text field. // This forces `caretRect(for position: UITextPosition)` to be called which will decide if we should show the cursor // This exists because ` caretRect(for position: UITextPosition)` is not called after we apply an autocompletion. private func forceResetCursor() { selectedTextRange = nil selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } public override func deleteBackward() { lastReplacement = "" hideCursor = false if isSelectionActive { removeCompletion() forceResetCursor() } else { super.deleteBackward() } } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { applyCompletion() super.touchesBegan(touches, with: event) } } // MARK: Shared /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void { let callback = Callback(handler: action) var timer: Timer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) RunLoop.current.add(timer!, forMode: RunLoop.Mode.default) } } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:() -> Void init(handler:@escaping () -> Void) { self.handler = handler } @objc func go() { handler() } } extension String { /// Returns a new string made by removing the leading String characters contained /// in a given character set. func stringByTrimmingLeadingCharactersInSet(_ set: CharacterSet) -> String { var trimmed = self while trimmed.rangeOfCharacter(from: set)?.lowerBound == trimmed.startIndex { trimmed.remove(at: trimmed.startIndex) } return trimmed } } public protocol AutocompleteTextFieldCompletionSource: AnyObject { func autocompleteTextFieldCompletionSource(_ autocompleteTextField: AutocompleteTextField, forText text: String) -> String? }
abbc47d246fad370586673cc6d066a5c
39.237838
156
0.667383
false
false
false
false
movielala/TVOSButton
refs/heads/master
TVOSButton/TVOSButtonLabel.swift
apache-2.0
1
// // TVOSButtonText.swift // TVOSButton // // Created by Cem Olcay on 12/02/16. // Copyright © 2016 MovieLaLa. All rights reserved. // import UIKit // MARK: TVOSButtonLabel public enum TVOSButtonLabel { case Custom(color: UIColor?, font: UIFont?, alignment: NSTextAlignment?, shadow: TVOSButtonShadow?) case DefaultText(color: UIColor?) case DefaultTitle(color: UIColor?) public func getStyle() -> TVOSButtonLabelStyle { switch self { case .Custom(let color, let font, let alignment, let shadow): return TVOSButtonLabelStyle( color: color, font: font, alignment: alignment, shadow: shadow) case .DefaultText(let color): return TVOSButtonLabel.Custom( color: color, font: nil, alignment: nil, shadow: nil) .getStyle() case .DefaultTitle(let color): return TVOSButtonLabel.Custom( color: color, font: UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1), alignment: nil, shadow: TVOSButtonShadow.TitleLabel) .getStyle() } } public func applyStyle(onLabel label: UILabel?) { guard let label = label else { return } let style = getStyle() style.shadow?.applyStyle(onLayer: label.layer) label.textColor = style.color ?? UIColor.whiteColor() label.font = style.font ?? UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.textAlignment = style.alignment ?? .Center } public static func resetStyle(onLabel label: UILabel?) { guard let label = label else { return } TVOSButtonShadow.resetStyle(onLayer: label.layer) label.textColor = UIColor.whiteColor() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.textAlignment = .Center } } // MARK: - TVOSButtonLabelStyle public struct TVOSButtonLabelStyle { public var color: UIColor? public var font: UIFont? public var alignment: NSTextAlignment? public var shadow: TVOSButtonShadow? }
f6419e4f3848abe215b7785c1ed62458
27.557143
101
0.691346
false
false
false
false
IvanVorobei/Sparrow
refs/heads/master
sparrow/share/SPShare.swift
mit
1
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public struct SPShare { public struct Native { static func share(text: String? = nil, fileNames: [String] = [], complection: ((_ isSharing: Bool)->())? = nil, sourceView: UIView, on viewController: UIViewController) { var shareData: [Any] = [] if text != nil { shareData.append(text!) } for file in fileNames { let path = Bundle.main.path(forResource: file, ofType: "") if path != nil { let fileData = URL.init(fileURLWithPath: path!) shareData.append(fileData) } } let shareViewController = UIActivityViewController(activityItems: shareData, applicationActivities: nil) shareViewController.completionWithItemsHandler = {(activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) in if !completed { complection?(false) return } complection?(true) } shareViewController.modalPresentationStyle = .popover shareViewController.popoverPresentationController?.sourceView = sourceView shareViewController.popoverPresentationController?.sourceRect = sourceView.bounds viewController.present(shareViewController, animated: true, completion: nil) } } }
bed20648f9bd45346bfc21364b8a9a91
44.793103
178
0.650979
false
false
false
false
thefuntasty/Funtasty-CleanSwift-templates
refs/heads/master
Clean Swift/Unit Tests.xctemplate/___FILEBASENAME___ViewControllerTests.swift
mit
1
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // @testable import ___PROJECTNAME___ import XCTest class ___FILEBASENAMEASIDENTIFIER___ViewControllerTests: XCTestCase { // MARK: - Subject under test var sut: ___FILEBASENAMEASIDENTIFIER___ViewController! var window: UIWindow! // MARK: - Test lifecycle override func setUp() { super.setUp() window = UIWindow() setup___FILEBASENAMEASIDENTIFIER___ViewController() } override func tearDown() { window = nil super.tearDown() } // MARK: - Test setup func setup___FILEBASENAMEASIDENTIFIER___ViewController() { let bundle = NSBundle.mainBundle() let storyboard = UIStoryboard(name: "Main", bundle: bundle) sut = storyboard.instantiateViewControllerWithIdentifier("___FILEBASENAMEASIDENTIFIER___ViewController") as! ___FILEBASENAMEASIDENTIFIER___ViewController } func loadView() { window.addSubview(sut.view) NSRunLoop.currentRunLoop().runUntilDate(NSDate()) } // MARK: - Test doubles // MARK: - Tests func testSomething() { // Given // When // Then } }
ff279c39438344870f866ecb430d6e81
22.321429
161
0.61562
false
true
false
false
lzpfmh/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Dialogs/Cells/DialogCell.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit; class DialogCell: UATableViewCell, ACBindedCell { // Binding data type typealias BindData = ACDialog // Hight of cell static func bindedCellHeight(table: ACManagedTable, item: ACDialog) -> CGFloat { return 76 } // Views let avatarView = AvatarView(style: "dialogs.avatar") let titleView: UILabel = UILabel(style: "dialogs.title") let messageView: UILabel = UILabel(style: "dialogs.message") let dateView: UILabel = UILabel(style: "dialogs.date") let statusView: UIImageView = UIImageView(style: "dialogs.status") let counterView: UILabel = UILabel(style: "dialogs.counter") let counterViewBg: UIImageView = UIImageView(style: "dialogs.counter.bg") override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(cellStyle: "dialogs.cell", reuseIdentifier: reuseIdentifier) self.contentView.addSubview(avatarView) self.contentView.addSubview(titleView) self.contentView.addSubview(messageView) self.contentView.addSubview(dateView) self.contentView.addSubview(statusView) self.contentView.addSubview(counterViewBg) self.contentView.addSubview(counterView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(item: ACDialog, table: ACManagedTable, index: Int, totalCount: Int) { self.avatarView.bind(item.dialogTitle, id: item.peer.peerId, avatar: item.dialogAvatar) self.titleView.text = item.dialogTitle self.messageView.text = Actor.getFormatter().formatDialogText(item) if item.messageType.ordinal() != jint(ACContentType.TEXT.rawValue) { self.messageView.applyStyle("dialog.message") } else { self.messageView.applyStyle("dialog.message.hightlight") } if (item.date > 0) { self.dateView.text = Actor.getFormatter().formatShortDate(item.date) self.dateView.hidden = false } else { self.dateView.hidden = true } if (item.unreadCount != 0) { self.counterView.text = "\(item.unreadCount)" self.counterView.hidden = false self.counterViewBg.hidden = false } else { self.counterView.hidden = true self.counterViewBg.hidden = true } let messageState = UInt(item.status.ordinal()) if (messageState == ACMessageState.PENDING.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSending self.statusView.image = Resources.iconClock self.statusView.hidden = false } else if (messageState == ACMessageState.READ.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogRead self.statusView.image = Resources.iconCheck2 self.statusView.hidden = false } else if (messageState == ACMessageState.RECEIVED.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogReceived self.statusView.image = Resources.iconCheck2 self.statusView.hidden = false } else if (messageState == ACMessageState.SENT.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogSent self.statusView.image = Resources.iconCheck1 self.statusView.hidden = false } else if (messageState == ACMessageState.ERROR.rawValue) { self.statusView.tintColor = MainAppTheme.bubbles.statusDialogError self.statusView.image = Resources.iconError self.statusView.hidden = false } else { self.statusView.hidden = true } setNeedsLayout() } override func prepareForReuse() { super.prepareForReuse() self.avatarView.unbind(true) } override func layoutSubviews() { super.layoutSubviews(); // We expect height == 76; let width = self.contentView.frame.width let leftPadding = CGFloat(76) let padding = CGFloat(14) avatarView.frame = CGRectMake(padding, padding, 48, 48) titleView.frame = CGRectMake(leftPadding, 16, width - leftPadding - /*paddingRight*/(padding + 50), 21) var messagePadding:CGFloat = 0 if (!self.statusView.hidden) { messagePadding = 22 statusView.frame = CGRectMake(leftPadding, 44, 20, 18) } var unreadPadding = CGFloat(0) if (!self.counterView.hidden) { counterView.frame = CGRectMake(0, 0, 1000, 1000) counterView.sizeToFit() let unreadW = max(counterView.frame.width + 8, 18) counterView.frame = CGRectMake(width - padding - unreadW, 44, unreadW, 18) counterViewBg.frame = counterView.frame unreadPadding = unreadW } messageView.frame = CGRectMake(leftPadding+messagePadding, 44, width - leftPadding - /*paddingRight*/padding - messagePadding - unreadPadding, 18) dateView.frame = CGRectMake(width - /*width*/60 - /*paddingRight*/padding , 18, 60, 18) } }
294c9af5d3eb64fbc6096c55537ae1b8
37.21831
154
0.62606
false
false
false
false
XYXiaoYuan/Meilishuo
refs/heads/master
Meilishuo/Classes/Other/Protocol/Thanable.swift
mit
1
// // Thanable.swift // Meilishuo // // Created by 袁小荣 on 2017/5/15. // Copyright © 2017年 袁小荣. All rights reserved. // import Foundation /// Then语法糖 public protocol Then {} extension Then where Self: Any { /** Makes it available to set properties with closures just after initializing. let label = UILabel().then { $0.textAlignment = .Center $0.textColor = UIColor.blackColor() $0.text = "Hello, World!" } */ /// Then语法糖 public func then( block: (inout Self) -> Void) -> Self { var copy = self block(&copy) return copy } } extension Then where Self: AnyObject { /** Makes it available to set properties with closures just after initializing. let label = UILabel().then { $0.textAlignment = .Center $0.textColor = UIColor.blackColor() $0.text = "Hello, World!" } */ /// Then语法糖 public func then( block: (Self) -> Void) -> Self { block(self) return self } } extension NSObject: Then {}
843bcff3420b45a2ba8b37ddf7028669
18.438596
80
0.555054
false
false
false
false
hashemi/FlyingMonkey
refs/heads/master
FlyingMonkey/Ast.swift
mit
1
// // Ast.swift // FlyingMonkey // // Created by Ahmad Alhashemi on 2017-08-18. // Copyright © 2017 Ahmad Alhashemi. All rights reserved. // protocol Node { var tokenLiteral: String { get } var string: String { get } } protocol Statement: Node { } protocol Expression: Node { } struct Program: Node { let statements: [Statement] var tokenLiteral: String { if statements.count > 0 { return statements[0].tokenLiteral } else { return "" } } var string: String { return statements.map { $0.string }.joined() } } // Statements struct LetStatement: Statement { let token: Token let name: Identifier let value: Expression? var tokenLiteral: String { return token.literal } var string: String { return "\(tokenLiteral) \(name.string) = \(value?.string ?? "");" } } struct ReturnStatement: Statement { let token: Token let returnValue: Expression? var tokenLiteral: String { return token.literal } var string: String { return "\(tokenLiteral) \(returnValue?.string ?? "");" } } struct ExpressionStatement: Statement { let token: Token let expression: Expression? var tokenLiteral: String { return token.literal } var string: String { return expression?.string ?? "" } } struct BlockStatement: Statement { let token: Token let statements: [Statement] var tokenLiteral: String { return token.literal } var string: String { return statements.map { $0.string }.joined() } } // Expressions struct Identifier: Expression { let token: Token let value: String var tokenLiteral: String { return token.literal } var string: String { return value } } struct BooleanLiteral: Expression { let token: Token let value: Bool var tokenLiteral: String { return token.literal } var string: String { return token.literal } } struct IntegerLiteral: Expression { let token: Token let value: Int64 var tokenLiteral: String { return token.literal } var string: String { return token.literal } } struct PrefixExpression: Expression { let token: Token let op: String let right: Expression? var tokenLiteral: String { return token.literal } var string: String { return "(\(op)\(right?.string ?? ""))" } } struct InfixExpression: Expression { let token: Token let left: Expression let op: String let right: Expression? var tokenLiteral: String { return token.literal } var string: String { return "(\(left.string) \(op) \(right?.string ?? ""))" } } struct IfExpression: Expression { let token: Token let condition: Expression? let consequence: BlockStatement let alternative: BlockStatement? var tokenLiteral: String { return token.literal } var string: String { let baseString = "if\(condition?.string ?? "") \(consequence.string)" if let alternative = alternative { return "\(baseString) else \(alternative.string)" } else { return baseString } } } struct FunctionLiteral: Expression { let token: Token let parameters: [Identifier]? let body: BlockStatement var tokenLiteral: String { return token.literal } var string: String { let paramsString: String if let parameters = parameters { paramsString = parameters.map { $0.string }.joined(separator: ", ") } else { paramsString = "" } return "\(tokenLiteral)(\(paramsString)) \(body.string)" } } struct CallExpression: Expression { let token: Token let function: Expression let arguments: [Expression]? var tokenLiteral: String { return token.literal } var string: String { let argsString: String if let arguments = arguments { argsString = arguments.map { $0.string }.joined(separator: ", ") } else { argsString = "" } return "\(function.string)(\(argsString))" } }
5e33a92c0102eaae1a215ccd655b1b86
22.275281
79
0.617186
false
false
false
false
NicolasRenaud/SwiftyPresentation
refs/heads/master
SwiftyPresentation/Classes/SlidePresentationAnimator.swift
mit
1
// // SlideInPresentationAnimator.swift // Presentation // // Created by Nicolas Renaud on 18/05/2017. // Copyright © 2017 NRC. All rights reserved. // import UIKit final class SlidePresentationAnimator: NSObject { // MARK: - Properties let direction: PresentationDirection let isPresentation: Bool // MARK: - Initializers init(direction: PresentationDirection, isPresentation: Bool) { self.direction = direction self.isPresentation = isPresentation super.init() } } // MARK: - UIViewControllerAnimatedTransitioning extension SlidePresentationAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from let controller = transitionContext.viewController(forKey: key)! if isPresentation { transitionContext.containerView.addSubview(controller.view) } let presentedFrame = transitionContext.finalFrame(for: controller) var dismissedFrame = presentedFrame switch direction { case .left: dismissedFrame.origin.x = -presentedFrame.width case .right: dismissedFrame.origin.x = transitionContext.containerView.frame.size.width case .top: dismissedFrame.origin.y = -presentedFrame.height case .bottom: dismissedFrame.origin.y = transitionContext.containerView.frame.size.height } let initialFrame = isPresentation ? dismissedFrame : presentedFrame let finalFrame = isPresentation ? presentedFrame : dismissedFrame let animationDuration = transitionDuration(using: transitionContext) controller.view.frame = initialFrame UIView.animate(withDuration: animationDuration, animations: { controller.view.frame = finalFrame }, completion: { finished in transitionContext.completeTransition(finished) }) } }
5a641eb3d3e900491fc0b5e63bfed0d5
32.647059
118
0.686189
false
false
false
false
alblue/swift
refs/heads/master
test/IRGen/clang_inline.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -enable-objc-interop -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -primary-file %s -O -disable-sil-perf-optzns -disable-llvm-optzns -emit-ir -Xcc -fstack-protector -I %t | %FileCheck %s // RUN: %empty-directory(%t/Empty.framework/Modules/Empty.swiftmodule) // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module-path %t/Empty.framework/Modules/Empty.swiftmodule/%target-swiftmodule-name %S/../Inputs/empty.swift -module-name Empty -I %t // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -primary-file %s -I %t -F %t -DIMPORT_EMPTY -O -disable-sil-perf-optzns -disable-llvm-optzns -emit-ir -Xcc -fstack-protector -enable-objc-interop | %FileCheck %s // REQUIRES: CPU=i386 || CPU=x86_64 // REQUIRES: objc_interop #if IMPORT_EMPTY import Empty #endif import gizmo // CHECK-LABEL: define hidden swiftcc i64 @"$s12clang_inline16CallStaticInlineC10ReturnZeros5Int64VyF"(%T12clang_inline16CallStaticInlineC* swiftself) {{.*}} { class CallStaticInline { func ReturnZero() -> Int64 { return Int64(zero()) } } // CHECK-LABEL: define internal i32 @zero() // CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden swiftcc i64 @"$s12clang_inline17CallStaticInline2C10ReturnZeros5Int64VyF"(%T12clang_inline17CallStaticInline2C* swiftself) {{.*}} { class CallStaticInline2 { func ReturnZero() -> Int64 { return Int64(wrappedZero()) } } // CHECK-LABEL: define internal i32 @wrappedZero() // CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline10testExterns5Int32VyF"() {{.*}} { func testExtern() -> CInt { return wrappedGetInt() } // CHECK-LABEL: define internal i32 @wrappedGetInt() // CHECK-SAME: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline16testAlwaysInlines5Int32VyF"() {{.*}} { func testAlwaysInline() -> CInt { return alwaysInlineNumber() } // CHECK-LABEL: define internal i32 @alwaysInlineNumber() // CHECK-SAME: [[ALWAYS_INLINE:#[0-9]+]] { // CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline20testInlineRedeclareds5Int32VyF"() {{.*}} { func testInlineRedeclared() -> CInt { return zeroRedeclared() } // CHECK-LABEL: define internal i32 @zeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline27testInlineRedeclaredWrappeds5Int32VyF"() {{.*}} { func testInlineRedeclaredWrapped() -> CInt { return wrappedZeroRedeclared() } // CHECK-LABEL: define internal i32 @wrappedZeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden swiftcc i32 @"$s12clang_inline22testStaticButNotInlines5Int32VyF"() {{.*}} { func testStaticButNotInline() -> CInt { return staticButNotInline() } // CHECK-LABEL: define internal i32 @staticButNotInline() #{{[0-9]+}} { // CHECK-LABEL: define internal i32 @innerZero() // CHECK-SAME: [[INNER_ZERO_ATTR:#[0-9]+]] { // CHECK-LABEL: declare i32 @getInt() // CHECK-SAME: [[GET_INT_ATTR:#[0-9]+]] // CHECK-DAG: attributes [[INLINEHINT_SSP_UWTABLE]] = { inlinehint optsize ssp {{.*}}} // CHECK-DAG: attributes [[ALWAYS_INLINE]] = { alwaysinline nounwind optsize ssp // CHECK-DAG: attributes [[INNER_ZERO_ATTR]] = { inlinehint nounwind optsize ssp // CHECK-DAG: attributes [[GET_INT_ATTR]] = {
abdf99676f6c747109f3673c0133e2db
42.607595
249
0.706821
false
true
false
false
TongjiUAppleClub/WeCitizens
refs/heads/master
WeCitizens/DataModel.swift
mit
1
// // DataModel.swift // WeCitizens // // Created by Teng on 2/10/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import Foundation import Parse class DataModel { func convertPFFileToImage(rawFile:PFFile?) -> UIImage? { var image:UIImage? = nil do { let imageData = try rawFile?.getData() if let data = imageData { image = UIImage(data: data) } } catch { print("") } return image } func convertArrayToImages(rawArray:NSArray) -> [UIImage] { var imageList = [UIImage]() for tmp in rawArray { let imageFile = tmp as! PFFile do { let imageData = try imageFile.getData() let image = UIImage(data: imageData) imageList.append(image!) } catch { print("") } } return imageList } func convertImageToPFFile(rawImageArray:[UIImage]) -> [PFFile] { var imageFileArray = [PFFile]() for image in rawImageArray { let imageData = UIImageJPEGRepresentation(image, 0.5) if let data = imageData { let imageFile = PFFile(name: nil, data: data) imageFileArray.append(imageFile!) } else { let imageDataPNG = UIImagePNGRepresentation(image) if let dataPNG = imageDataPNG { let imageFile = PFFile(name: nil, data: dataPNG) imageFileArray.append(imageFile!) } else { //图片格式非PNG或JPEG print("图片格式非PNG或JPEG,给用户个提示") } } } return imageFileArray } }
6f6319420b77269e14eccbe6a44b1879
27.046154
68
0.499177
false
false
false
false
PhillipEnglish/TIY-Assignments
refs/heads/master
FirstContact/FirstContact/ContactsTableViewController.swift
cc0-1.0
1
// // ContactsTableViewController.swift // FirstContact // // Created by Phillip English on 11/20/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import RealmSwift class ContactsTableViewController: UITableViewController { let realm = try! Realm() var contacts : Results<Contact>! override func viewDidLoad() { super.viewDidLoad() contacts = realm.objects(Contact).sorted("name") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath) let aContact = contacts[indexPath.row] cell.textLabel?.text = aContact.name cell.detailTextLabel?.text = aContact.phoneNumber return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: - Row Deletion override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let aContact = contacts[indexPath.row] try! realm.write{ self.realm.delete(aContact) } tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } }
b933209420d4424ece4c59de84e1ed43
29.208
157
0.665784
false
false
false
false
Jpoliachik/DroidconBoston-iOS
refs/heads/master
DroidconBoston/Pods/XLPagerTabStrip/Sources/ButtonBarPagerTabStripViewController.swift
apache-2.0
3
// ButtonBarPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public enum ButtonBarItemSpec<CellType: UICollectionViewCell> { case nibFile(nibName: String, bundle: Bundle?, width:((IndicatorInfo)-> CGFloat)) case cellClass(width:((IndicatorInfo)-> CGFloat)) public var weight: ((IndicatorInfo) -> CGFloat) { switch self { case .cellClass(let widthCallback): return widthCallback case .nibFile(_, _, let widthCallback): return widthCallback } } } public struct ButtonBarPagerTabStripSettings { public struct Style { public var buttonBarBackgroundColor: UIColor? public var buttonBarMinimumLineSpacing: CGFloat? public var buttonBarLeftContentInset: CGFloat? public var buttonBarRightContentInset: CGFloat? public var selectedBarBackgroundColor = UIColor.black public var selectedBarHeight: CGFloat = 5 public var buttonBarItemBackgroundColor: UIColor? public var buttonBarItemFont = UIFont.systemFont(ofSize: 18) public var buttonBarItemLeftRightMargin: CGFloat = 8 public var buttonBarItemTitleColor: UIColor? @available(*, deprecated: 7.0.0) public var buttonBarItemsShouldFillAvailiableWidth: Bool { set { buttonBarItemsShouldFillAvailableWidth = newValue } get { return buttonBarItemsShouldFillAvailableWidth } } public var buttonBarItemsShouldFillAvailableWidth = true // only used if button bar is created programaticaly and not using storyboards or nib files public var buttonBarHeight: CGFloat? } public var style = Style() } open class ButtonBarPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource { public var settings = ButtonBarPagerTabStripSettings() public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarViewCell>! public var changeCurrentIndex: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ animated: Bool) -> Void)? public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarViewCell?, _ newCell: ButtonBarViewCell?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)? @IBOutlet public weak var buttonBarView: ButtonBarView! lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in return self.calculateWidths() }() override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: Bundle(for: ButtonBarViewCell.self), width:{ [weak self] (childItemInfo) -> CGFloat in let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = self?.settings.style.buttonBarItemFont label.text = childItemInfo.title let labelSize = label.intrinsicContentSize return labelSize.width + (self?.settings.style.buttonBarItemLeftRightMargin ?? 8) * 2 }) let buttonBarViewAux = buttonBarView ?? { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .horizontal let buttonBarHeight = settings.style.buttonBarHeight ?? 44 let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout) buttonBar.backgroundColor = .orange buttonBar.selectedBar.backgroundColor = .black buttonBar.autoresizingMask = .flexibleWidth var newContainerViewFrame = containerView.frame newContainerViewFrame.origin.y = buttonBarHeight newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y) containerView.frame = newContainerViewFrame return buttonBar }() buttonBarView = buttonBarViewAux if buttonBarView.superview == nil { view.addSubview(buttonBarView) } if buttonBarView.delegate == nil { buttonBarView.delegate = self } if buttonBarView.dataSource == nil { buttonBarView.dataSource = self } buttonBarView.scrollsToTop = false let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.scrollDirection = .horizontal flowLayout.minimumInteritemSpacing = 0 flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing let sectionInset = flowLayout.sectionInset flowLayout.sectionInset = UIEdgeInsetsMake(sectionInset.top, settings.style.buttonBarLeftContentInset ?? sectionInset.left, sectionInset.bottom, settings.style.buttonBarRightContentInset ?? sectionInset.right) buttonBarView.showsHorizontalScrollIndicator = false buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor buttonBarView.selectedBarHeight = settings.style.selectedBarHeight // register button bar item cell switch buttonBarItemSpec! { case .nibFile(let nibName, let bundle, _): buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell") case .cellClass: buttonBarView.register(ButtonBarViewCell.self, forCellWithReuseIdentifier:"Cell") } //- } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) buttonBarView.layoutIfNeeded() } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard isViewAppearing || isViewRotating else { return } // Force the UICollectionViewFlowLayout to get laid out again with the new size if // a) The view is appearing. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called for a second time // when the view is shown and when the view *frame(s)* are actually set // (we need the view frame's to have been set to work out the size's and on the // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s) // aren't set correctly) // b) The view is rotating. This ensures that // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views // *new* frame so that the buttonBarView cell's actually get resized correctly cachedCellWidths = calculateWidths() buttonBarView.collectionViewLayout.invalidateLayout() // When the view first appears or is rotated we also need to ensure that the barButtonView's // selectedBar is resized and its contentOffset/scroll is set correctly (the selected // tab/cell may end up either skewed or off screen after a rotation otherwise) buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen) } // MARK: - Public Methods open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() guard isViewLoaded else { return } buttonBarView.reloadData() cachedCellWidths = calculateWidths() buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes) } open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat { var numberOfLargeCells = 0 var totalWidthOfLargeCells: CGFloat = 0 for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth { totalWidthOfLargeCells += minimumCellWidthValue numberOfLargeCells += 1 } guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth } let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right let numberOfCells = minimumCellWidths.count let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing let numberOfSmallCells = numberOfCells - numberOfLargeCells let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells) return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells) } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { guard shouldUpdateButtonBarView else { return } buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes) if let changeCurrentIndex = changeCurrentIndex { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell changeCurrentIndex(oldCell, newCell, true) } } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { guard shouldUpdateButtonBarView else { return } buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes) if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true) } } // MARK: - UICollectionViewDelegateFlowLayut open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { guard let cellWidthValue = cachedCellWidths?[indexPath.row] else { fatalError("cachedCellWidths for \(indexPath.row) must not be nil") } return CGSize(width: cellWidthValue, height: collectionView.frame.size.height) } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath.item != currentIndex else { return } buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes) shouldUpdateButtonBarView = false let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarViewCell let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarViewCell if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(oldCell, newCell, 1, true, true) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(oldCell, newCell, true) } } moveToViewController(at: indexPath.item) } // MARK: - UICollectionViewDataSource open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewControllers.count } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarViewCell else { fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell") } let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider let indicatorInfo = childController.indicatorInfo(for: self) cell.label.text = indicatorInfo.title cell.label.font = settings.style.buttonBarItemFont cell.label.textColor = settings.style.buttonBarItemTitleColor ?? cell.label.textColor cell.contentView.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.contentView.backgroundColor cell.backgroundColor = settings.style.buttonBarItemBackgroundColor ?? cell.backgroundColor if let image = indicatorInfo.image { cell.imageView.image = image } if let highlightedImage = indicatorInfo.highlightedImage { cell.imageView.highlightedImage = highlightedImage } configureCell(cell, indicatorInfo: indicatorInfo) if pagerBehaviour.isProgressiveIndicator { if let changeCurrentIndexProgressive = changeCurrentIndexProgressive { changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false) } } else { if let changeCurrentIndex = changeCurrentIndex { changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false) } } return cell } // MARK: - UIScrollViewDelegate open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { super.scrollViewDidEndScrollingAnimation(scrollView) guard scrollView == containerView else { return } shouldUpdateButtonBarView = true } open func configureCell(_ cell: ButtonBarViewCell, indicatorInfo: IndicatorInfo){ } private func calculateWidths() -> [CGFloat] { let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout let numberOfCells = viewControllers.count var minimumCellWidths = [CGFloat]() var collectionViewContentWidth: CGFloat = 0 for viewController in viewControllers { let childController = viewController as! IndicatorInfoProvider let indicatorInfo = childController.indicatorInfo(for: self) switch buttonBarItemSpec! { case .cellClass(let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width case .nibFile(_, _, let widthCallback): let width = widthCallback(indicatorInfo) minimumCellWidths.append(width) collectionViewContentWidth += width } } let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing collectionViewContentWidth += cellSpacingTotal let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth { return minimumCellWidths } else { let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells) let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0) var stretchedCellWidths = [CGFloat]() for minimumCellWidthValue in minimumCellWidths { let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth stretchedCellWidths.append(cellWidth) } return stretchedCellWidths } } private var shouldUpdateButtonBarView = true }
549682e36fb4767d16033f104bcb1e27
49.482385
217
0.695351
false
false
false
false
NachoSoto/Carthage
refs/heads/master
Source/carthage/Archive.swift
mit
2
// // Archive.swift // Carthage // // Created by Justin Spahr-Summers on 2015-02-13. // Copyright (c) 2015 Carthage. All rights reserved. // import CarthageKit import Commandant import Foundation import LlamaKit import ReactiveCocoa public struct ArchiveCommand: CommandType { public let verb = "archive" public let function = "Archives a built framework into a zip that Carthage can use" public func run(mode: CommandMode) -> Result<()> { return ColdSignal.fromResult(ArchiveOptions.evaluate(mode)) .mergeMap { options -> ColdSignal<()> in let formatting = options.colorOptions.formatting return ColdSignal.fromValues(Platform.supportedPlatforms) .map { platform in platform.relativePath.stringByAppendingPathComponent(options.frameworkName).stringByAppendingPathExtension("framework")! } .filter { relativePath in NSFileManager.defaultManager().fileExistsAtPath(relativePath) } .on(next: { path in carthage.println(formatting.bullets + "Found " + formatting.path(string: path)) }) .reduce(initial: []) { $0 + [ $1 ] } .mergeMap { paths -> ColdSignal<()> in if paths.isEmpty { return .error(CarthageError.InvalidArgument(description: "Could not find any copies of \(options.frameworkName).framework. Make sure you're in the project’s root and that the framework has already been built.").error) } let outputPath = (options.outputPath.isEmpty ? "\(options.frameworkName).framework.zip" : options.outputPath) let outputURL = NSURL(fileURLWithPath: outputPath, isDirectory: false)! return zipIntoArchive(outputURL, paths).on(completed: { carthage.println(formatting.bullets + "Created " + formatting.path(string: outputPath)) }) } } .wait() } } private struct ArchiveOptions: OptionsType { let frameworkName: String let outputPath: String let colorOptions: ColorOptions static func create(outputPath: String)(colorOptions: ColorOptions)(frameworkName: String) -> ArchiveOptions { return self(frameworkName: frameworkName, outputPath: outputPath, colorOptions: colorOptions) } static func evaluate(m: CommandMode) -> Result<ArchiveOptions> { return create <*> m <| Option(key: "output", defaultValue: "", usage: "the path at which to create the zip file (or blank to infer it from the framework name)") <*> ColorOptions.evaluate(m) <*> m <| Option(usage: "the name of the built framework to archive (without any extension)") } }
1abb94a37e591048aa5adc6ec1fa79d0
38.253968
224
0.725435
false
false
false
false
ustwo/formvalidator-swift
refs/heads/master
Sources/Controls/ValidatorTextView-UIKit.swift
mit
1
// // ValidatorTextView-UIKit.swift // FormValidatorSwift // // Created by Aaron McTavish on 14/01/2016. // Copyright © 2016 ustwo Fampany Ltd. All rights reserved. // import UIKit open class ValidatorTextView: UITextView, ValidatorControl { // MARK: - Properties open var shouldAllowViolation = false open var validateOnFocusLossOnly = false public let validator: Validator /// Validator delegate for the text view. /// /// - SeeAlso: setValidatorDelegate(_:) to set the validator delegate. open var validatorDelegate: ValidatorControlDelegate? { return validatorControlResponder?.delegate } open var validatableText: String? { return text } fileprivate var validatorControlResponder: ValidatorTextViewResponder? // MARK: - Initializers public convenience init(validator: Validator) { self.init(frame: CGRect.zero, validator: validator) } public convenience init(frame: CGRect, validator: Validator) { self.init(frame: frame, textContainer: nil, validator: validator) } public init(frame: CGRect, textContainer: NSTextContainer?, validator: Validator) { self.validator = validator super.init(frame: frame, textContainer: textContainer) setup() } public required init?(coder aDecoder: NSCoder) { fatalError("Not implemented.") } deinit { guard let responder = validatorControlResponder else { return } NotificationCenter.default.removeObserver(responder, name: UITextView.textDidEndEditingNotification, object: self) } // MARK: - Setup fileprivate func setup() { let responder = ValidatorTextViewResponder(validatorTextView: self) validatorControlResponder = responder super.delegate = responder NotificationCenter.default.addObserver(responder, selector: #selector(UITextViewDelegate.textViewDidEndEditing(_:)), name: UITextView.textDidEndEditingNotification, object: self) } // MARK: - Custom Setters /// Sets the `validatorDelegate` for the text view. This allows custom responses to both `UITextViewDelegate` callbacks as well as those from `ValidatorControlDelegate`. /// /// - Parameter newDelegate: The delegate for `ValidatorTextView` callbacks. open func setValidatorDelegate(_ newDelegate: ValidatorControlDelegate & UITextViewDelegate) { validatorControlResponder?.delegate = newDelegate } // MARK: - Callbacks on state change open func validatorTextViewSuccededConditions() { } open func validatorTextViewViolatedConditions(_ conditions: [Condition]) { } } internal class ValidatorTextViewResponder: NSObject, UITextViewDelegate { // MARK: - Properties var validatorTextView: ValidatorTextView weak var delegate: (ValidatorControlDelegate & UITextViewDelegate)? fileprivate var didEndEditing = false fileprivate var lastIsValid: Bool? // MARK: - Initializers init(validatorTextView: ValidatorTextView) { self.validatorTextView = validatorTextView } // MARK: - UITextViewDelegate func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let sourceText = textView.text let originalString = NSString(string: sourceText!) let futureString = originalString.replacingCharacters(in: range, with: text) let conditions = validatorTextView.validator.checkConditions(futureString) if let conditions = conditions { validatorTextView.validatorTextViewViolatedConditions(conditions) } else { validatorTextView.validatorTextViewSuccededConditions() } if !validatorTextView.validateOnFocusLossOnly && range.location != 0, let conditions = conditions, (!validatorTextView.shouldAllowViolation || !(conditions.isEmpty || conditions[0].shouldAllowViolation)) { return false } if let result = delegate?.textView?(validatorTextView, shouldChangeTextIn: range, replacementText: text) { return result } return true } func textViewDidChange(_ textView: UITextView) { defer { // Inform delegate about changes delegate?.validatorControlDidChange(validatorTextView) } // Only validate if violations are allowed // Validate according to `validateOnFocusLossOnly` while editing first time or after focus loss guard validatorTextView.shouldAllowViolation && (!validatorTextView.validateOnFocusLossOnly || (validatorTextView.validateOnFocusLossOnly && didEndEditing)) else { return } let conditions = validatorTextView.validator.checkConditions(validatorTextView.text) let isValid = conditions == nil if lastIsValid != isValid { lastIsValid = isValid // Inform the text view about valid state change if isValid { validatorTextView.validatorTextViewSuccededConditions() } else { validatorTextView.validatorTextViewViolatedConditions(conditions!) } // Inform delegate about valid state change delegate?.validatorControl(validatorTextView, changedValidState: isValid) if !isValid { // Inform delegatate about violation delegate?.validatorControl(validatorTextView, violatedConditions: conditions!) } } } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if let result = delegate?.textViewShouldBeginEditing?(validatorTextView) { return result } return true } func textViewDidBeginEditing(_ textView: UITextView) { delegate?.textViewDidBeginEditing?(validatorTextView) } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { if let result = delegate?.textViewShouldEndEditing?(validatorTextView) { return result } return true } func textViewDidEndEditing(_ textView: UITextView) { didEndEditing = true textViewDidChange(textView) delegate?.textViewDidEndEditing?(validatorTextView) } func textViewDidChangeSelection(_ textView: UITextView) { delegate?.textViewDidChangeSelection?(validatorTextView) } }
e4500493f0e19dd01dedd4837d58643e
31.388626
186
0.64779
false
false
false
false
nicolastinkl/swift
refs/heads/master
UICatalog:CreatingandCustomizingUIKitControlsinSwift/UICatalog/AlertControllerViewController.swift
mit
1
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The view controller that demonstrates how to use UIAlertController. */ import UIKit class AlertControllerViewController : UITableViewController { // MARK: Properties weak var secureTextAlertAction: UIAlertAction? // MARK: UIAlertControllerStyleAlert Style Alerts // Show an alert with an "Okay" button. func showSimpleAlert() { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the action. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The simple alert's cancel action occured.") } // Add the action. alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } // Show an alert with an "Okay" and "Cancel" button. func showOkayCancelAlert() { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertCotroller = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Okay/Cancel\" alert's other action occured.") } // Add the actions. alertCotroller.addAction(cancelAction) alertCotroller.addAction(otherAction) presentViewController(alertCotroller, animated: true, completion: nil) } // Show an alert with two custom buttons. func showOtherAlert() { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitleOne = NSLocalizedString("Coice One", comment: "") let otherButtonTitleTwo = NSLocalizedString("Choice Two", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Other\" alert's cancel action occured.") } let otherButtonOneAction = UIAlertAction(title: otherButtonTitleOne, style: .Default) { action in NSLog("The \"Other\" alert's other button one action occured.") } let otherButtonTwoAction = UIAlertAction(title: otherButtonTitleTwo, style: .Default) { action in NSLog("The \"Other\" alert's other button two action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherButtonOneAction) alertController.addAction(otherButtonTwoAction) presentViewController(alertController, animated: true, completion: nil) } // Show a text entry alert with two custom buttons. func showTextEntryAlert() { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for text entry. alertController.addTextFieldWithConfigurationHandler { textField in // If you need to customize the text field, you can do so here. } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Text Entry\" alert's cancel action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Text Entry\" alert's other action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } // Show a secure text entry alert with two custom buttons. func showSecureTextEntryAlert() { let title = NSLocalizedString("A Short Title is Best", comment: "") let message = NSLocalizedString("A message should be a short, complete sentence.", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let otherButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) // Add the text field for the secure text entry. alertController.addTextFieldWithConfigurationHandler { textField in // Listen for changes to the text field's text so that we can toggle the current // action's enabled property based on whether the user has entered a sufficiently // secure entry. NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField) textField.secureTextEntry = true } // Stop listening for text change notifications on the text field. This func will be called in the two action handlers. func removeTextFieldObserver() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0]) } // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Secure Text Entry\" alert's cancel action occured.") removeTextFieldObserver() } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Secure Text Entry\" alert's other action occured.") removeTextFieldObserver() } // The text field initially has no text in the text field, so we'll disable it. otherAction.enabled = false // Hold onto the secure text alert action to toggle the enabled/disabled state when the text changed. secureTextAlertAction = otherAction // Add the actions. alertController.addAction(cancelAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } // MARK: UIAlertControllerStyleActionSheet Style Alerts // Show a dialog with an "Okay" and "Cancel" button. func showOkayCancelActionSheet() { let cancelButtonTitle = NSLocalizedString("Cancel", comment: "OK") let destructiveButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in NSLog("The \"Okay/Cancel\" alert action sheet's cancel action occured.") } let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Okay/Cancel\" alert action sheet's destructive action occured.") } // Add the actions. alertController.addAction(cancelAction) alertController.addAction(destructiveAction) presentViewController(alertController, animated: true, completion: nil) } // Show a dialog with two custom buttons. func showOtherActionSheet() { let destructiveButtonTitle = NSLocalizedString("Destructive Choice", comment: "") let otherButtonTitle = NSLocalizedString("Safe Choice", comment: "") let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) // Create the actions. let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in NSLog("The \"Other\" alert action sheet's destructive action occured.") } let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in NSLog("The \"Other\" alert action sheet's other action occured.") } // Add the actions. alertController.addAction(destructiveAction) alertController.addAction(otherAction) presentViewController(alertController, animated: true, completion: nil) } // MARK: UITextFieldTextDidChangeNotification func handleTextFieldTextDidChangeNotification(notification: NSNotification) { let textField = notification.object as UITextField // Enforce a minimum length of >= 5 for secure text alerts. secureTextAlertAction!.enabled = textField.text.utf16count >= 5 } // MARK: UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // A matrix of closures that should be invoked based on which table view cell is // tapped (index by section, row). let actionMap: Array<Array<() -> Void>> = [ // Alert style alerts. [ showSimpleAlert, showOkayCancelAlert, showOtherAlert, showTextEntryAlert, showSecureTextEntryAlert ], // Action sheet style alerts. [ showOkayCancelActionSheet, showOtherActionSheet ] ] let action = actionMap[indexPath.section][indexPath.row] action() tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
90fce312ca7c1d502d7890491a66701d
42.03861
184
0.648246
false
false
false
false
ajaybeniwal/IOS11AppStoreClone
refs/heads/master
IOS11AppStoreClone/IOS11AppStoreClone/NSEdgeLayoutConstraints.swift
mit
1
import UIKit public final class NSEdgeLayoutConstraints { // MARK: - Properties public var top, left, bottom, right: NSLayoutConstraint private var constraints: [NSLayoutConstraint] { return [top, left, bottom, right] } // MARK: - Init public convenience init(view: UIView, container: UIView) { self.init(view: view, container: container, frame: .zero) } public init(view: UIView, container: UIView, frame: CGRect) { top = view.topAnchor.constraint(equalTo: container.topAnchor, constant: frame.minY) left = view.leftAnchor.constraint(equalTo: container.leftAnchor, constant: frame.minX) bottom = view.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: frame.maxY - container.frame.height) right = view.rightAnchor.constraint(equalTo: container.rightAnchor, constant: frame.maxX - container.frame.width) } public func constants(to value: CGFloat) { constraints.forEach { $0.constant = value } } public func verticalConstants(to value: CGFloat) { top.constant = value bottom.constant = value } public func horizontalConstants(to value: CGFloat) { left.constant = value right.constant = value } public func match(to frame: CGRect, container: UIView) { top.constant = frame.minY+20 left.constant = frame.minX bottom.constant = frame.maxY - container.frame.height-20 right.constant = frame.maxX - container.frame.width } public func toggleConstraints(_ value: Bool) { constraints.forEach { $0.isActive = value } } }
b11d29bb61d701474461de1bb57762c4
33.607843
94
0.624929
false
false
false
false
dusek/firefox-ios
refs/heads/master
Sync/EncryptedRecord.swift
mpl-2.0
3
/* 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 FxA public class KeyBundle : Equatable { let encKey: NSData; let hmacKey: NSData; public class func random() -> KeyBundle { // Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which // on iOS is populated by the OS from kernel-level sources of entropy. // That should mean that we don't need to seed or initialize anything before calling // this. That is probably not true on (some versions of) OS X. return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32)) } public class var invalid: KeyBundle { return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef") } public init(encKeyB64: String, hmacKeyB64: String) { self.encKey = Bytes.decodeBase64(encKeyB64) self.hmacKey = Bytes.decodeBase64(hmacKeyB64) } public init(encKey: NSData, hmacKey: NSData) { self.encKey = encKey self.hmacKey = hmacKey } private func _hmac(ciphertext: NSData) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) { let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256) let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CCHmac(hmacAlgorithm, hmacKey.bytes, UInt(hmacKey.length), ciphertext.bytes, UInt(ciphertext.length), result) return (result, digestLen) } public func hmac(ciphertext: NSData) -> NSData { let (result, digestLen) = _hmac(ciphertext) var data = NSMutableData(bytes: result, length: digestLen) result.destroy() return data } /** * Returns a hex string for the HMAC. */ public func hmacString(ciphertext: NSData) -> String { let (result, digestLen) = _hmac(ciphertext) var hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(hash) } public func encrypt(cleartext: NSData, iv: NSData?=nil) -> (ciphertext: NSData, iv: NSData)? { let iv = iv ?? Bytes.generateRandomBytes(16) let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = NSData(bytes: b, length: Int(copied)) b.destroy() return (d, iv) } b.destroy() return nil } // You *must* verify HMAC before calling this. public func decrypt(ciphertext: NSData, iv: NSData) -> String? { let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = NSData(bytesNoCopy: b, length: Int(copied)) let s = NSString(data: d, encoding: NSUTF8StringEncoding) b.destroy() return s } b.destroy() return nil } private func crypt(input: NSData, iv: NSData, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutablePointer<CUnsignedChar>, count: UInt) { let resultSize = input.length + kCCBlockSizeAES128 let result = UnsafeMutablePointer<CUnsignedChar>.alloc(resultSize) var copied: UInt = 0 let success: CCCryptorStatus = CCCrypt(op, CCHmacAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), encKey.bytes, UInt(kCCKeySizeAES256), iv.bytes, input.bytes, UInt(input.length), result, UInt(resultSize), &copied ); return (success, result, copied) } public func verify(#hmac: NSData, ciphertextB64: NSData) -> Bool { let expectedHMAC = hmac let computedHMAC = self.hmac(ciphertextB64) return expectedHMAC.isEqualToData(computedHMAC) } public func factory<T : CleartextPayloadJSON>() -> (String) -> T? { return { (payload: String) -> T? in let potential = EncryptedJSON(json: payload, keyBundle: self) if !(potential.isValid()) { return nil } let cleartext = potential.cleartext if (cleartext == nil) { return nil } return T(cleartext!) } } } public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool { return lhs.encKey.isEqualToData(rhs.encKey) && lhs.hmacKey.isEqualToData(rhs.hmacKey) } public class Keys { let valid: Bool let defaultBundle: KeyBundle var collectionKeys: [String: KeyBundle] = [String: KeyBundle]() public init(defaultBundle: KeyBundle) { self.defaultBundle = defaultBundle self.valid = true } public init(downloaded: EnvelopeJSON, master: KeyBundle) { let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory()) if let payload: KeysPayload = keysRecord?.payload { if payload.isValid() && payload.defaultKeys != nil { self.defaultBundle = payload.defaultKeys! self.valid = true return } self.defaultBundle = KeyBundle.invalid self.valid = false return } self.defaultBundle = KeyBundle.invalid self.valid = true } public func forCollection(collection: String) -> KeyBundle { if let bundle = collectionKeys[collection] { return bundle } return defaultBundle } public func factory<T : CleartextPayloadJSON>(collection: String) -> (String) -> T? { let bundle = forCollection(collection) return bundle.factory() } } /** * Turns JSON of the form * * { ciphertext: ..., hmac: ..., iv: ...} * * into a new JSON object resulting from decrypting and parsing the ciphertext. */ public class EncryptedJSON : JSON { var _cleartext: JSON? // Cache decrypted cleartext. var _ciphertextBytes: NSData? // Cache decoded ciphertext. var _hmacBytes: NSData? // Cache decoded HMAC. var _ivBytes: NSData? // Cache decoded IV. var valid: Bool = false var validated: Bool = false let keyBundle: KeyBundle public init(json: String, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(JSON.parse(json)) } public init(json: JSON, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(json) } private func validate() -> Bool { if validated { return valid } valid = self["ciphertext"].isString && self["hmac"].isString && self["IV"].isString if (!valid) { validated = true return false } validated = true if let ciphertextForHMAC = self.ciphertextB64 { return keyBundle.verify(hmac: self.hmac, ciphertextB64: ciphertextForHMAC) } else { return false } } public func isValid() -> Bool { return !isError && self.validate() } func fromBase64(str: String) -> NSData { let b = Bytes.decodeBase64(str) println("Base64 \(str) yielded \(b)") return b } var ciphertextB64: NSData? { if let ct = self["ciphertext"].asString { return Bytes.dataFromBase64(ct) } else { return nil } } var ciphertext: NSData { if (_ciphertextBytes != nil) { return _ciphertextBytes! } _ciphertextBytes = fromBase64(self["ciphertext"].asString!) return _ciphertextBytes! } var hmac: NSData { if (_hmacBytes != nil) { return _hmacBytes! } _hmacBytes = NSData(base16EncodedString: self["hmac"].asString!, options: NSDataBase16DecodingOptions.Default) return _hmacBytes! } var iv: NSData { if (_ivBytes != nil) { return _ivBytes! } _ivBytes = fromBase64(self["IV"].asString!) return _ivBytes! } // Returns nil on error. public var cleartext: JSON? { if (_cleartext != nil) { return _cleartext } if (!validate()) { println("Failed to validate.") return nil } let decrypted: String? = keyBundle.decrypt(self.ciphertext, iv: self.iv) if (decrypted == nil) { println("Failed to decrypt.") valid = false return nil } _cleartext = JSON.parse(decrypted!) return _cleartext! } }
ca157325a1821466c644eff3d4eb5a59
29.321192
155
0.580275
false
false
false
false
jduquennoy/Log4swift
refs/heads/master
Log4swift/Appenders/Appender.swift
apache-2.0
1
// // Appender.swift // log4swift // // Created by Jérôme Duquennoy on 14/06/2015. // Copyright © 2015 Jérôme Duquennoy. 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 /** Appenders are responsible for sending logs to heir destination. This class is the base class, from which all appenders should inherit. */ @objc open class Appender: NSObject { public enum DictionaryKey: String { case ThresholdLevel = "ThresholdLevel" case FormatterId = "FormatterId" } @objc let identifier: String @objc public var thresholdLevel = LogLevel.Debug public var formatter: Formatter? @objc public required init(_ identifier: String) { self.identifier = identifier } open func update(withDictionary dictionary: Dictionary<String, Any>, availableFormatters: Array<Formatter>) throws { if let safeThresholdString = (dictionary[DictionaryKey.ThresholdLevel.rawValue] as? String) { if let safeThreshold = LogLevel(safeThresholdString) { thresholdLevel = safeThreshold } else { throw NSError.Log4swiftError(description: "Invalid '\(DictionaryKey.ThresholdLevel.rawValue)' for appender '\(self.identifier)'") } } if let safeFormatterId = (dictionary[DictionaryKey.FormatterId.rawValue] as? String) { if let formatter = availableFormatters.find(filter: { $0.identifier == safeFormatterId }) { self.formatter = formatter } else { throw NSError.Log4swiftError(description: "No such formatter '\(safeFormatterId)' for appender \(self.identifier)") } } } open func performLog(_ log: String, level: LogLevel, info: LogInfoDictionary) { // To be overriden by subclasses } final func log(_ log: String, level: LogLevel, info: LogInfoDictionary) { if(level.rawValue >= self.thresholdLevel.rawValue) { let logMessage: String if let formatter = self.formatter { logMessage = formatter.format(message: log, info: info) } else { logMessage = log } self.performLog(logMessage, level: level, info: info) } } } extension Appender { static var availableAppenderTypes: [Appender.Type] { return AppendersRegistry.appenders } }
a7afdee8f13e293b47209a1d30ce31db
32.02381
137
0.700793
false
false
false
false
j-chao/venture
refs/heads/master
source/venture/NewTripVC.swift
mit
1
// // NewTripVC.swift // venture // // Created by Justin Chao on 3/18/17. // Copyright © 2017 Group1. All rights reserved. // import UIKit import Firebase class NewTripVC: UIViewController, UITextFieldDelegate { var ref: FIRDatabaseReference! = FIRDatabase.database().reference() let userID = FIRAuth.auth()?.currentUser!.uid @IBOutlet weak var tripName: UITextField! @IBOutlet weak var tripLocation: UITextField! @IBOutlet weak var datePick: UIDatePicker! @IBOutlet weak var startDate: UILabel! @IBOutlet weak var endDate: UILabel! override func viewDidLoad() { self.setBackground() super.viewDidLoad() tripName.attributedPlaceholder = NSAttributedString(string: "trip name", attributes: [NSForegroundColorAttributeName:UIColor.lightGray]) tripLocation.attributedPlaceholder = NSAttributedString(string: "location", attributes: [NSForegroundColorAttributeName:UIColor.lightGray]) tripName.delegate = self tripLocation.delegate = self datePick.backgroundColor = .white datePick.setValue(0.8, forKeyPath: "alpha") } var startingDate:Date? = nil var endingDate:Date? = nil @IBAction func setStart(_ sender: Any) { startingDate = datePick.date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/YYYY" self.startDate.text = dateFormatter.string(from: datePick.date) } @IBAction func setEnd(_ sender: Any) { endingDate = datePick.date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MM/dd/YYYY" self.endDate.text = dateFormatter.string(from: datePick.date) } @IBAction func createTrip(_ sender: Any) { if tripName.text!.isEmpty || tripLocation.text!.isEmpty || startDate.text!.isEmpty || endDate.text!.isEmpty { let alert = UIAlertController(title: "Error", message: "You must enter a value for all fields." , preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action:UIAlertAction) in } alert.addAction(OKAction) self.present(alert, animated: true, completion:nil) return } else if endingDate! < startingDate! { let alert = UIAlertController(title: "Error", message: "End date must not be earlier than start date." , preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action:UIAlertAction) in } alert.addAction(OKAction) self.present(alert, animated: true, completion:nil) return } self.addTrip(tripName:tripName.text!, tripLocation:tripLocation.text!, startDate:startDate.text!, endDate:endDate.text!, food:"0", transportation:"0", lodging:"0", attractions:"0", misc:"0", total:"0") let storyboard: UIStoryboard = UIStoryboard(name: "trip", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "tripNavCtrl") self.show(vc, sender: self) } func addTrip (tripName:String, tripLocation:String, startDate:String, endDate:String, food:String, transportation:String, lodging:String, attractions:String, misc:String, total:String) { let tripRef = ref.child("users/\(userID!)/trips/\(tripName)") tripRef.child("tripName").setValue(tripName) tripRef.child("tripLocation").setValue(tripLocation) tripRef.child("startDate").setValue(startDate) tripRef.child("endDate").setValue(endDate) // adding default budget values let tripBudgetRef = ref.child("users/\(userID!)/budgets/\(tripName)") tripBudgetRef.child("food").setValue(food) tripBudgetRef.child("transportation").setValue(transportation) tripBudgetRef.child("lodging").setValue(lodging) tripBudgetRef.child("attractions").setValue(attractions) tripBudgetRef.child("misc").setValue(misc) tripBudgetRef.child("total").setValue(total) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
298fbf733e3e6e493c2ccdf97ee2f5e9
40.53271
209
0.659541
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
refs/heads/master
RxSwiftGuideRead/RxSwift-master/Tests/RxRelayTests/Observable+RelayBindTests.swift
mit
3
// // Observable+RelayBindTests.swift // Tests // // Created by Shai Mishali on 09/04/2019. // Copyright © 2019 Krunoslav Zaher. All rights reserved. // import RxSwift import RxRelay import RxTest import XCTest class ObservableRelayBindTest: RxTest { } // MARK: bind(to:) publish relay extension ObservableRelayBindTest { func testBindToPublishRelay() { var events: [Recorded<Event<Int>>] = [] let relay = PublishRelay<Int>() _ = relay.subscribe{ event in events.append(Recorded(time: 0, value: event)) } _ = Observable.just(1).bind(to: relay) XCTAssertEqual(events, [ .next(1) ]) } func testBindToPublishRelays() { var events1: [Recorded<Event<Int>>] = [] var events2: [Recorded<Event<Int>>] = [] let relay1 = PublishRelay<Int>() let relay2 = PublishRelay<Int>() _ = relay1.subscribe { event in events1.append(Recorded(time: 0, value: event)) } _ = relay2.subscribe { event in events2.append(Recorded(time: 0, value: event)) } _ = Observable.just(1).bind(to: relay1, relay2) XCTAssertEqual(events1, [ .next(1) ]) XCTAssertEqual(events2, [ .next(1) ]) } func testBindToOptionalPublishRelay() { var events: [Recorded<Event<Int?>>] = [] let relay = PublishRelay<Int?>() _ = relay.subscribe { event in events.append(Recorded(time: 0, value: event)) } _ = (Observable.just(1) as Observable<Int>).bind(to: relay) XCTAssertEqual(events, [ .next(1) ]) } func testBindToOptionalPublishRelays() { var events1: [Recorded<Event<Int?>>] = [] var events2: [Recorded<Event<Int?>>] = [] let relay1 = PublishRelay<Int?>() let relay2 = PublishRelay<Int?>() _ = relay1.subscribe { event in events1.append(Recorded(time: 0, value: event)) } _ = relay2.subscribe { event in events2.append(Recorded(time: 0, value: event)) } _ = (Observable.just(1) as Observable<Int>).bind(to: relay1, relay2) XCTAssertEqual(events1, [ .next(1) ]) XCTAssertEqual(events2, [ .next(1) ]) } func testBindToPublishRelayNoAmbiguity() { var events: [Recorded<Event<Int?>>] = [] let relay = PublishRelay<Int?>() _ = relay.subscribe { event in events.append(Recorded(time: 0, value: event)) } _ = Observable.just(1).bind(to: relay) XCTAssertEqual(events, [ .next(1) ]) } } // MARK: bind(to:) behavior relay extension ObservableRelayBindTest { func testBindToBehaviorRelay() { let relay = BehaviorRelay<Int>(value: 0) _ = Observable.just(1).bind(to: relay) XCTAssertEqual(relay.value, 1) } func testBindToBehaviorRelays() { let relay1 = BehaviorRelay<Int>(value: 0) let relay2 = BehaviorRelay<Int>(value: 0) _ = Observable.just(1).bind(to: relay1, relay2) XCTAssertEqual(relay1.value, 1) XCTAssertEqual(relay2.value, 1) } func testBindToOptionalBehaviorRelay() { let relay = BehaviorRelay<Int?>(value: 0) _ = (Observable.just(1) as Observable<Int>).bind(to: relay) XCTAssertEqual(relay.value, 1) } func testBindToOptionalBehaviorRelays() { let relay1 = BehaviorRelay<Int?>(value: 0) let relay2 = BehaviorRelay<Int?>(value: 0) _ = (Observable.just(1) as Observable<Int>).bind(to: relay1, relay2) XCTAssertEqual(relay1.value, 1) XCTAssertEqual(relay2.value, 1) } func testBindToBehaviorRelayNoAmbiguity() { let relay = BehaviorRelay<Int?>(value: 0) _ = Observable.just(1).bind(to: relay) XCTAssertEqual(relay.value, 1) } }
5a6e3210b6883a45914cb386446bd84c
23.301205
76
0.567179
false
true
false
false
robotwholearned/GettingStarted
refs/heads/master
Meal.swift
mit
1
// // Meal.swift // FoodTracker // // Created by Sandquist, Cassandra - Cassandra on 3/12/16. // Copyright © 2016 robotwholearned. All rights reserved. // import UIKit class Meal: NSObject, NSCoding { // MARK: Properties var name: String var photo: UIImage? var rating: Int // MARK: Archiving Paths static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals") // MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" static let ratingKey = "rating" } // MARK: Initialization init?(name: String, photo: UIImage?, rating: Int) { // Initialize stored properties. self.name = name self.photo = photo self.rating = rating super.init() // Initialization should fail if there is no name or if the rating is negative. if name.isEmpty || rating < 0 { return nil } } // MARK: NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: PropertyKey.nameKey) aCoder.encodeObject(photo, forKey: PropertyKey.photoKey) aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey) self.init(name: name, photo: photo, rating: rating) } }
80afc6fb983d90c03f0608914b0474fb
28.305085
123
0.662811
false
false
false
false
hikelee/hotel
refs/heads/master
Sources/Video/Models/Config.swift
mit
1
import Vapor import Fluent import HTTP import Common final class Config: HotelBasedModel { static var entity: String { return "hotel_config" } var id: Node? var channelId: Node? var hotelId: Node? var host: String? var enabled: Bool = false //items var exists: Bool = false //used in fluent init(node: Node) throws { id = try? node.extract("id") channelId = try? node.extract("channel_id") hotelId = try? node.extract("hotel_id") host = try node.extract("host") enabled = node["enabled"]?.bool ?? false } convenience init(node: Node, in context: Context) throws { try self.init(node:node) } func makeNode() throws->Node { return try Node( node:[ "id": id, "channel_id": channelId, "hotel_id": hotelId, "host": host, "enabled": enabled, ]) } func validate(isCreate: Bool) throws -> [String:String] { var result:[String:String]=[:] if (hotelId?.int ?? 0) == 0 { result["hotel_id"] = "必选项"; }else if try (Hotel.query().filter("id", .equals, hotelId!).first()) == nil { result["hotel_id"] = "找不到所选的酒店" } if host?.isEmpty ?? true{result["host"]="必填项"} return result } }
28219757e7b7c80ca009457c999c0b8a
26.1
86
0.538745
false
false
false
false
PlanTeam/BSON
refs/heads/master/8.0
Sources/BSON/Document/Document.swift
mit
1
import Foundation import NIO // TODO: ByteBuffer is missing Sendable annotation, but is Sendable public struct Document: Primitive, @unchecked Sendable { static let allocator = ByteBufferAllocator() /// The internal storage engine that stores BSON in it's original binary form /// The null terminator is missing here for performance reasons. We append it in `makeData()` var storage: ByteBuffer var usedCapacity: Int32 { get { guard let int = storage.getInteger(at: 0, endianness: .little, as: Int32.self) else { assertionFailure("Corrupted document header") return 0 } return int } set { Swift.assert(usedCapacity >= 5) storage.setInteger(newValue, at: 0, endianness: .little) } } /// Dictates whether this `Document` is an `Array` or `Dictionary`-like type public internal(set) var isArray: Bool /// Creates a new empty BSONDocument /// /// `isArray` dictates what kind of subdocument the `Document` is, and is `false` by default public init(isArray: Bool = false) { var buffer = Document.allocator.buffer(capacity: 4_096) buffer.writeInteger(Int32(5), endianness: .little) buffer.writeInteger(UInt8(0), endianness: .little) self.storage = buffer self.isArray = isArray } /// Creates a new `Document` by parsing an existing `ByteBuffer` public init(buffer: ByteBuffer, isArray: Bool = false) { self.storage = buffer self.isArray = isArray } /// Creates a new `Document` by parsing the existing `Data` buffer public init(data: Data, isArray: Bool = false) { self.storage = Document.allocator.buffer(capacity: data.count) self.storage.writeBytes(data) self.isArray = isArray } /// Creates a new `Document` from the given bytes public init(bytes: [UInt8], isArray: Bool = false) { self.storage = Document.allocator.buffer(capacity: bytes.count) self.storage.writeBytes(bytes) self.isArray = isArray } }
5d4fc625f325016f97ef08f688d8f529
35.05
97
0.630143
false
false
false
false
eliburke/swamp
refs/heads/master
Example/Pods/CryptoSwift/Sources/CryptoSwift/PKCS5/PBKDF2.swift
mit
2
// // PBKDF2.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 05/04/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // #if os(Linux) import Glibc #else import Darwin #endif public extension PKCS5 { /// A key derivation function. /// /// PBKDF2 - Password-Based Key Derivation Function 2. Key stretching technique. /// DK = PBKDF2(PRF, Password, Salt, c, dkLen) public struct PBKDF2 { public enum Error: Swift.Error { case invalidInput case derivedKeyTooLong } private let salt: Array<UInt8> // S fileprivate let iterations: Int // c private let numBlocks: UInt // l private let dkLen: Int; fileprivate let prf: HMAC /// - parameters: /// - salt: salt /// - variant: hash variant /// - iterations: iteration count, a positive integer /// - keyLength: intended length of derived key public init(password: Array<UInt8>, salt: Array<UInt8>, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha256) throws { precondition(iterations > 0) let prf = HMAC(key: password, variant: variant) guard iterations > 0 && !password.isEmpty && !salt.isEmpty else { throw Error.invalidInput } self.dkLen = keyLength ?? variant.digestSize let keyLengthFinal = Double(self.dkLen) let hLen = Double(prf.variant.digestSize) if keyLengthFinal > (pow(2,32) - 1) * hLen { throw Error.derivedKeyTooLong } self.salt = salt self.iterations = iterations self.prf = prf self.numBlocks = UInt(ceil(Double(keyLengthFinal) / hLen)) // l = ceil(keyLength / hLen) } public func calculate() -> Array<UInt8> { var ret = Array<UInt8>() for i in 1...self.numBlocks { // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter if let value = calculateBlock(self.salt, blockNum: i) { ret.append(contentsOf: value) } } return Array(ret.prefix(self.dkLen)) } } } fileprivate extension PKCS5.PBKDF2 { func INT(_ i: UInt) -> Array<UInt8> { var inti = Array<UInt8>(repeating: 0, count: 4) inti[0] = UInt8((i >> 24) & 0xFF) inti[1] = UInt8((i >> 16) & 0xFF) inti[2] = UInt8((i >> 8) & 0xFF) inti[3] = UInt8(i & 0xFF) return inti } // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c // U_1 = PRF (P, S || INT (i)) func calculateBlock(_ salt: Array<UInt8>, blockNum: UInt) -> Array<UInt8>? { guard let u1 = try? prf.authenticate(salt + INT(blockNum)) else { return nil } do { var u = u1 var ret = u if self.iterations > 1 { // U_2 = PRF (P, U_1) , // U_c = PRF (P, U_{c-1}) . for _ in 2...self.iterations { u = try prf.authenticate(u) for x in 0..<ret.count { ret[x] = ret[x] ^ u[x] } } } return ret } catch { return nil } } }
54d13ccae26fdc178676b82e64aa259c
30.385321
172
0.498977
false
false
false
false
honghaoz/2048-Solver-AI
refs/heads/master
2048 AI/AI/TDLearning/State2048.swift
gpl-2.0
1
// Copyright © 2019 ChouTi. All rights reserved. import Foundation final class State2048 { struct METRIC { static var SIZE = 4 static var BOARD_SIZE = RectSize(size: SIZE) static var num_initial_locations = 2 static var four_probability = 1 } let size = 4 let board_size = RectSize(size: 4) let num_initial_locations = 2 let four_probability: Int = 1 // out of 10 let rewards: [Int] = [0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536] let myInt: [Int: Int] = [0: 0, 2: 1, 4: 2, 8: 3, 16: 4, 32: 5, 64: 6, 128: 7, 256: 8, 512: 9, 1024: 10, 2048: 11, 4096: 12, 8192: 13, 16384: 14, 32768: 15, 65536: 16] var board: [[Int]] init() { self.board = Array(count: size, repeatedValue: Array(count: 4, repeatedValue: 0)) } convenience init(state: State2048) { self.init() for i in 0..<size { for j in 0..<size { board[i][j] = state.board[i][j] } } } convenience init(data: [[Int]]) { self.init() var feature = [Int]() for array in data { for val in array { feature.append(myInt[val]!) } } var index = 0 for i in 0..<size { for j in 0..<size { board[i][j] = Int(feature[index]) index += 1 } } } // initialize the state with features, which is a double Array convenience init(features: [Double]) { self.init() var index = 0 for i in 0..<size { for j in 0..<size { board[i][j] = Int(features[index]) index += 1 } } } // the number of values that a board could provide func getNumValues() -> Int { return rewards.count } // return the powered grid func getPowerGrid() -> [[Int]] { var grid: [[Int]] = Array(count: size, repeatedValue: Array(count: 4, repeatedValue: 0)) for i in 0..<size { for j in 0..<size { grid[i][j] = rewards[board[i][j]] } } return grid } // features is a list by flatten the board func getFeatures() -> [Double] { var index = 0 // BUGFIXED: firstly we should create the empty pos. var features = Array(count: size * size, repeatedValue: 0.0) for i in 0..<size { for j in 0..<size { features[index] = Double(board[i][j]) index += 1 } } return features } func getValue(_ flatLocation: Int) -> Int { return board[flatLocation / size][flatLocation % size] } func setValue(_ flatLocation: Int, value: Int) { board[flatLocation / size][flatLocation % size] = value } // add random tile func addRandomTile() { var emptyLocations: [Int] = [Int]() for location in 0..<size * size { if getValue(location) == 0 { emptyLocations.append(location) } } if emptyLocations.isEmpty { return } let randomLoc = emptyLocations[Int(arc4random_uniform(UInt32(emptyLocations.count)))] let isFour: Bool = (Int(arc4random_uniform(10)) < four_probability) if isFour { setValue(randomLoc, value: 2) } else { setValue(randomLoc, value: 1) } } // Move up a board func moveUp() -> Int { var reward = 0 for col in 0..<size { var firstFreeRow = 0 var alreadyAggregated = false for row in 0..<size { if board[row][col] == 0 { continue } if firstFreeRow > 0, !alreadyAggregated, board[firstFreeRow - 1][col] == board[row][col] { board[firstFreeRow - 1][col] += 1 board[row][col] = 0 reward += rewards[board[firstFreeRow - 1][col]] alreadyAggregated = true } else { let tmp = board[row][col] board[row][col] = 0 board[firstFreeRow][col] = tmp firstFreeRow += 1 alreadyAggregated = false } } } return reward } // rotate a state func rotateBoard() { for i in 0..<size / 2 { for j in i..<size - i - 1 { let tmp = board[i][j] board[i][j] = board[j][size - i - 1] board[j][size - i - 1] = board[size - i - 1][size - j - 1] board[size - i - 1][size - j - 1] = board[size - j - 1][i] board[size - j - 1][i] = tmp } } } // make a move func makeMove(_ action: Action2048) -> Int { var reward = 0 switch action { case .UP: reward = moveUp() case .DOWN: rotateBoard() rotateBoard() reward = moveUp() rotateBoard() rotateBoard() case .RIGHT: rotateBoard() reward = moveUp() rotateBoard() rotateBoard() rotateBoard() case .LEFT: rotateBoard() rotateBoard() rotateBoard() reward = moveUp() rotateBoard() } return reward } // getPossibleMoves func getPossibleMoves() -> [Action2048] { var set: [Bool] = Array(count: 4, repeatedValue: false) var moves: [Action2048] = Array() for row in 0..<size { for col in 0..<size { if board[row][col] > 0 { continue } if !set[Action2048.rawValue(Action2048.RIGHT).0] { for col2 in 0..<col { if board[row][col2] > 0 { set[Action2048.rawValue(Action2048.RIGHT).0] = true moves.append(Action2048.RIGHT) break } } } if !set[Action2048.rawValue(Action2048.LEFT).0] { for col2 in (col + 1)..<size { if board[row][col2] > 0 { set[Action2048.rawValue(Action2048.LEFT).0] = true moves.append(Action2048.LEFT) break } } } if !set[Action2048.rawValue(Action2048.DOWN).0] { for row2 in 0..<row { if board[row2][col] > 0 { set[Action2048.rawValue(Action2048.DOWN).0] = true moves.append(Action2048.DOWN) break } } } if !set[Action2048.rawValue(Action2048.UP).0] { for row2 in (row + 1)..<size { if board[row2][col] > 0 { set[Action2048.rawValue(Action2048.UP).0] = true moves.append(Action2048.UP) break } } } if moves.count == 4 { return moves } } } if !set[Action2048.rawValue(Action2048.RIGHT).0] || !set[Action2048.rawValue(Action2048.LEFT).0] { for row in 0..<size { for col in 0..<size - 1 { if board[row][col] > 0, board[row][col] == board[row][col + 1] { set[Action2048.rawValue(Action2048.LEFT).0] = true set[Action2048.rawValue(Action2048.RIGHT).0] = true moves.append(Action2048.LEFT) moves.append(Action2048.RIGHT) break } } } } if !set[Action2048.rawValue(Action2048.DOWN).0] || !set[Action2048.rawValue(Action2048.UP).0] { for col in 0..<size { for row in 0..<size - 1 { if board[row][col] > 0, board[row][col] == board[row + 1][col] { set[Action2048.rawValue(Action2048.UP).0] = true set[Action2048.rawValue(Action2048.DOWN).0] = true moves.append(Action2048.UP) moves.append(Action2048.DOWN) break } } } } return moves } private func hasEqualNeighbour(_ row: Int, col: Int) -> Bool { if (row > 0 && board[row - 1][col] == board[row][col]) || (col < size - 1 && board[row][col + 1] == board[row][col]) || (row < size - 1 && board[row + 1][col] == board[row][col]) || (col > 0 && board[row][col - 1] == board[row][col]) { return true } else { return false } } // Determine the terminated state func isTerminal() -> Bool { for row in 0..<size { for col in 0..<size { if board[row][col] == 0 { return false } } } for row in 0..<size { for col in 0..<size { if hasEqualNeighbour(row, col: col) { return false } } } return true } // Return the maximum score of current board func getMaxTile() -> Int { var maxTile: Int = 0 for row in 0..<size { for col in 0..<size { if board[row][col] > maxTile { maxTile = board[row][col] } } } return rewards[maxTile] } // Pretty Print func prettyPrint() { let DisplayFormat = "05" for row in 0..<size { for col in 0..<size { print("\(rewards[board[row][col]].format(DisplayFormat)) ", terminator: "") } print("") } print("") } // Factory Method Return an initial State class func getInitialState(_ numLocations: Int) -> State2048 { let state = State2048() for _ in 0..<numLocations { state.addRandomTile() } return state } class func getInitialState() -> State2048 { return State2048.getInitialState(2) } }
1fb08fa225ce7a91e3820519a6cd2a40
23.803324
168
0.530266
false
false
false
false
krzysztofzablocki/Sourcery
refs/heads/master
SourceryRuntime/Sources/AST/TypeName/Tuple.swift
mit
1
import Foundation /// Describes tuple type @objcMembers public final class TupleType: NSObject, SourceryModel { /// Type name used in declaration public var name: String /// Tuple elements public var elements: [TupleElement] /// :nodoc: public init(name: String, elements: [TupleElement]) { self.name = name self.elements = elements } /// :nodoc: public init(elements: [TupleElement]) { self.name = elements.asSource self.elements = elements } // sourcery:inline:TupleType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let elements: [TupleElement] = aDecoder.decode(forKey: "elements") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["elements"])); fatalError() }; self.elements = elements } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.elements, forKey: "elements") } // sourcery:end } /// Describes tuple type element @objcMembers public final class TupleElement: NSObject, SourceryModel, Typed { /// Tuple element name public let name: String? /// Tuple element type name public var typeName: TypeName // sourcery: skipEquality, skipDescription /// Tuple element type, if known public var type: Type? /// :nodoc: public init(name: String? = nil, typeName: TypeName, type: Type? = nil) { self.name = name self.typeName = typeName self.type = type } public var asSource: String { // swiftlint:disable:next force_unwrapping "\(name != nil ? "\(name!): " : "")\(typeName.asSource)" } // sourcery:inline:TupleElement.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { self.name = aDecoder.decode(forKey: "name") guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") } // sourcery:end } extension Array where Element == TupleElement { public var asSource: String { "(\(map { $0.asSource }.joined(separator: ", ")))" } public var asTypeName: String { "(\(map { $0.typeName.asSource }.joined(separator: ", ")))" } }
dac98886cf40a1e559ac58f75b85c07c
32.626374
255
0.624837
false
false
false
false
grpc/grpc-swift
refs/heads/main
Tests/GRPCTests/FunctionalTests.swift
apache-2.0
1
/* * Copyright 2019, gRPC Authors 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 Dispatch import EchoModel import Foundation @testable import GRPC import NIOCore import NIOHTTP1 import NIOHTTP2 import XCTest class FunctionalTestsInsecureTransport: EchoTestCaseBase { override var transportSecurity: TransportSecurity { return .none } var aFewStrings: [String] { return ["foo", "bar", "baz"] } var lotsOfStrings: [String] { return (0 ..< 500).map { String(describing: $0) } } func doTestUnary( request: Echo_EchoRequest, expect response: Echo_EchoResponse, file: StaticString = #filePath, line: UInt = #line ) { let responseExpectation = self.makeResponseExpectation() let statusExpectation = self.makeStatusExpectation() let call = client.get(request) call.response.assertEqual(response, fulfill: responseExpectation, file: file, line: line) call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line) self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout) } func doTestUnary(message: String, file: StaticString = #filePath, line: UInt = #line) { self.doTestUnary( request: Echo_EchoRequest(text: message), expect: Echo_EchoResponse(text: "Swift echo get: \(message)"), file: file, line: line ) } func testUnary() throws { self.doTestUnary(message: "foo") } func testUnaryLotsOfRequests() throws { guard self.runTimeSensitiveTests() else { return } // Sending that many requests at once can sometimes trip things up, it seems. let clockStart = clock() let numberOfRequests = 200 // Due to https://github.com/apple/swift-nio-http2/issues/87#issuecomment-483542401 we need to // limit the number of active streams. The default in NIOHTTP2 is 100, so we'll use it too. // // In the future we might want to build in some kind of mechanism which handles this for the // user. let batchSize = 100 // Instead of setting a timeout out on the test we'll set one for each batch, if any of them // timeout then we'll bail out of the test. let batchTimeout: TimeInterval = 30.0 self.continueAfterFailure = false for lowerBound in stride(from: 0, to: numberOfRequests, by: batchSize) { let upperBound = min(lowerBound + batchSize, numberOfRequests) let numberOfCalls = upperBound - lowerBound let responseExpectation = self .makeResponseExpectation(expectedFulfillmentCount: numberOfCalls) let statusExpectation = self.makeStatusExpectation(expectedFulfillmentCount: numberOfCalls) for i in lowerBound ..< upperBound { let request = Echo_EchoRequest(text: "foo \(i)") let response = Echo_EchoResponse(text: "Swift echo get: foo \(i)") let get = client.get(request) get.response.assertEqual(response, fulfill: responseExpectation) get.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation) } if upperBound % 100 == 0 { print( "\(upperBound) requests sent so far, elapsed time: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))" ) } self.wait(for: [responseExpectation, statusExpectation], timeout: batchTimeout) } print( "total time to receive \(numberOfRequests) responses: \(Double(clock() - clockStart) / Double(CLOCKS_PER_SEC))" ) } func testUnaryWithLargeData() throws { // Default max frame size is: 16,384. We'll exceed this as we also have to send the size and compression flag. let longMessage = String(repeating: "e", count: 16384) self.doTestUnary(message: longMessage) } func testUnaryEmptyRequest() throws { self.doTestUnary( request: Echo_EchoRequest(), expect: Echo_EchoResponse(text: "Swift echo get: ") ) } func doTestClientStreaming( messages: [String], file: StaticString = #filePath, line: UInt = #line ) throws { let responseExpectation = self.makeResponseExpectation() let statusExpectation = self.makeStatusExpectation() let call = client.collect(callOptions: CallOptions(timeLimit: .none)) call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, file: file, line: line) call.response.assertEqual( Echo_EchoResponse(text: "Swift echo collect: \(messages.joined(separator: " "))"), fulfill: responseExpectation ) call.sendMessages(messages.map { .init(text: $0) }, promise: nil) call.sendEnd(promise: nil) self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout) } func testClientStreaming() { XCTAssertNoThrow(try self.doTestClientStreaming(messages: self.aFewStrings)) } func testClientStreamingLotsOfMessages() throws { guard self.runTimeSensitiveTests() else { return } XCTAssertNoThrow(try self.doTestClientStreaming(messages: self.lotsOfStrings)) } private func doTestServerStreaming(messages: [String], line: UInt = #line) throws { let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count) let statusExpectation = self.makeStatusExpectation() var iterator = messages.enumerated().makeIterator() let call = client.expand(Echo_EchoRequest(text: messages.joined(separator: " "))) { response in if let (index, message) = iterator.next() { XCTAssertEqual( Echo_EchoResponse(text: "Swift echo expand (\(index)): \(message)"), response, line: line ) responseExpectation.fulfill() } else { XCTFail("Too many responses received", line: line) } } call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line) self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout) } func testServerStreaming() { XCTAssertNoThrow(try self.doTestServerStreaming(messages: self.aFewStrings)) } func testServerStreamingLotsOfMessages() { guard self.runTimeSensitiveTests() else { return } XCTAssertNoThrow(try self.doTestServerStreaming(messages: self.lotsOfStrings)) } private func doTestBidirectionalStreaming( messages: [String], waitForEachResponse: Bool = false, line: UInt = #line ) throws { let responseExpectation = self.makeResponseExpectation(expectedFulfillmentCount: messages.count) let statusExpectation = self.makeStatusExpectation() let responseReceived = waitForEachResponse ? DispatchSemaphore(value: 0) : nil var iterator = messages.enumerated().makeIterator() let call = client.update { response in if let (index, message) = iterator.next() { XCTAssertEqual( Echo_EchoResponse(text: "Swift echo update (\(index)): \(message)"), response, line: line ) responseExpectation.fulfill() responseReceived?.signal() } else { XCTFail("Too many responses received", line: line) } } call.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation, line: line) messages.forEach { part in call.sendMessage(Echo_EchoRequest(text: part), promise: nil) XCTAssertNotEqual( responseReceived?.wait(timeout: .now() + .seconds(30)), .some(.timedOut), line: line ) } call.sendEnd(promise: nil) self.wait(for: [responseExpectation, statusExpectation], timeout: self.defaultTestTimeout) } func testBidirectionalStreamingBatched() throws { XCTAssertNoThrow(try self.doTestBidirectionalStreaming(messages: self.aFewStrings)) } func testBidirectionalStreamingPingPong() throws { XCTAssertNoThrow( try self .doTestBidirectionalStreaming(messages: self.aFewStrings, waitForEachResponse: true) ) } func testBidirectionalStreamingLotsOfMessagesBatched() throws { guard self.runTimeSensitiveTests() else { return } XCTAssertNoThrow(try self.doTestBidirectionalStreaming(messages: self.lotsOfStrings)) } func testBidirectionalStreamingLotsOfMessagesPingPong() throws { guard self.runTimeSensitiveTests() else { return } XCTAssertNoThrow( try self .doTestBidirectionalStreaming(messages: self.lotsOfStrings, waitForEachResponse: true) ) } } #if canImport(NIOSSL) class FunctionalTestsAnonymousClient: FunctionalTestsInsecureTransport { override var transportSecurity: TransportSecurity { return .anonymousClient } override func testUnary() throws { try super.testUnary() } override func testUnaryLotsOfRequests() throws { try super.testUnaryLotsOfRequests() } override func testUnaryWithLargeData() throws { try super.testUnaryWithLargeData() } override func testUnaryEmptyRequest() throws { try super.testUnaryEmptyRequest() } override func testClientStreaming() { super.testClientStreaming() } override func testClientStreamingLotsOfMessages() throws { try super.testClientStreamingLotsOfMessages() } override func testServerStreaming() { super.testServerStreaming() } override func testServerStreamingLotsOfMessages() { super.testServerStreamingLotsOfMessages() } override func testBidirectionalStreamingBatched() throws { try super.testBidirectionalStreamingBatched() } override func testBidirectionalStreamingPingPong() throws { try super.testBidirectionalStreamingPingPong() } override func testBidirectionalStreamingLotsOfMessagesBatched() throws { try super.testBidirectionalStreamingLotsOfMessagesBatched() } override func testBidirectionalStreamingLotsOfMessagesPingPong() throws { try super.testBidirectionalStreamingLotsOfMessagesPingPong() } } class FunctionalTestsMutualAuthentication: FunctionalTestsInsecureTransport { override var transportSecurity: TransportSecurity { return .mutualAuthentication } override func testUnary() throws { try super.testUnary() } override func testUnaryLotsOfRequests() throws { try super.testUnaryLotsOfRequests() } override func testUnaryWithLargeData() throws { try super.testUnaryWithLargeData() } override func testUnaryEmptyRequest() throws { try super.testUnaryEmptyRequest() } override func testClientStreaming() { super.testClientStreaming() } override func testClientStreamingLotsOfMessages() throws { try super.testClientStreamingLotsOfMessages() } override func testServerStreaming() { super.testServerStreaming() } override func testServerStreamingLotsOfMessages() { super.testServerStreamingLotsOfMessages() } override func testBidirectionalStreamingBatched() throws { try super.testBidirectionalStreamingBatched() } override func testBidirectionalStreamingPingPong() throws { try super.testBidirectionalStreamingPingPong() } override func testBidirectionalStreamingLotsOfMessagesBatched() throws { try super.testBidirectionalStreamingLotsOfMessagesBatched() } override func testBidirectionalStreamingLotsOfMessagesPingPong() throws { try super.testBidirectionalStreamingLotsOfMessagesPingPong() } } #endif // canImport(NIOSSL) // MARK: - Variants using NIO TS and Network.framework // Unfortunately `swift test --generate-linuxmain` uses the macOS test discovery. Because of this // it's difficult to avoid tests which run on Linux. To get around this shortcoming we can just // run no-op tests on Linux. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) class FunctionalTestsInsecureTransportNIOTS: FunctionalTestsInsecureTransport { override var networkPreference: NetworkPreference { #if canImport(Network) return .userDefined(.networkFramework) #else // We shouldn't need this, since the tests won't do anything. However, we still need to be able // to compile this class. return .userDefined(.posix) #endif } override func testBidirectionalStreamingBatched() throws { #if canImport(Network) try super.testBidirectionalStreamingBatched() #endif } override func testBidirectionalStreamingLotsOfMessagesBatched() throws { #if canImport(Network) try super.testBidirectionalStreamingLotsOfMessagesBatched() #endif } override func testBidirectionalStreamingLotsOfMessagesPingPong() throws { #if canImport(Network) try super.testBidirectionalStreamingLotsOfMessagesPingPong() #endif } override func testBidirectionalStreamingPingPong() throws { #if canImport(Network) try super.testBidirectionalStreamingPingPong() #endif } override func testClientStreaming() { #if canImport(Network) super.testClientStreaming() #endif } override func testClientStreamingLotsOfMessages() throws { #if canImport(Network) try super.testClientStreamingLotsOfMessages() #endif } override func testServerStreaming() { #if canImport(Network) super.testServerStreaming() #endif } override func testServerStreamingLotsOfMessages() { #if canImport(Network) super.testServerStreamingLotsOfMessages() #endif } override func testUnary() throws { #if canImport(Network) try super.testUnary() #endif } override func testUnaryEmptyRequest() throws { #if canImport(Network) try super.testUnaryEmptyRequest() #endif } override func testUnaryLotsOfRequests() throws { #if canImport(Network) try super.testUnaryLotsOfRequests() #endif } override func testUnaryWithLargeData() throws { #if canImport(Network) try super.testUnaryWithLargeData() #endif } } #if canImport(NIOSSL) @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) class FunctionalTestsAnonymousClientNIOTS: FunctionalTestsInsecureTransportNIOTS { override var transportSecurity: TransportSecurity { return .anonymousClient } override func testUnary() throws { try super.testUnary() } override func testUnaryLotsOfRequests() throws { try super.testUnaryLotsOfRequests() } override func testUnaryWithLargeData() throws { try super.testUnaryWithLargeData() } override func testUnaryEmptyRequest() throws { try super.testUnaryEmptyRequest() } override func testClientStreaming() { super.testClientStreaming() } override func testClientStreamingLotsOfMessages() throws { try super.testClientStreamingLotsOfMessages() } override func testServerStreaming() { super.testServerStreaming() } override func testServerStreamingLotsOfMessages() { super.testServerStreamingLotsOfMessages() } override func testBidirectionalStreamingBatched() throws { try super.testBidirectionalStreamingBatched() } override func testBidirectionalStreamingPingPong() throws { try super.testBidirectionalStreamingPingPong() } override func testBidirectionalStreamingLotsOfMessagesBatched() throws { try super.testBidirectionalStreamingLotsOfMessagesBatched() } override func testBidirectionalStreamingLotsOfMessagesPingPong() throws { try super.testBidirectionalStreamingLotsOfMessagesPingPong() } } @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) class FunctionalTestsMutualAuthenticationNIOTS: FunctionalTestsInsecureTransportNIOTS { override var transportSecurity: TransportSecurity { return .mutualAuthentication } override func testUnary() throws { try super.testUnary() } override func testUnaryLotsOfRequests() throws { try super.testUnaryLotsOfRequests() } override func testUnaryWithLargeData() throws { try super.testUnaryWithLargeData() } override func testUnaryEmptyRequest() throws { try super.testUnaryEmptyRequest() } override func testClientStreaming() { super.testClientStreaming() } override func testClientStreamingLotsOfMessages() throws { try super.testClientStreamingLotsOfMessages() } override func testServerStreaming() { super.testServerStreaming() } override func testServerStreamingLotsOfMessages() { super.testServerStreamingLotsOfMessages() } override func testBidirectionalStreamingBatched() throws { try super.testBidirectionalStreamingBatched() } override func testBidirectionalStreamingPingPong() throws { try super.testBidirectionalStreamingPingPong() } override func testBidirectionalStreamingLotsOfMessagesBatched() throws { try super.testBidirectionalStreamingLotsOfMessagesBatched() } override func testBidirectionalStreamingLotsOfMessagesPingPong() throws { try super.testBidirectionalStreamingLotsOfMessagesPingPong() } } #endif // canImport(NIOSSL)
967f24c7b1efcac01d6c78095ee0d59f
29.412698
118
0.730689
false
true
false
false
Donkey-Tao/SinaWeibo
refs/heads/master
SinaWeibo/SinaWeibo/Classes/Home/HomeModel/TFStatusViewModel.swift
mit
1
// // TFStatusViewModel.swift // SinaWeibo // // Created by Donkey-Tao on 2016/10/3. // Copyright © 2016年 http://taofei.me All rights reserved. // import UIKit class TFStatusViewModel: NSObject { //MARK:- 定义属性 var status : TFStatus? //MARK:- 对数据处理的属性 var source_text : String? //处理来源 var created_at_text : String? //处理创建时间 var verifiedImage :UIImage? //处理用户认证图标 var vipImage :UIImage? //处理用户等级 var profileURL : URL? //处理用户头像的URL var picURLs : [URL] = [URL]() //处理微博配图的URL //MARK:- 自定义构造函数 init(status : TFStatus) { self.status = status //1.对来源信息进行处理 if let source = status.source, status.source != "" {//1.1空值校验 //1.2对来源的字符串进行处理 let startIndex = (source as NSString).range(of: ">").location + 1 let length = (source as NSString).range(of: "</").location - startIndex source_text = (source as NSString).substring(with: NSRange(location: startIndex, length: length)) } //2.对时间的处理 if let created_at = status.created_at {//2.1nil值校验 //2.2对时间进行处理 created_at_text = Date.createDateString(created_at) } //3.处理认证 let verified_type = status.user?.verified_type ?? -1 switch verified_type { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2,3,5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } //4.处理会员图标 let mbrank = status.user?.mbrank ?? 0 if mbrank > 0 && mbrank <= 6 { vipImage = UIImage(named: "common_icon_membership_level\(mbrank)") } //5.处理用户头像的URL let profileURLString = status.user?.profile_image_url ?? "" profileURL = URL(string: profileURLString) //6.处理微博配图 if let picURLDicts = status.pic_urls { for picURLDict in picURLDicts { guard let picURLString = picURLDict["thumbnail_pic"] else { continue } picURLs.append(URL(string: picURLString)!)//这里就强制解包了 } } } }
bdd378a9c99bd694feeb36cebea1cca9
31.5
109
0.547436
false
false
false
false
coolmacmaniac/swift-ios
refs/heads/master
LearnSwift/MusicAlbum/MusicAlbum/View/HorizontalScroller.swift
gpl-3.0
1
// // HorizontalScroller.swift // MusicAlbum // // Created by Sourabh on 23/06/17. // Copyright © 2017 Home. All rights reserved. // import UIKit class HorizontalScroller: UIView, UIScrollViewDelegate { public static let VIEW_PADDING = CGFloat(10) public static let VIEW_DIMENSION = CGFloat(100) public static let VIEWS_OFFSET = CGFloat(100) public weak var delegate: HorizontalScrollerDelegate? private var scrollView: UIScrollView override init(frame: CGRect) { let rect = CGRect( x: 0, y: 0, width: frame.size.width, height: frame.size.height ) scrollView = UIScrollView(frame: rect) super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { scrollView = UIScrollView(coder: aDecoder)! super.init(coder: aDecoder) initialize() } private func initialize() { scrollView.delegate = self addSubview(scrollView) let tapGestureRecognizer = UITapGestureRecognizer() tapGestureRecognizer.addTarget(self, action: #selector(scrollerTapped(tapGestureRecognizer:))) scrollView.addGestureRecognizer(tapGestureRecognizer) } override func didMoveToSuperview() { // message is sent to a view when it's added to another view as a subview. // This is the right time to reload the contents of the scroller. self.reload() } @objc private func scrollerTapped(tapGestureRecognizer: UITapGestureRecognizer) { let tapPoint = tapGestureRecognizer.location(in: tapGestureRecognizer.view) // we can't use an enumerator here, because we don't want to enumerate // over all of the UIScrollView subviews. // we want to enumerate only the subviews that we added let numViews = self.delegate?.numberOfViews(in: self) ?? 0 for index in 0..<numViews { let subview = self.scrollView.subviews[index] if subview.frame.contains(tapPoint) { self.delegate?.horizontalScroller(self, didSelectViewAt: index) self.scrollView.setContentOffset(CGPoint( x: subview.frame.origin.x - self.bounds.size.width / 2 + subview.frame.size.width / 2, y: 0 ), animated: true) break } } } private func centerCurrentView() { var xFinal = self.scrollView.contentOffset.x + HorizontalScroller.VIEW_PADDING + ( HorizontalScroller.VIEWS_OFFSET / 2 ) let viewIndex = xFinal / ( HorizontalScroller.VIEW_DIMENSION + 2 * HorizontalScroller.VIEW_PADDING ) xFinal = viewIndex * ( HorizontalScroller.VIEW_DIMENSION + 2 * HorizontalScroller.VIEW_PADDING ) self.scrollView.setContentOffset(CGPoint(x: xFinal, y: 0), animated: true) self.delegate?.horizontalScroller(self, didSelectViewAt: Int(viewIndex)) } public func reload() { // remove all subviews for view in self.scrollView.subviews { view.removeFromSuperview() } // get the total number of subviews let numViews = self.delegate?.numberOfViews(in: self) ?? 0 // xValue is the starting X point of each view inside the scroller var xValue = HorizontalScroller.VIEWS_OFFSET // enumerate and get each view, compute its frame and set it for index in 0 ..< numViews { xValue += HorizontalScroller.VIEW_PADDING let view = (self.delegate?.horizontalScroller(self, viewAt: index))! let frame = CGRect( x: xValue, y: HorizontalScroller.VIEW_PADDING, width: HorizontalScroller.VIEW_DIMENSION, height: HorizontalScroller.VIEW_DIMENSION ) view.frame = frame self.scrollView.addSubview(view) xValue += HorizontalScroller.VIEW_DIMENSION + HorizontalScroller.VIEW_PADDING } // update the content size of scroll view so that it can scroll self.scrollView.contentSize = CGSize( width: xValue + HorizontalScroller.VIEWS_OFFSET, height: self.frame.size.height ) // if an initial view index is set then center it inside the scroll view let initialIndex = CGFloat( self.delegate?.initialViewIndex(in: self) ?? 0 ) self.scrollView.setContentOffset(CGPoint( x: initialIndex * ( 2 * HorizontalScroller.VIEW_PADDING + HorizontalScroller.VIEW_DIMENSION), y: 0 ), animated: true) } //MARK: - UIScrollViewDelegate func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { self.centerCurrentView() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.centerCurrentView() } } // The class keyword in the Swift protocol definition limits protocol adoption to class types // (and not structures or enums). This is important if we want to use a weak reference to the delegate. protocol HorizontalScrollerDelegate: class { // ask the delegate how many views he wants to present inside the horizontal scroller func numberOfViews(in horizontalScroller: HorizontalScroller) -> Int // ask the delegate to return the view that should appear at <index> func horizontalScroller(_ horizontalScroller: HorizontalScroller, viewAt index: Int) -> UIView // inform the delegate what the view at <index> has been clicked func horizontalScroller(_ horizontalScroller: HorizontalScroller, didSelectViewAt index: Int) // ask the delegate for the index of the initial view to display, defaults to 0 func initialViewIndex(in horizontalScroller: HorizontalScroller) -> Int }
9617d65ae34478b93f23de03825774ff
30.244048
122
0.733854
false
false
false
false
ALHariPrasad/BluetoothKit
refs/heads/develop
Carthage/Checkouts/CryptoSwift/CryptoSwift/Utils.swift
apache-2.0
20
// // Utils.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 26/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation func rotateLeft(v:UInt8, n:UInt8) -> UInt8 { return ((v << n) & 0xFF) | (v >> (8 - n)) } func rotateLeft(v:UInt16, n:UInt16) -> UInt16 { return ((v << n) & 0xFFFF) | (v >> (16 - n)) } func rotateLeft(v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } func rotateLeft(x:UInt64, n:UInt64) -> UInt64 { return (x << n) | (x >> (64 - n)) } func rotateRight(x:UInt16, n:UInt16) -> UInt16 { return (x >> n) | (x << (16 - n)) } func rotateRight(x:UInt32, n:UInt32) -> UInt32 { return (x >> n) | (x << (32 - n)) } func rotateRight(x:UInt64, n:UInt64) -> UInt64 { return ((x >> n) | (x << (64 - n))) } func reverseBytes(value: UInt32) -> UInt32 { return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24); } func xor(a: [UInt8], b:[UInt8]) -> [UInt8] { var xored = [UInt8](count: a.count, repeatedValue: 0) for i in 0..<xored.count { xored[i] = a[i] ^ b[i] } return xored } func perf(text: String, closure: () -> ()) { let measurementStart = NSDate(); closure() let measurementStop = NSDate(); let executionTime = measurementStop.timeIntervalSinceDate(measurementStart) print("\(text) \(executionTime)"); }
518fe8553ce2ddaf7f30060163257691
23.55
132
0.569293
false
false
false
false
alblue/swift
refs/heads/master
test/SILOptimizer/definite_init_objc_factory_init.swift
apache-2.0
6
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-sil -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import Foundation import ImportAsMember.Class // CHECK-LABEL: sil shared [serializable] [thunk] @$sSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive> func testInstanceTypeFactoryMethod(queen: Bee) { // CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type): // CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: release_value [[QUEEN]] // CHECK-NEXT: return [[HIVE]] : $Optional<Hive> var hive1 = Hive(queen: queen) } extension Hive { // CHECK-LABEL: sil hidden @$sSo4HiveC027definite_init_objc_factory_C0E10otherQueenABSo3BeeC_tcfC convenience init(otherQueen other: Bee) { // CHECK: bb0({{.*}}, [[META:%.*]] : $@thick Hive.Type) // CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]] // CHECK: dealloc_stack [[SELF_ADDR]] // CHECK: return [[NEW_SELF]] self.init(queen: other) } convenience init(otherFlakyQueen other: Bee) throws { try self.init(flakyQueen: other) } } extension SomeClass { // SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_ // SIL: bb0([[DOUBLE:%[0-9]+]] : $Double // SIL-NOT: value_metatype // SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // SIL: apply [[FNREF]]([[DOUBLE]]) convenience init(double: Double) { self.init(value: double) } } class SubHive : Hive { // CHECK-LABEL: sil hidden @$s027definite_init_objc_factory_B07SubHiveC20delegatesToInheritedACyt_tcfC convenience init(delegatesToInherited: ()) { // CHECK: bb0([[METATYPE:%.*]] : $@thick SubHive.Type) // CHECK: [[UPMETA:%.*]] = upcast [[METATYPE]] // CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[UPMETA]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK: [[METHOD:%.*]] = objc_method [[OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive? // CHECK: apply [[METHOD]]({{.*}}, [[OBJC]]) // CHECK: return {{%.*}} : $SubHive self.init(queen: Bee()) } }
2d4c26ce53de1d3663a0d3044b252636
54.163934
265
0.641605
false
false
false
false
wwu-pi/md2-framework
refs/heads/master
de.wwu.md2.framework/res/resources/ios/lib/workflow/MD2WorkflowManager.swift
apache-2.0
1
// // MD2WorkflowManager.swift // md2-ios-library // // Created by Christoph Rieger on 14.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /// The object managing the workflow process. class MD2WorkflowManager { /// The singleton instance static let instance: MD2WorkflowManager = MD2WorkflowManager() /// The current workflow element var currentWorkflowElement: MD2WorkflowElement? /// List of startable workflow elements to present on start screeen var startableWorkflowElements: Dictionary<MD2WidgetMapping, (String, MD2WorkflowElement)> = [:] /// Start screen view to fill with elements var startScreen: MD2ViewController? /// Singleton initializer private init() { // Private initializer for singleton object } /** Add startable workflow element. :param: workflowElement The startable workflow element */ func addStartableWorkflowElement(workflowElement: MD2WorkflowElement, withCaption: String, forWidget: MD2WidgetMapping) { startableWorkflowElements[forWidget] = (withCaption, workflowElement) } /** Switch to another workflow element. The currently running workflow element (if existing) is properly ended beforehand. :param workflowElement The workflow element to start. */ func goToWorkflow(workflowElement: MD2WorkflowElement) { println("[WorkflowManager] Switch workflow into '\(workflowElement.name)'") if let _ = currentWorkflowElement { currentWorkflowElement!.end() } currentWorkflowElement = workflowElement currentWorkflowElement!.start() } /** End the workflow element. To continue the app flow, the start view is invoked for a new workflow selection. :param workflowElement The workflow element to end. */ func endWorkflow(workflowElement: MD2WorkflowElement) { println("[WorkflowManager] End workflow '\(workflowElement.name)'") workflowElement.end() currentWorkflowElement = nil // Go back to startup screen MD2ViewManager.instance.goToStartView() } /** Generate a view with buttons for all startable workflow elements that is shown on startup */ func generateStartScreen() { let outerLayout = MD2FlowLayoutPane(widgetId: MD2WidgetMapping.__startScreen) outerLayout.orientation = MD2FlowLayoutPane.Orientation.Vertical // Add initial Label let label = MD2LabelWidget(widgetId: MD2WidgetMapping.__startScreen_Label) label.value = MD2String("Select workflow to start") label.fontSize = MD2Float(2.0) label.widgetElement.textAlignment = .Center label.color = MD2String("#000000") label.textStyle = MD2WidgetTextStyle.Bold outerLayout.addWidget(label) MD2WidgetRegistry.instance.add(MD2WidgetWrapper(widget: label)) outerLayout.addWidget(MD2SpacerWidget(widgetId: MD2WidgetMapping.Spacer)) // Add buttons for each startable workflow for (widget, (caption, wfe)) in startableWorkflowElements { let button = MD2ButtonWidget(widgetId: widget) button.value = MD2String(caption) outerLayout.addWidget(button) let buttonWrapper = MD2WidgetWrapper(widget: button) MD2WidgetRegistry.instance.add(buttonWrapper) // Link button click to workflow action MD2OnClickHandler.instance.registerAction(MD2SetWorkflowElementAction(actionSignature: "__startScreen_" + wfe.name, workflowElement: wfe), widget: buttonWrapper) } startScreen = MD2ViewManager.instance.setupView("__startScreen", view: outerLayout) MD2ViewManager.instance.showStartView("__startScreen") } /** Recreate the start screen view with all startable workflow elements */ func updateStartScreen() { // MARK Update existing view when remote workflow handling is implemented (currently there is no change) } }
54a3c57ab51f756efb2d55a685983ca9
36.9
173
0.675941
false
false
false
false