repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Masteryyz/CSYMicroBlockSina
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/ComposePage(发布微博界面)/CSYPictureSeletedViewController.swift
1
6628
// // CSYPictureSeletedViewController.swift // CSYMicroBlockSina // // Created by 姚彦兆 on 15/11/19. // Copyright © 2015年 姚彦兆. All rights reserved. // import UIKit private let pictureWidth : CGFloat = (screen_Width - 5 * cellMargin) / 4 private let maxImageCount : NSInteger = 4 private let reuseIdentifier = "Cell" class CSYPictureSeletedViewController: UICollectionViewController { //设置数据源数组 lazy var pictureBox : [UIImage] = [UIImage]() init(){ let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = cellMargin layout.minimumLineSpacing = cellMargin layout.itemSize = CGSizeMake(pictureWidth, pictureWidth) layout.sectionInset = UIEdgeInsetsMake(cellMargin, cellMargin, 0, cellMargin) super.init(collectionViewLayout: layout) } private func caculateItemSize() -> CGSize{ let width : CGFloat = (screen_Width - 5 * cellMargin) / 4 return CGSizeMake(width, width) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.registerClass(CSYPictureSeletedCell.self, forCellWithReuseIdentifier: reuseIdentifier) self.collectionView?.backgroundColor = UIColor(white: 0.85, alpha: 1) // Do any additional setup after loading the view. } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items let flag = (pictureBox.count == maxImageCount) ? 0 : 1 return pictureBox.count + flag } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CSYPictureSeletedCell cell.delegate = self cell.backgroundColor = UIColor(white: 0.97, alpha: 1) if indexPath.item == pictureBox.count{ cell.image = nil }else{ cell.image = pictureBox[indexPath.item] } return cell } } extension CSYPictureSeletedViewController : CSYPictureSeletedCellDelegate{ func clickAddBtn(targetCell: CSYPictureSeletedCell) { if targetCell.image != nil{ print("已经有图片") return } print("++点击了添加图片按钮++") //添加图片需要使用系统的图片选择器 let picturePick = UIImagePickerController() picturePick.delegate = self picturePick.allowsEditing = true presentViewController(picturePick, animated: true, completion: nil) } func clickDeleteBtn(targetCell: CSYPictureSeletedCell) { print("--点击了删除图片按钮--") let indexPath : NSIndexPath = (collectionView?.indexPathForCell(targetCell))! pictureBox.removeAtIndex(indexPath.item) UIView.animateWithDuration(0.75, animations: { () -> Void in targetCell.alpha = 0 }) { (_) -> Void in targetCell.alpha = 1 self.collectionView?.reloadData() } } } extension CSYPictureSeletedViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{ func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { pictureBox.append(image) collectionView?.reloadData() dismissViewControllerAnimated(true, completion: nil) } } @objc protocol CSYPictureSeletedCellDelegate : NSObjectProtocol{ optional func clickAddBtn( targetCell : CSYPictureSeletedCell ) optional func clickDeleteBtn( targetCell : CSYPictureSeletedCell ) } class CSYPictureSeletedCell : UICollectionViewCell{ var image : UIImage? { didSet{ delete_Btn.hidden = (image == nil) if image != nil { add_Btn.setBackgroundImage(image, forState: UIControlState.Normal) }else{ add_Btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal) } } } weak var delegate : CSYPictureSeletedCellDelegate? @objc private func clickAddButton(){ delegate?.clickAddBtn!(self) } @objc private func clickDeleteButton(){ delegate?.clickDeleteBtn!(self) } override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpUI(){ contentView.addSubview(add_Btn) contentView.addSubview(delete_Btn) add_Btn.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.snp_edges) } delete_Btn.snp_makeConstraints { (make) -> Void in make.top.equalTo(add_Btn.snp_top) make.right.equalTo(add_Btn.snp_right) } add_Btn.addTarget(self, action: "clickAddButton", forControlEvents: UIControlEvents.TouchUpInside) delete_Btn.addTarget(self, action: "clickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside) } lazy var add_Btn = UIButton(title: "", titleColor: UIColor(white: 0.95, alpha: 1), image: "", backImage: "compose_pic_add", fontSize: 0) lazy var delete_Btn = UIButton(title: "", titleColor: nil, image: "", backImage: "compose_photo_close", fontSize: 0) }
mit
6e22a35a619e47eed6521e358a6a5181
23.241636
140
0.593774
5.353859
false
false
false
false
paulemmanuel-garcia/Meteo
Meteo/Current Weather/CurrentWeatherViewController.swift
1
1574
// // CurrentViewController.swift // Meteo // // Created by Paul-Emmanuel on 09/01/17. // Copyright © 2017 rstudio. All rights reserved. // import UIKit import ImageLoader public class CurrentWeatherViewController: UIViewController, UIWeatherElement { public var city: String = "" private var _currentWeather: CurrentWeather? private var currentWeather: CurrentWeather? { set { _currentWeather = newValue guard let weather = newValue else { return } tempLabel.text = "\(weather.temp)" conditionLabel.text = weather.conditions.first?.description iconImageView.load(with: iconBaseUrl + (weather.conditions.first?.icon ?? "01d") + ".png") } get { return _currentWeather } } @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var conditionLabel: UILabel! @IBOutlet weak var tempLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! override public func viewDidLoad() { super.viewDidLoad() cityLabel.text = city // Do any additional setup after loading the view. Weather.api.getCurrentWeather(for: city) { currentWeather, error in self.currentWeather = currentWeather } } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
62d86dab99690b175ba4f81e64c9dba8
26.12069
102
0.600127
5.243333
false
false
false
false
flockoffiles/FFDataWrapper
FFDataWrapper/FFDataWrapperEncoders.swift
1
5034
// // FFDataWrapperEncoders.swift // FFDataWrapper // // Created by Sergey Novitsky on 26/09/2017. // Copyright © 2017 Flock of Files. All rights reserved. // import Foundation /// Enumeration defining some basic coders (transformers) public enum FFDataWrapperEncoders { /// Do not transform. Just copy. case identity /// XOR with the random vector of the given legth. case xorWithRandomVectorOfLength(Int) /// XOR with the given vector case xor(Data) public var coders: FFDataWrapper.Coders { switch self { case .identity: return (encoder: FFDataWrapperEncoders.identityFunction(), decoder: FFDataWrapperEncoders.identityFunction()) case .xorWithRandomVectorOfLength(let length): var vector = Data(count: length) let _ = vector.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, length, $0) } return (encoder: FFDataWrapperEncoders.xorWithVector(vector), decoder: FFDataWrapperEncoders.xorWithVector(vector)) case .xor(let vector): return (encoder: FFDataWrapperEncoders.xorWithVector(vector), decoder: FFDataWrapperEncoders.xorWithVector(vector)) } } public var infoCoders: FFDataWrapper.InfoCoders { switch self { case .identity: return (encoder: FFDataWrapperEncoders.infoIdentityFunction(), decoder: FFDataWrapperEncoders.infoIdentityFunction()) case .xorWithRandomVectorOfLength(let length): var vector = Data(count: length) let _ = vector.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, length, $0) } return (encoder: FFDataWrapperEncoders.infoXorWithVector(vector), decoder: FFDataWrapperEncoders.infoXorWithVector(vector)) case .xor(let vector): return (encoder: FFDataWrapperEncoders.infoXorWithVector(vector), decoder: FFDataWrapperEncoders.infoXorWithVector(vector)) } } public static func xorWithVector(_ vector: Data) -> FFDataWrapper.Coder { return { (src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>) in xor(src: src, dest: dest, with: vector) } } public static func infoXorWithVector(_ vector: Data) -> FFDataWrapper.InfoCoder { return { (src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>, info: Any?) in xor(src: src, dest: dest, with: vector) } } public static func identityFunction() -> FFDataWrapper.Coder { return { (src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>) in justCopy(src: src, dest: dest) } } public static func infoIdentityFunction() -> FFDataWrapper.InfoCoder { return { (src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>, info: Any?) in justCopy(src: src, dest: dest) } } } public extension FFDataWrapperEncoders { /// Simple identity transformation. /// /// - Parameters: /// - src: Source data to transform. /// - srcLength: Length of the source data. /// - dest: Destination data buffer. Will be cleared before transformation takes place. static func justCopy(src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>) { // Wipe contents if needed. if (dest.count > 0) { dest.baseAddress!.initialize(repeating: 0, count: dest.count) } guard src.count > 0 && dest.count >= src.count else { return } dest.baseAddress!.assign(from: src.baseAddress!, count: src.count) } /// Sample transformation for custom content. XORs the source representation (byte by byte) with the given vector. /// /// - Parameters: /// - src: Source data to transform. /// - dest: Destination data buffer. Will be cleared before transformation takes place. /// - with: Vector to XOR with. If the vector is shorter than the original data, it will be wrapped around. static func xor(src: UnsafeBufferPointer<UInt8>, dest: UnsafeMutableBufferPointer<UInt8>, with: Data) { // Initialize contents if (dest.count > 0) { dest.baseAddress!.initialize(repeating: 0, count: dest.count) } guard src.count > 0 && dest.count >= src.count else { return } var j = 0 for i in 0 ..< dest.count { let srcByte: UInt8 = i < src.count ? src[i] : 0 dest[i] = srcByte ^ with[j] j += 1 if j >= with.count { j = 0 } } } } public extension Array where Element == UInt8 { func coders(_ coder: (Data) -> FFDataWrapper.Coder) -> (FFDataWrapper.Coder, FFDataWrapper.Coder) { let data = Data(bytes: self) return (coder(data), coder(data)) } }
mit
19aadd60383582b887746219f0922c8c
37.715385
135
0.629048
4.621671
false
false
false
false
brentdax/swift
test/SILGen/same_type_abstraction.swift
2
2504
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol Associated { associatedtype Assoc } struct Abstracted<T: Associated, U: Associated> { let closure: (T.Assoc) -> U.Assoc } struct S1 {} struct S2 {} // CHECK-LABEL: sil hidden @$s21same_type_abstraction28callClosureWithConcreteTypes{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s{{.*}}TR : func callClosureWithConcreteTypes<T: Associated, U: Associated>(x: Abstracted<T, U>, arg: S1) -> S2 where T.Assoc == S1, U.Assoc == S2 { return x.closure(arg) } // Problem when a same-type constraint makes an associated type into a tuple protocol MyProtocol { associatedtype ReadData associatedtype Data func readData() -> ReadData } extension MyProtocol where Data == (ReadData, ReadData) { // CHECK-LABEL: sil hidden @$s21same_type_abstraction10MyProtocolPAA8ReadDataQz_AEt0G0RtzrlE07currentG0AE_AEtyF : $@convention(method) <Self where Self : MyProtocol, Self.Data == (Self.ReadData, Self.ReadData)> (@in_guaranteed Self) -> (@out Self.ReadData, @out Self.ReadData) func currentData() -> Data { // CHECK: bb0(%0 : @trivial $*Self.ReadData, %1 : @trivial $*Self.ReadData, %2 : @trivial $*Self): // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%0, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%1, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: return return (readData(), readData()) } } // Problem with protocol typealiases, which are modeled as same-type // constraints protocol Refined : Associated { associatedtype Key typealias Assoc = Key init() } extension Refined { // CHECK-LABEL: sil hidden @$s21same_type_abstraction7RefinedPAAE12withElementsx5AssocQz_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self init(withElements newElements: Key) { self.init() } }
apache-2.0
e65a413c9b59205db88647bf818e913d
42.649123
278
0.676849
3.295364
false
false
false
false
xiekw2010/iOS7PlayGround
Vendor/LineFlowLayout.swift
1
2406
// // LineFlowLayout.swift // UICategories // // Created by xiekw on 1/27/15. // Copyright (c) 2015 xiekw. All rights reserved. // import UIKit class LineFlowLayout: UICollectionViewFlowLayout { let cellItemSize: CGSize = CGSizeMake(80.0, 80.0) let activeDistance: CGFloat = 200.0 let zoomFactor: CGFloat = 0.4 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() itemSize = cellItemSize scrollDirection = UICollectionViewScrollDirection.Horizontal sectionInset = UIEdgeInsetsMake(100.0, 0.0, 0.0, 100.0) minimumLineSpacing = 35.0 } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let superAttributes = super.layoutAttributesForElementsInRect(rect) as [UICollectionViewLayoutAttributes] let visibleBounds = collectionView?.bounds for atr in superAttributes { if CGRectIntersectsRect(atr.frame, rect) { let distance = CGRectGetMidX(atr.frame) - CGRectGetMidX(visibleBounds!) let normlizedDistance = abs(distance / activeDistance) if abs(distance) < activeDistance { let zoom = 1 + zoomFactor * (1.0 - normlizedDistance) atr.transform3D = CATransform3DMakeScale(zoom, zoom, 1.0) } } } return superAttributes } override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var adjust: CGFloat = CGFloat.max let midx = proposedContentOffset.x + (CGRectGetWidth(collectionView!.bounds) / 2.0) let targetRect = CGRect(origin: CGPointMake(proposedContentOffset.x, 0.0), size: collectionView!.bounds.size) let atrsInTarget = super.layoutAttributesForElementsInRect(targetRect) as [UICollectionViewLayoutAttributes] for atr in atrsInTarget { let atrCenter = atr.center.x if (abs(atrCenter - midx) < abs(adjust)) { adjust = atrCenter - midx } } return CGPoint(x: (proposedContentOffset.x + round(adjust)), y: proposedContentOffset.y) } }
mit
816b4c0ce5bad86d67289faca0a2ecdb
37.806452
147
0.650873
4.792829
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/minimum-number-of-refueling-stops.swift
1
943
/** * https://leetcode.com/problems/minimum-number-of-refueling-stops/ * * */ // Date: Wed Mar 30 22:13:01 PDT 2022 class Solution { /// - Complexity: /// - Time: O(n), n = stations.count /// - Space: O(n), n = stations.count func minRefuelStops(_ target: Int, _ startFuel: Int, _ stations: [[Int]]) -> Int { let n = stations.count // dp[x]: Farthest distance could be reached by using x stations. var dp = Array(repeating: 0, count: n + 1) dp[0] = startFuel for index in 0 ..< n { for last in stride(from: index, through: 0, by: -1) { if dp[last] >= stations[index][0] { dp[last + 1] = max(dp[last + 1], dp[last] + stations[index][1]) } } } for index in 0 ... n { if dp[index] >= target { return index } } return -1 } }
mit
be888616d9f918c7d3da7d13a94f3f63
30.466667
86
0.478261
3.57197
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/Utility/WebNavigationDelegate.swift
1
1049
import Foundation import WebKit // This is an odd design, but it needs to work on Objective-C // Since Swift now allows ommiting the type in static functions, it will // look like an enum on the delegate implementations: // // func shouldNavigate(request: URLRequest) -> WebNavigationPolicy { // return .allow // return .cancel // return .redirect(request) // } class WebNavigationPolicy: NSObject { private(set) var redirectRequest: URLRequest? private(set) var action: WKNavigationActionPolicy = .cancel private override init() {} static let allow: WebNavigationPolicy = { let policy = WebNavigationPolicy() policy.action = .allow return policy }() static let cancel = WebNavigationPolicy() static func redirect(_ request: URLRequest) -> WebNavigationPolicy { let policy = WebNavigationPolicy() policy.redirectRequest = request return policy } } @objc protocol WebNavigationDelegate { func shouldNavigate(request: URLRequest) -> WebNavigationPolicy }
gpl-2.0
85efeceefb3be7d6ab77ec5f31a994da
27.351351
72
0.706387
4.621145
false
false
false
false
kumabook/MusicFav
MusicFav/SpotifyPlayer.swift
1
3632
// // SpotifyPlayer.swift // MusicFav // // Created by Hiroki Kumamoto on 2017/03/11. // Copyright © 2017 Hiroki Kumamoto. All rights reserved. // import Foundation import MediaPlayer import PlayerKit import Spotify class SpotifyPlayer: PlayerKit.SpotifyPlayer, SPTAudioStreamingPlaybackDelegate { public fileprivate(set) var streamingController: SPTAudioStreamingController override init() { streamingController = SPTAudioStreamingController.sharedInstance() super.init() } @objc func updateTime() { notify(.timeUpdated) } // MARK: SPTAudioStreamingPlaybackDelegate func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChangePlaybackStatus isPlaying: Bool) { if state == .play && !isPlaying { state = .pause } } func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChangePosition position: TimeInterval) { switch state { case .loadToPlay: state = .play default: break } notify(.timeUpdated) } func audioStreamingDidPopQueue(_ audioStreaming: SPTAudioStreamingController!) { notify(.didPlayToEndTime) } // MARK: QueuePlayer protocol override var playerType: PlayerType { return PlayerType.appleMusic } override var playingInfo: PlayingInfo? { if let track = streamingController.metadata?.currentTrack { return PlayingInfo(duration: track.duration, elapsedTime: streamingController.playbackState?.position ?? 0.0) } return nil } override func seekToTime(_ time: TimeInterval) { if !streamingController.loggedIn { return } streamingController.seek(to: time) { e in if let e = e { print("spotify seek error \(e)") return } self.notify(.timeUpdated) } } open func keepPlaying() { if state.isPlaying { play() } } override func play() { if !streamingController.loggedIn { return } state = .loadToPlay streamingController.setIsPlaying(true) { e in if let e = e { print("spotify setIsPlaying error \(e)") return } } } open override func pause() { if !streamingController.loggedIn { return } state = .load streamingController.setIsPlaying(false) { e in self.state = .pause if let e = e { print("spotify setIsPlaying error \(e)") return } } } override func clearPlayer() { if !streamingController.loggedIn { return } streamingController.setIsPlaying(false) { e in } streamingController.playbackDelegate = nil } override func preparePlayer() { if !streamingController.loggedIn { return } guard let track = track, let uri = track.spotifyURI, track.isValid else { return } streamingController.playbackDelegate = self streamingController.seek(to: 0.0) { e in } streamingController.playSpotifyURI(uri, startingWith: 0, startingWithPosition: 0) { e in switch self.state { case .loadToPlay, .play: self.streamingController.setIsPlaying(true) {e in } default: self.streamingController.setIsPlaying(false) {e in } } if let e = e { print("Failed to play uri \(uri): \(e)") return } } } }
mit
c17478a1a7ac9751ded28e1339cba2cb
29.008264
115
0.596254
4.946866
false
false
false
false
kokuyoku82/NumSwift
NumSwift/Source/Utilities.swift
1
15912
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered // import Accelerate import Foundation /** Compute Norm of 2D Vectors (Elementwise). - Parameters: - x: array of x-axis coordinates. - y: array of y-axis coordinates. - Returns: array of norm of each vector, (x_i, y_i), where x_i and y_i are the i-th element of x and y, respectively. */ public func norm(x:[Double], _ y:[Double]) -> [Double]{ var inputX = [Double](x) var inputY = [Double](y) var xSquare = [Double](count:x.count, repeatedValue:0.0) var ySquare = [Double](count:y.count, repeatedValue:0.0) vDSP_vsqD(&inputX, 1, &xSquare, 1, vDSP_Length(x.count)) vDSP_vsqD(&inputY, 1, &ySquare, 1, vDSP_Length(y.count)) var squareSum = [Double](count:x.count, repeatedValue:0.0) vDSP_vaddD(&xSquare, 1, &ySquare, 1, &squareSum, 1, vDSP_Length(x.count)) var N = Int32(squareSum.count) var vectorNorm = [Double](count:squareSum.count, repeatedValue:0.0) vvsqrt(&vectorNorm, &squareSum, &N) return vectorNorm } /** Compute Norm of 2D Vectors (Elementwise). - Parameters: - x: array of x-axis coordinates. - y: array of y-axis coordinates. - Returns: array of norm of each vector, (x_i, y_i), where x_i and y_i are the i-th element of x and y, respectively. */ public func norm(x:[Float], _ y:[Float]) -> [Float]{ var inputX = [Float](x) var inputY = [Float](y) var xSquare = [Float](count:x.count, repeatedValue:0.0) var ySquare = [Float](count:y.count, repeatedValue:0.0) vDSP_vsq(&inputX, 1, &xSquare, 1, vDSP_Length(x.count)) vDSP_vsq(&inputY, 1, &ySquare, 1, vDSP_Length(y.count)) var squareSum = [Float](count:x.count, repeatedValue:0.0) vDSP_vadd(&xSquare, 1, &ySquare, 1, &squareSum, 1, vDSP_Length(x.count)) var N = Int32(squareSum.count) var vectorNorm = [Float](count:squareSum.count, repeatedValue:0.0) vvsqrtf(&vectorNorm, &squareSum, &N) return vectorNorm } /** Rounding toward Zero (Elementwise). - Parameters: - x: array to be rounded. - Returns: array of elements in x rounding toward zero. #### Example ``` let x:[Double] = [1.1, 2.5, -1.2] roundToZero(x) // [1, 2, -1] ``` */ public func roundToZero(x:[Double]) -> [Double]{ var input = [Double](x) var fracPart = [Double](count:x.count, repeatedValue:0.0) vDSP_vfracD(&input, 1, &fracPart, 1, vDSP_Length(x.count)) var result = [Double](count:x.count, repeatedValue:0.0) vDSP_vsubD(&fracPart, 1, &input, 1, &result, 1, vDSP_Length(x.count)) return result } /** Rounding toward Zero (Elementwise). - Parameters: - x: array to be rounded. - Returns: array of elements in x rounding toward zero. #### Example ``` let x:[Float] = [1.1, 2.5, -1.2] roundToZero(x) // [1, 2, -1] ``` */ public func roundToZero(x:[Float]) -> [Float]{ var input = [Float](x) var fracPart = [Float](count:x.count, repeatedValue:0.0) vDSP_vfrac(&input, 1, &fracPart, 1, vDSP_Length(x.count)) var result = [Float](count:x.count, repeatedValue:0.0) vDSP_vsub(&fracPart, 1, &input, 1, &result, 1, vDSP_Length(x.count)) return result } /** Evenly spaced values with a given start value. - Parameters: - N: output length - start: starting value (default 0). - step: step size between values. - Returns: A double precision array of sequential values starting at `start` with even step size. */ public func arange(N:Int, start:Double = 0, step:Double) -> [Double]{ var start = start var step = Double(step) var result = [Double](count:N, repeatedValue:0.0) vDSP_vrampD(&start, &step, &result, 1, vDSP_Length(N)) return result } /** Evenly spaced values with a given start value. - Parameters: - N: output length - start: starting value (default 0). - step: step size between values. - Returns: A single precision array of sequential values starting at `start` with even step size. */ public func arange(N:Int, start:Float = 0, step:Float) -> [Float] { var start = start var step = step var result = [Float](count:N, repeatedValue:0.0) vDSP_vramp(&start, &step, &result, 1, vDSP_Length(N)) return result } /** Return evenly spaced numbers over a specified interval. - Parameters: - start: the value where the interval starts. - end: the value where the interval ends. - num: number of samples to be generated. - Returns: An double precision array of `num` many equally spaced samples. */ public func linspace(start:Double, _ end:Double, num:Int = 100) -> [Double]{ precondition(start <= end, "start must be no larger than end.") var startDouble = Double(start) var endDouble = Double(end) var result = [Double](count:num, repeatedValue:0.0) vDSP_vgenD(&startDouble, &endDouble, &result, 1, vDSP_Length(num)) return result } /** Return evenly spaced numbers over a specified interval. - Parameters: - start: the value where the interval starts. - end: the value where the interval ends. - num: number of samples to be generated. - Returns: An single precision array of `num` many equally spaced samples. */ public func linspace(start:Float, _ end:Float, num:Int = 100) -> [Float]{ precondition(start <= end, "start must be no larger than end.") var startFloat = Float(start) var endFloat = Float(end) var result = [Float](count:num, repeatedValue:0.0) vDSP_vgen(&startFloat, &endFloat, &result, 1, vDSP_Length(num)) return result } /** Compute the arithmetic mean - Parameters: - x: array of data - Returns: the mean of elements in x. */ public func mean(x:[Double]) -> Double { var value:Double = 0.0 vDSP_meanvD(x, 1, &value, vDSP_Length(x.count)) return value } /** Compute the arithmetic mean - Parameters: - x: array of data - Returns: the mean of elements in x. */ public func mean(x:[Float]) -> Float { var value:Float = 0.0 vDSP_meanv(x, 1, &value, vDSP_Length(x.count)) return value } /** Compute the variance - Note: variance = mean(abs(x - mean_x)^2) - Parameters: - x: array of data - Returns: the variance of elements in x. */ public func variance(x:[Double]) -> Double { let N = vDSP_Length(x.count) var output_buffer = [Double](count:x.count, repeatedValue:0.0) var neg_mean_x = -mean(x) vDSP_vsaddD(x, 1, &neg_mean_x, &output_buffer, 1, N) vDSP_vsqD(&output_buffer, 1, &output_buffer, 1, N) let result = output_buffer.reduce(0, combine:{$0 + $1}) return result/Double(x.count) } /** Compute the variance - Note: variance = mean(abs(x - mean_x)^2) - Parameters: - x: array of data - Returns: the variance of elements in x. */ public func variance(x:[Float]) -> Float { let N = vDSP_Length(x.count) var output_buffer = [Float](count:x.count, repeatedValue:0.0) var neg_mean_x = -mean(x) vDSP_vsadd(x, 1, &neg_mean_x, &output_buffer, 1, N) vDSP_vsq(&output_buffer, 1, &output_buffer, 1, N) let result = output_buffer.reduce(0, combine:{$0 + $1}) return result/Float(x.count) } /** Compute the standard deviation - Note: std = sqrt(variance(x)) - Parameters: - x: the input data. - Returns: The standard deviation of x. */ public func std(x:[Double]) -> Double { return sqrt(variance(x)) } /** Compute the standard deviation - Note: std = sqrt(variance(x)) - Parameters: - x: the input data. - Returns: The standard deviation of x. */ public func std(x:[Float]) -> Float { return sqrt(variance(x)) } /** Data normalization Normalize data to zero mean and unit standard deviation. - Parameters: - x: array of input data. - Returns: Normalized data which has zero mean and unit standard deviation. */ public func normalize(x:[Double]) -> [Double] { var mean_x = mean(x) var std_x = std(x) var x_normalized = [Double](count:x.count, repeatedValue:0.0) vDSP_normalizeD(x, 1, &x_normalized, 1, &mean_x, &std_x, vDSP_Length(x.count)) return x_normalized } /** Data normalization Normalize data to zero mean and unit standard deviation. - Parameters: - x: array of input data. - Returns: Normalized data which has zero mean and unit standard deviation. */ public func normalize(x:[Float]) -> [Float]{ var mean_x = mean(x) var std_x = std(x) var x_normalized = [Float](count:x.count, repeatedValue:0.0) vDSP_normalize(x, 1, &x_normalized, 1, &mean_x, &std_x, vDSP_Length(x.count)) return x_normalized } /** Split array into smaller subarrays. - Parameters: - x: the input array. - numberOfParts: number of splits. - Returns: array of array of each split. #### Example ``` let arr:[Double] = (1...6).map {Double($0)} splitArrayIntoParts(arr, 3) /// [[1, 2], [3, 4], [5, 6]] ``` */ public func splitArrayIntoParts(x:[Double], _ numberOfParts: Int) -> [[Double]] { var parts = [[Double]]() let input = [Double](x) let samplesPerSplit = Int(round(Double(x.count)/Double(numberOfParts))) var startIndex:Int var endIndex:Int var slice:ArraySlice<Double> for i in 1..<numberOfParts { startIndex = (i-1)*samplesPerSplit endIndex = i*samplesPerSplit slice = input[startIndex..<endIndex] parts.append([Double](slice)) } startIndex = (numberOfParts-1)*samplesPerSplit endIndex = x.count slice = input[startIndex..<endIndex] parts.append([Double](slice)) return parts } /** Split array into smaller subarrays. - Parameters: - x: the input array. - numberOfParts: number of splits. - Returns: array of array of each split. #### Example ``` let arr:[Double] = (1...6).map {Double($0)} splitArrayIntoParts(arr, 3) /// [[1, 2], [3, 4], [5, 6]] ``` */ public func splitArrayIntoParts(x:[Float], _ numberOfParts: Int) -> [[Float]] { var parts = [[Float]]() let input = [Float](x) let samplesPerSplit = Int(round(Double(x.count)/Double(numberOfParts))) var startIndex:Int var endIndex:Int var slice:ArraySlice<Float> for i in 1..<numberOfParts { startIndex = (i-1)*samplesPerSplit endIndex = i*samplesPerSplit slice = input[startIndex..<endIndex] parts.append([Float](slice)) } startIndex = (numberOfParts-1)*samplesPerSplit endIndex = x.count slice = input[startIndex..<endIndex] parts.append([Float](slice)) return parts } /** Find the least power of 2. Returns the least power of 2 greater than `N`. - Parameters: - N: the lower bound of power of 2. - Returns: the least power of 2 greater than N */ public func leastPowerOfTwo(N:Int) -> Int { /* Find the least power of two greater than `N`. */ let log2N = Int(log2(Double(N))) var NPowTwo = 1 << log2N if NPowTwo < N { NPowTwo = NPowTwo << 1 } return NPowTwo } /** Find the least power of 2. Returns the least power of 2 greater than `N`. - Parameters: - N: the lower bound of power of 2. - Returns: the least power of 2 greater than N */ public func leastPowerOfTwo(N:Double) -> Double { let log2N = Int(log2(N)) var NPowTwo = 1 << log2N if Double(NPowTwo) < N { NPowTwo = NPowTwo << 1 } return Double(NPowTwo) } /** Find the least power of 2. Returns the least power of 2 greater than `N`. - Parameters: - N: the lower bound of power of 2. - Returns: the least power of 2 greater than N */ public func leastPowerOfTwo(N:Float) -> Float { let log2N = Int(log2(N)) var NPowTwo = 1 << log2N if Float(NPowTwo) < N { NPowTwo = NPowTwo << 1 } return Float(NPowTwo) } /** Compute absolute value (elementwise). - Parameters: - x: the input data - Returns: an array containing the absolute value of each element in x. */ public func abs(x:[Double]) -> [Double] { var input = [Double](x) var output = [Double](count:x.count, repeatedValue:0.0) vDSP_vabsD(&input, 1, &output, 1, vDSP_Length(x.count)) return output } /** Compute absolute value (elementwise). - Parameters: - x: the input data - Returns: an array containing the absolute value of each element in x. */ public func abs(x:[Float]) -> [Float] { var input = [Float](x) var output = [Float](count:x.count, repeatedValue:0.0) vDSP_vabs(&input, 1, &output, 1, vDSP_Length(x.count)) return output } /** Padding array to specific length - Parameters: - x: the input array. - toLength: target length. - value: the number to be padded (default 0.0). - Returns: the padded array. #### Example ``` let x:[Double] = [1, 2, 3] pad(x, toLength:5) /// [1.0, 2.0, 3.0, 0.0, 0.0] ``` */ public func pad(x:[Double], toLength length: Int, value:Double = 0.0) -> [Double] { let result:[Double] if length <= x.count { result = [Double](x) } else { result = [Double](x) + [Double](count:length - x.count, repeatedValue:value) } return result } /** Padding array to specific length - Parameters: - x: the input array. - toLength: target length. - value: the number to be padded (default 0.0). - Returns: the padded array. #### Example ``` let x:[Float] = [1, 2, 3] pad(x, toLength:5) /// [1.0, 2.0, 3.0, 0.0, 0.0] ``` */ public func pad(x:[Float], toLength length: Int, value:Float = 0.0) -> [Float] { let result:[Float] if length <= x.count { result = [Float](x) } else { result = [Float](x) + [Float](count:length - x.count, repeatedValue:value) } return result } /** Return true if two arrays are equal with tolerance. - Parameters: - x: input array. - y: input array. - tol: tolerance. - Returns: true if two array are equal with tolerance, false otherwise. */ public func allClose(x:[Double], y:[Double], tol:Double = 3e-7) -> Bool { var inputX = [Double](x) var inputY = [Double](y) var isClosed = false if x.count == y.count { let N = x.count var xMinusY = [Double](count:N, repeatedValue:0.0) // Compute x - y (vectorized) vDSP_vsubD(&inputY, 1, &inputX, 1, &xMinusY, 1, vDSP_Length(N)) // Take abs value vDSP_vabsD(&xMinusY, 1, &xMinusY, 1, vDSP_Length(N)) var maximum:Double = 0 vDSP_maxvD(&xMinusY, 1, &maximum, vDSP_Length(N)) if maximum <= tol { isClosed = true } } return isClosed } /** Return true if two arrays are equal with tolerance. - Parameters: - x: input array. - y: input array. - tol: tolerance. - Returns: true if two array are equal with tolerance, false otherwise. */ public func allClose(x:[Float], y:[Float], tol:Float = 3e-7) -> Bool { var inputX = [Float](x) var inputY = [Float](y) var isClosed = false if x.count == y.count { let N = x.count var xMinusY = [Float](count:N, repeatedValue:0.0) // Compute x - y (vectorized) vDSP_vsub(&inputY, 1, &inputX, 1, &xMinusY, 1, vDSP_Length(N)) // Take abs value vDSP_vabs(&xMinusY, 1, &xMinusY, 1, vDSP_Length(N)) var maximum:Float = 0 vDSP_maxv(&xMinusY, 1, &maximum, vDSP_Length(N)) if maximum <= tol { isClosed = true } } return isClosed }
mit
fdd4a0c25008dc9be59a5297f900c578
21.162953
121
0.620726
3.321921
false
false
false
false
narner/AudioKit
AudioKit/Common/Internals/AKSettings.swift
1
13622
// // AKSettings.swift // AudioKit // // Created by Stéphane Peter, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Global settings for AudioKit @objc open class AKSettings: NSObject { /// Enum of available buffer lengths /// from Shortest: 2 power 5 samples (32 samples = 0.7 ms @ 44100 kz) /// to Longest: 2 power 12 samples (4096 samples = 92.9 ms @ 44100 Hz) @objc public enum BufferLength: Int { /// Shortest case shortest = 5 /// Very Short case veryShort = 6 /// Short case short = 7 /// Medium case medium = 8 /// Long case long = 9 /// Very Long case veryLong = 10 /// Huge case huge = 11 /// Longest case longest = 12 /// The buffer Length expressed as number of samples public var samplesCount: AVAudioFrameCount { return AVAudioFrameCount(pow(2.0, Double(rawValue))) } /// The buffer Length expressed as a duration in seconds public var duration: Double { return Double(samplesCount) / AKSettings.sampleRate } } /// The sample rate in Hertz @objc open static var sampleRate: Double = 44_100 /// Number of audio channels: 2 for stereo, 1 for mono @objc open static var numberOfChannels: UInt32 = 2 /// Whether we should be listening to audio input (microphone) @objc open static var audioInputEnabled: Bool = false /// Whether to allow audio playback to override the mute setting @objc open static var playbackWhileMuted: Bool = false /// Global audio format AudioKit will default to @objc open static var audioFormat: AVAudioFormat { return AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: numberOfChannels)! } /// Whether to output to the speaker (rather than receiver) when audio input is enabled @objc open static var defaultToSpeaker: Bool = false /// Whether to use bluetooth when audio input is enabled @objc open static var useBluetooth: Bool = false #if !os(macOS) /// Additional control over the options to use for bluetooth @objc open static var bluetoothOptions: AVAudioSessionCategoryOptions = [] #endif /// Whether AirPlay is enabled when audio input is enabled @objc open static var allowAirPlay: Bool = false /// Global default rampTime value @objc open static var rampTime: Double = 0.000_2 /// Allows AudioKit to send Notifications @objc open static var notificationsEnabled: Bool = false /// AudioKit buffer length is set using AKSettings.BufferLength /// default is .VeryLong for a buffer set to 2 power 10 = 1024 samples (232 ms) @objc open static var bufferLength: BufferLength = .veryLong #if os(macOS) /// The hardware ioBufferDuration. Setting this will request the new value, getting /// will query the hardware. @objc open static var ioBufferDuration: Double { set { let node = AudioKit.engine.outputNode guard let audioUnit = node.audioUnit else { return } let samplerate = node.outputFormat(forBus: 0).sampleRate var frames = UInt32(round( newValue * samplerate )) let status = AudioUnitSetProperty(audioUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &frames, UInt32(MemoryLayout<UInt32>.size)) if status != 0 { print("error in set ioBufferDuration status \(status)") } } get { let node = AudioKit.engine.outputNode guard let audioUnit = node.audioUnit else { return 0 } let sampleRate = node.outputFormat(forBus: 0).sampleRate var frames = UInt32() var propSize = UInt32(MemoryLayout<UInt32>.size) let status = AudioUnitGetProperty(audioUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &frames, &propSize) if status != 0 { print("error in get ioBufferDuration status \(status)") } return Double(frames) / sampleRate } } #else /// The hardware ioBufferDuration. Setting this will request the new value, getting /// will query the hardware. @objc open static var ioBufferDuration: Double { set { do { try AVAudioSession.sharedInstance().setPreferredIOBufferDuration(ioBufferDuration) } catch { print(error) } } get { return AVAudioSession.sharedInstance().ioBufferDuration } } #endif /// AudioKit recording buffer length is set using AKSettings.BufferLength /// default is .VeryLong for a buffer set to 2 power 10 = 1024 samples (232 ms) /// in Apple's doc : "The requested size of the incoming buffers. The implementation may choose another size." /// So setting this value may have no effect (depending on the hardware device ?) @objc open static var recordingBufferLength: BufferLength = .veryLong /// If set to true, Recording will stop after some delay to compensate /// latency between time recording is stopped and time it is written to file /// If set to false (the default value) , stopping record will be immediate, /// even if the last audio frames haven't been recorded to file yet. @objc open static var fixTruncatedRecordings = false /// Enable AudioKit AVAudioSession Category Management @objc open static var disableAVAudioSessionCategoryManagement: Bool = false /// If set to false, AudioKit will not handle the AVAudioSession route change /// notification (AVAudioSessionRouteChange) and will not restart the AVAudioEngine /// instance when such notifications are posted. The developer can instead subscribe /// to these notifications and restart AudioKit after rebuiling their audio chain. @objc open static var enableRouteChangeHandling: Bool = true /// If set to false, AudioKit will not handle the AVAudioSession category change /// notification (AVAudioEngineConfigurationChange) and will not restart the AVAudioEngine /// instance when such notifications are posted. The developer can instead subscribe /// to these notifications and restart AudioKit after rebuiling their audio chain. @objc open static var enableCategoryChangeHandling: Bool = true /// Turn off AudioKit logging @objc open static var enableLogging: Bool = true #if !os(macOS) /// Checks the application's info.plist to see if UIBackgroundModes includes "audio". /// If background audio is supported then the system will allow the AVAudioEngine to start even if the app is in, /// or entering, a background state. This can help prevent a potential crash /// (AVAudioSessionErrorCodeCannotStartPlaying aka error code 561015905) when a route/category change causes /// AudioEngine to attempt to start while the app is not active and background audio is not supported. @objc open static let appSupportsBackgroundAudio = (Bundle.main.infoDictionary?["UIBackgroundModes"] as? [String])?.contains("audio") ?? false #endif } #if !os(macOS) extension AKSettings { /// Shortcut for AVAudioSession.sharedInstance() @objc open static let session = AVAudioSession.sharedInstance() /// Convenience method accessible from Objective-C @objc open static func setSession(category: SessionCategory, options: UInt) throws { try setSession(category: category, with: AVAudioSessionCategoryOptions(rawValue: options)) } /// Set the audio session type @objc open static func setSession(category: SessionCategory, with options: AVAudioSessionCategoryOptions = [.mixWithOthers]) throws { if ❗️AKSettings.disableAVAudioSessionCategoryManagement { do { try session.setCategory("\(category)", with: options) } catch let error as NSError { AKLog("Error: \(error) Cannot set AVAudioSession Category to \(category) with options: \(options)") throw error } } // Preferred IO Buffer Duration do { try session.setPreferredIOBufferDuration(bufferLength.duration) } catch let error as NSError { AKLog("AKSettings Error: Cannot set Preferred IOBufferDuration to " + "\(bufferLength.duration) ( = \(bufferLength.samplesCount) samples)") AKLog("AKSettings Error: \(error))") throw error } // Activate session do { try session.setActive(true) } catch let error as NSError { AKLog("AKSettings Error: Cannot set AVAudioSession.setActive to true") AKLog("AKSettings Error: \(error))") throw error } } @objc open static func computedSessionCategory() -> SessionCategory { if AKSettings.audioInputEnabled { return .playAndRecord } else if AKSettings.playbackWhileMuted { return .playback } else { return .ambient } } @objc open static func computedSessionOptions() -> AVAudioSessionCategoryOptions { var options: AVAudioSessionCategoryOptions = [.mixWithOthers] if AKSettings.audioInputEnabled { options = options.union(.mixWithOthers) #if !os(tvOS) if #available(iOS 10.0, *) { // Blueooth Options // .allowBluetooth can only be set with the categories .playAndRecord and .record // .allowBluetoothA2DP comes for free if the category is .ambient, .soloAmbient, or // .playback. This option is cleared if the category is .record, or .multiRoute. If this // option and .allowBluetooth are set and a device supports Hands-Free Profile (HFP) and the // Advanced Audio Distribution Profile (A2DP), the Hands-Free ports will be given a higher // priority for routing. if AKSettings.bluetoothOptions.isNotEmpty { options = options.union(AKSettings.bluetoothOptions) } else if AKSettings.useBluetooth { // If bluetoothOptions aren't specified // but useBluetooth is then we will use these defaults options = options.union([.allowBluetooth, .allowBluetoothA2DP]) } // AirPlay if AKSettings.allowAirPlay { options = options.union(.allowAirPlay) } } else if AKSettings.bluetoothOptions.isNotEmpty || AKSettings.useBluetooth || AKSettings.allowAirPlay { AKLog("Some of the specified AKSettings are not supported by iOS 9 and were ignored.") } // Default to Speaker if AKSettings.defaultToSpeaker { options = options.union(.defaultToSpeaker) } #endif } return options } /// Checks if headphones are plugged /// Returns true if headPhones are plugged, otherwise return false @objc static open var headPhonesPlugged: Bool { return session.currentRoute.outputs.contains { $0.portType == AVAudioSessionPortHeadphones } } /// Enum of available AVAudioSession Categories @objc public enum SessionCategory: Int, CustomStringConvertible { /// Audio silenced by silent switch and screen lock - audio is mixable case ambient /// Audio is silenced by silent switch and screen lock - audio is non mixable case soloAmbient /// Audio is not silenced by silent switch and screen lock - audio is non mixable case playback /// Silences playback audio case record /// Audio is not silenced by silent switch and screen lock - audio is non mixable. /// To allow mixing see AVAudioSessionCategoryOptionMixWithOthers. case playAndRecord #if !os(tvOS) /// Disables playback and recording case audioProcessing #endif /// Use to multi-route audio. May be used on input, output, or both. case multiRoute public var description: String { if self == .ambient { return AVAudioSessionCategoryAmbient } else if self == .soloAmbient { return AVAudioSessionCategorySoloAmbient } else if self == .playback { return AVAudioSessionCategoryPlayback } else if self == .record { return AVAudioSessionCategoryRecord } else if self == .playAndRecord { return AVAudioSessionCategoryPlayAndRecord } else if self == .multiRoute { return AVAudioSessionCategoryMultiRoute } fatalError("unrecognized AVAudioSessionCategory \(self)") } } } #endif
mit
137bd5f7ec20ba23f242319c4a16a039
39.284024
146
0.621181
5.420382
false
false
false
false
eduardourso/GIFGenerator
Pod/Classes/GIFGenerator.swift
1
6526
import ImageIO import MobileCoreServices import AVFoundation @objc open class GifGenerator: NSObject { var cmTimeArray:[NSValue] = [] var framesArray:[UIImage] = [] /** Generate a GIF using a set of images You can specify the loop count and the delays between the frames. :param: imagesArray an array of images :param: repeatCount the repeat count, defaults to 0 which is infinity :param: frameDelay an delay in seconds between each frame :param: callback set a block that will get called when done, it'll return with data and error, both which can be nil */ open func generateGifFromImages(imagesArray:[UIImage], repeatCount: Int = 0, frameDelay: TimeInterval, destinationURL: URL, callback:@escaping (_ data: Data?, _ error: NSError?) -> ()) { DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { () -> Void in if let imageDestination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeGIF, imagesArray.count, nil) { let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]] as CFDictionary let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] as CFDictionary for image in imagesArray { CGImageDestinationAddImage(imageDestination, image.cgImage!, frameProperties) } CGImageDestinationSetProperties(imageDestination, gifProperties) if CGImageDestinationFinalize(imageDestination) { do { let data = try Data(contentsOf: destinationURL) callback(data, nil) } catch { callback(nil, error as NSError) } } else { callback(nil, self.errorFromString("Couldn't create the final image")) } } } } /** Generate a GIF using a set of video file (NSURL) You can specify the loop count and the delays between the frames. :param: videoURL an url where you video file is stored :param: repeatCount the repeat count, defaults to 0 which is infinity :param: frameDelay an delay in seconds between each frame :param: callback set a block that will get called when done, it'll return with data and error, both which can be nil */ open func generateGifFromVideoURL(videoURL videoUrl:URL, repeatCount: Int = 0, framesInterval:Int, frameDelay: TimeInterval, destinationURL: URL, callback:@escaping (_ data: Data?, _ error: NSError?) -> ()) { self.generateFrames(videoUrl, framesInterval: framesInterval) { (images) -> () in if let images = images { self.generateGifFromImages(imagesArray: images, repeatCount: repeatCount, frameDelay: frameDelay, destinationURL: destinationURL, callback: { (data, error) -> () in self.cmTimeArray = [] self.framesArray = [] callback(data, error) }) } } } // MARK: THANKS TO: http://stackoverflow.com/questions/4001755/trying-to-understand-cmtime-and-cmtimemake fileprivate func generateFrames(_ url:URL, framesInterval:Int, callback:@escaping (_ images:[UIImage]?) -> ()) { DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { () -> Void in self.generateCMTimesArrayOfFramesUsingAsset(framesInterval, asset: AVURLAsset(url: url)) var i = 0 let test = { (time1: CMTime, im: CGImage?, time2: CMTime, result: AVAssetImageGeneratorResult, error: Error?) in if(result == AVAssetImageGeneratorResult.succeeded) { if let image = im { self.framesArray.append(UIImage(cgImage: image)) } } else if (result == AVAssetImageGeneratorResult.failed) { callback(nil); } else if (result == AVAssetImageGeneratorResult.cancelled) { callback(nil); } i = i+1 if(i == self.cmTimeArray.count) { //Thumbnail generation completed callback(self.framesArray) } } as AVAssetImageGeneratorCompletionHandler let generator = AVAssetImageGenerator(asset: AVAsset(url: url)) generator.apertureMode = AVAssetImageGeneratorApertureModeCleanAperture; generator.appliesPreferredTrackTransform = true; generator.requestedTimeToleranceBefore = kCMTimeZero; generator.requestedTimeToleranceAfter = kCMTimeZero; generator.generateCGImagesAsynchronously(forTimes: self.cmTimeArray, completionHandler: test) } } fileprivate func generateCMTimesArrayOfAllFramesUsingAsset(_ asset:AVURLAsset) { if cmTimeArray.count > 0 { cmTimeArray.removeAll() } for t in 0 ..< asset.duration.value { let thumbTime = CMTimeMake(t, asset.duration.timescale) let value = NSValue(time: thumbTime) cmTimeArray.append(value) } } fileprivate func generateCMTimesArrayOfFramesUsingAsset(_ framesInterval:Int, asset:AVURLAsset) { let videoDuration = Int(ceilf((Float(Int(asset.duration.value)/Int(asset.duration.timescale))))) if cmTimeArray.count > 0 { cmTimeArray.removeAll() } for t in 0 ..< videoDuration { let tempInt = Int64(t) let tempCMTime = CMTimeMake(tempInt, asset.duration.timescale) let interval = Int32(framesInterval) for j in 1 ..< framesInterval+1 { let newCMtime = CMTimeMake(Int64(j), interval) let addition = CMTimeAdd(tempCMTime, newCMtime) cmTimeArray.append(NSValue(time: addition)) } } } fileprivate func errorFromString(_ string: String, code: Int = -1) -> NSError { let dict = [NSLocalizedDescriptionKey: string] return NSError(domain: "org.cocoapods.GIFGenerator", code: code, userInfo: dict) } }
mit
8f4ce867fd678852775ac6108dc65d00
44.957746
212
0.604199
5.23336
false
false
false
false
benlangmuir/swift
test/Distributed/distributed_actor_initialization.swift
5
1724
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed import Distributed import FakeDistributedActorSystems @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- distributed actor OK0 { } distributed actor OK1 { var x: Int = 1 // ok, since all fields are initialized, the constructor can be synthesized } distributed actor OK2 { var x: Int init(x: Int, system: FakeActorSystem) { // ok self.x = x } } // NOTE: keep in mind this is only through typechecking, so no explicit // actorSystem is being assigned here. distributed actor OK3 { init() {} } distributed actor OK4 { init(x: String) { } } distributed actor OK5 { var x: Int = 1 init(system: FakeActorSystem, too many: FakeActorSystem) { } } distributed actor OK6 { var x: Int init(y: Int, system: FakeActorSystem) { self.x = y } } distributed actor OKMulti { convenience init(y: Int, system: FakeActorSystem) { // expected-warning{{initializers in actors are not marked with 'convenience'; this is an error in Swift 6}}{{3-15=}} self.init(actorSystem: system) } } distributed actor OKMultiDefaultValues { init(y: Int, system: FakeActorSystem, x: Int = 1234) { // ok self.init(actorSystem: system) } }
apache-2.0
609c12a1183a41d7ecb07f39ad64a716
23.28169
219
0.669374
3.909297
false
false
false
false
benlangmuir/swift
test/TypeDecoder/local_types.swift
31
1807
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-executable %s -g -o %t/local_types -emit-module // RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/local_types -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE // RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test-with-sdk %t/local_types -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL func blackHole(_: Any...) {} func foo() { struct Outer { struct Inner { } struct GenericInner<T> { } } do { let x1 = Outer() let x2 = Outer.Inner() let x3 = Outer.GenericInner<Int>() blackHole(x1, x2, x3) } do { let x1 = Outer.self let x2 = Outer.Inner.self let x3 = Outer.GenericInner<Int>.self blackHole(x1, x2, x3) } } // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_VD // CHECK-TYPE: Outer // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_V5InnerVD // CHECK-TYPE: Outer.Inner // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_V12GenericInnerVy_SiGD // CHECK-TYPE: Outer.GenericInner<Int> // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_VmD // CHECK-TYPE: Outer.Type // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_V5InnerVmD // CHECK-TYPE: Outer.Inner.Type // DEMANGLE-TYPE: $s11local_types3fooyyF5OuterL_V12GenericInnerVy_SiGmD // CHECK-TYPE: Outer.GenericInner<Int>.Type // DEMANGLE-DECL: $s11local_types3fooyyF5OuterL_V // CHECK-DECL: local_types.(file).foo().Outer // DEMANGLE-DECL: $s11local_types3fooyyF5OuterL_V5InnerV // CHECK-DECL: local_types.(file).foo().Outer.Inner // DEMANGLE-DECL: $s11local_types3fooyyF5OuterL_V12GenericInnerV // CHECK-DECL: local_types.(file).foo().Outer.GenericInner
apache-2.0
95e101d907bd7c1f409e0129166d8448
28.16129
125
0.68622
2.823438
false
false
false
false
thanegill/RxSwift
Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
4
4735
//: [<< Index](@previous) import RxSwift import Foundation /*: # Introduction ## Why use RxSwift? A vast majority of the code we write revolves around responding to external actions. When a user manipulates a control, we need to write an @IBAction to respond to that. We need to observe Notifications to detect when the keyboard changes position. We must provide blocks to execute when URL Sessions respond with data. And we use KVO to detect changes in variables. All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system. ## Observables The key to understanding RxSwift is in understanding the notion of Observables. Creating them, manipulating them, and subscribing to them in order to react to changes. ## Creating and Subscribing to Observables The first step in understanding this library is in understanding how to create Observables. There are a number of functions available to make Observables. Creating an Observable is one thing, but if nothing subscribes to the observable, then nothing will come of it so both are explained simultaneously. */ /*: ### empty `empty` creates an empty sequence. The only message it sends is the `.Completed` message. */ example("empty") { let emptySequence = Observable<Int>.empty() let subscription = emptySequence .subscribe { event in print(event) } } /*: ### never `never` creates a sequence that never sends any element or completes. */ example("never") { let neverSequence = Observable<Int>.never() let subscription = neverSequence .subscribe { _ in print("This block is never called.") } } /*: ### just `just` represents sequence that contains one element. It sends two messages to subscribers. The first message is the value of single element and the second message is `.Completed`. */ example("just") { let singleElementSequence = Observable.just(32) let subscription = singleElementSequence .subscribe { event in print(event) } } /*: ### sequenceOf `sequenceOf` creates a sequence of a fixed number of elements. */ example("sequenceOf") { let sequenceOfElements/* : Observable<Int> */ = Observable.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) let subscription = sequenceOfElements .subscribe { event in print(event) } } /*: ### from `from` creates a sequence from `SequenceType` */ example("toObservable") { let sequenceFromArray = [1, 2, 3, 4, 5].toObservable() let subscription = sequenceFromArray .subscribe { event in print(event) } } /*: ### create `create` creates sequence using Swift closure. This examples creates custom version of `just` operator. */ example("create") { let myJust = { (singleElement: Int) -> Observable<Int> in return Observable.create { observer in observer.on(.Next(singleElement)) observer.on(.Completed) return NopDisposable.instance } } let subscription = myJust(5) .subscribe { event in print(event) } } /*: ### failWith create an Observable that emits no items and terminates with an error */ example("failWith") { let error = NSError(domain: "Test", code: -1, userInfo: nil) let erroredSequence = Observable<Int>.error(error) let subscription = erroredSequence .subscribe { event in print(event) } } /*: ### `deferred` do not create the Observable until the observer subscribes, and create a fresh Observable for each observer ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/defer.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/defer.html ) */ example("deferred") { let deferredSequence: Observable<Int> = Observable.deferred { print("creating") return Observable.create { observer in print("emmiting") observer.on(.Next(0)) observer.on(.Next(1)) observer.on(.Next(2)) return NopDisposable.instance } } _ = deferredSequence .subscribe { event in print(event) } _ = deferredSequence .subscribe { event in print(event) } } /*: There is a lot more useful methods in the RxCocoa library, so check them out: * `rx_observe` exist on every NSObject and wraps KVO. * `rx_tap` exists on buttons and wraps @IBActions * `rx_notification` wraps NotificationCenter events * ... and many others */ //: [Index](Index) - [Next >>](@next)
mit
bf8306125c1856c19ee9bf5c0a2f2541
26.690058
366
0.667159
4.352022
false
false
false
false
tuzaiz/ConciseCore
src/CCDB.swift
1
1310
// // TZDB.swift // CloudCore // // Created by Henry on 2014/11/22. // Copyright (c) 2014年 Cloudbay. All rights reserved. // import Foundation import CoreData class CCDB : NSObject { lazy var context : NSManagedObjectContext = { var ctx = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType) ctx.parentContext = ConciseCore.managedObjectContext return ctx }() internal func save() { var error : NSError? self.context.performBlockAndWait { () -> Void in self.saveToContext(&error) } } internal func save(completion:((NSError?) -> Void)?) { self.context.performBlock { () -> Void in var error : NSError? self.context.performBlock({ () -> Void in self.saveToContext(&error) if let complete = completion { complete(error) } }) } } private func saveToContext(error:NSErrorPointer?) { var error : NSError? self.context.save(&error) var ctx : NSManagedObjectContext? = self.context while var context = ctx?.parentContext { context.save(&error) ctx = context } } }
mit
e2c1ad14ba7be001785275f56bf2565f
26.851064
124
0.580275
4.954545
false
false
false
false
phr85/Shopy
ShopyUITests/ShopyUITests.swift
1
4565
// // ShopyUITests.swift // ShopyUITests // // Created by Philippe H. Regenass on 31.03.17. // Copyright © 2017 treeinspired GmbH. All rights reserved. // import XCTest class ShopyUITests: XCTestCase { // MARK: - Properties let app = XCUIApplication() // MARK: - Setup override func setUp() { super.setUp() continueAfterFailure = false app.launch() } override func tearDown() { super.tearDown() } // MARK: - Test Cases func testProductLoadingFromJSON() { // Check if product loading from JSON works let tablesQuery = app.tables let count = tablesQuery.cells.count XCTAssert(count == 4) } func testAddTwoMilkToBasket() { clearBasket() let tablesQuery = app.tables tablesQuery.cells.containing(.staticText, identifier:"Milk").buttons["+"].tap() tablesQuery.cells.containing(.staticText, identifier:"Milk").buttons["+"].tap() app.tabBars.buttons["Basket"].tap() let count = tablesQuery.cells.count XCTAssert(count == 1) } func testBasketTotalPriceInUSD() { clearBasket() // Add some products to basket let tablesShop = app.tables tablesShop.cells.containing(.staticText, identifier:"Eggs").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Eggs").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Milk").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Beans").buttons["+"].tap() app.tabBars.buttons["Basket"].tap() // Open Checkout app.navigationBars["Basket"].buttons["Checkout"].tap() // Scroll Table -> Trigger again TableView datasource let table = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element.children(matching: .table).element table.swipeUp() // Check Totalprice XCTAssert(XCUIApplication().staticTexts["Total Price: USD 6.23"].exists) // Order Products XCUIApplication().toolbars.buttons["Order Now"].tap() // Check if basket empty… app.tabBars.buttons["Shop"].tap() app.tabBars.buttons["Basket"].tap() isBasketClear() } func testOrderViewWithTotalPriceInEUR() { clearBasket() // Add some products to basket let tablesShop = app.tables tablesShop.cells.containing(.staticText, identifier:"Eggs").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Eggs").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Milk").buttons["+"].tap() tablesShop.cells.containing(.staticText, identifier:"Beans").buttons["+"].tap() app.tabBars.buttons["Basket"].tap() // Open Checkout app.navigationBars["Basket"].buttons["Checkout"].tap() // Change currency to EUR app.navigationBars["Review"].buttons["Change Currency"].tap() let usdPickerWheel = app.pickerWheels["USD"] usdPickerWheel.adjust(toPickerWheelValue: "EUR") app.buttons["Apply"].tap() // Waste some time let table = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element.children(matching: .table).element table.swipeUp() // Check if Total Price label changed let totalPricePredicate = NSPredicate(format: "label BEGINSWITH 'Total Price: EUR 5.'") let totalPriceLabel = app.staticTexts.element(matching: totalPricePredicate) XCTAssert(totalPriceLabel.exists) XCUIApplication().toolbars.buttons["Order Now"].tap() let tablesBasket = app.tables let count = tablesBasket.cells.count XCTAssert(count == 0) } // MARK: - Helpers func clearBasket() { app.tabBars.buttons["Basket"].tap() app.navigationBars["Basket"].buttons["Empty"].tap() let tablesBasket = app.tables let count = tablesBasket.cells.count XCTAssert(count == 0) app.tabBars.buttons["Shop"].tap() } func isBasketClear() { clearBasket() app.tabBars.buttons["Basket"].tap() let tablesBasket = app.tables let count = tablesBasket.cells.count XCTAssert(count == 0) } }
mit
5531cda80d23808acca7fbeff2e1638c
33.044776
176
0.61552
4.59879
false
true
false
false
adrfer/swift
stdlib/public/SDK/Foundation/NSValue.swift
1
1135
//===--- NSValue.swift - Bridging things in NSValue -----------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension NSRange : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSValue.self } public func _bridgeToObjectiveC() -> NSValue { return NSValue(range: self) } public static func _forceBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } }
apache-2.0
815b0539cd16a4220542f09fc426d3ad
27.375
80
0.634361
4.809322
false
false
false
false
smartnsoft/Extra
Extra/Classes/UIKit/UIColor+Extra.swift
1
3701
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation extension Extra where Base: UIColor { /// Transform the current color to a sizable UIImage /// /// - parameter size: the desired size, default is 10/10 /// /// - returns: The filled color image public func toImage(size: CGSize = CGSize(width: 10, height: 10)) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) self.base.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } /// Create a color from an hexa string /// /// - parameter hexaString: #1234 or #123456 or without # character /// - parameter alpha: the desired transparence /// /// - returns: generated UIColor public static func fromHexa(_ hexaString: String, alpha: CGFloat = 1) -> UIColor? { guard !hexaString.isEmpty else { return nil } var formatedHexa = hexaString if !hexaString.starts(with: ["#"]) { formatedHexa = "#\(hexaString)" } guard formatedHexa.count == 7 || formatedHexa.count == 4 else { print("Unsupported string format:\(formatedHexa)") return nil } if formatedHexa.count == 4 { let hexaString = formatedHexa as NSString formatedHexa = "#" + hexaString.substring(with: NSRange(location: 1, length: 1)) + hexaString.substring(with: NSRange(location: 1, length: 1)) + hexaString.substring(with: NSRange(location: 2, length: 1)) + hexaString.substring(with: NSRange(location: 2, length: 1)) + hexaString.substring(with: NSRange(location: 3, length: 1)) + hexaString.substring(with: NSRange(location: 3, length: 1)) } let hexaString = formatedHexa as NSString let redHex = "0x" + hexaString.substring(with: NSRange(location: 1, length: 2)) let greenHex = "0x" + hexaString.substring(with: NSRange(location: 3, length: 2)) let blueHex = "0x" + hexaString.substring(with: NSRange(location: 5, length: 2)) var red: UInt32 = 0 Scanner(string: redHex).scanHexInt32(&red) var green: UInt32 = 0 Scanner(string: greenHex).scanHexInt32(&green) var blue: UInt32 = 0 Scanner(string: blueHex).scanHexInt32(&blue) let color = UIColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: alpha) return color } }
mit
58aa0b9e03a94d4e6887a93fc454d861
36.383838
85
0.666847
4.239404
false
false
false
false
KevinCoble/AIToolbox
Package/Gaussian.swift
1
14806
// // Gaussian.swift // AIToolbox // // Created by Kevin Coble on 4/11/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation #if os(Linux) import Glibc #else import Accelerate #endif public enum GaussianError: Error { case dimensionError case zeroInVariance case inverseError case badVarianceValue case diagonalCovarianceOnly case errorInSVDParameters case svdDidNotConverge } open class Gaussian { // Parameters var σsquared : Double var mean : Double var multiplier : Double /// Create a gaussian public init(mean: Double, variance: Double) throws { if (variance < 0.0) { throw GaussianError.badVarianceValue } self.mean = mean σsquared = variance multiplier = 1.0 / sqrt(σsquared * 2.0 * Double.pi) } open func setMean(_ mean: Double) { self.mean = mean } open func setVariance(_ variance: Double) { σsquared = variance multiplier = 1.0 / sqrt(σsquared * 2.0 * Double.pi) } open func setParameters(_ parameters: [Double]) throws { if (parameters.count < 2) { throw MachineLearningError.notEnoughData } mean = parameters[0] setVariance(parameters[1]) } open func getParameterDimension() -> Int { return 2 // Mean and variance } open func getParameters() throws -> [Double] { var parameters = [mean] parameters.append(σsquared) return parameters } /// Function to get the probability of an input value open func getProbability(_ input: Double) -> Double { let exponent = (input - mean) * (input - mean) / (-2.0 * σsquared) return multiplier * exp(exponent) } /// Function to get a random value open func gaussRandom() -> Double { return Gaussian.gaussianRandom(mean, standardDeviation: sqrt(σsquared)) } static var y2 = 0.0 static var use_last = false /// static Function to get a random value for a given distribution open static func gaussianRandom(_ mean : Double, standardDeviation : Double) -> Double { var y1 : Double if (use_last) /* use value from previous call */ { y1 = y2 use_last = false } else { var w = 1.0 var x1 = 0.0 var x2 = 0.0 repeat { #if os(Linux) x1 = 2.0 * (Double(random()) / Double(RAND_MAX)) - 1.0 x2 = 2.0 * (Double(random()) / Double(RAND_MAX)) - 1.0 #else x1 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 x2 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 #endif w = x1 * x1 + x2 * x2 } while ( w >= 1.0 ) w = sqrt( (-2.0 * log( w ) ) / w ) y1 = x1 * w y2 = x2 * w use_last = true } return( mean + y1 * standardDeviation ) } static var y2Float: Float = 0.0 static var use_lastFloat = false /// static Function to get a random value for a given distribution open static func gaussianRandomFloat(_ mean : Float, standardDeviation : Float) -> Float { var y1 : Float if (use_last) /* use value from previous call */ { y1 = y2Float use_last = false } else { var w : Float = 1.0 var x1 : Float = 0.0 var x2 : Float = 0.0 repeat { #if os(Linux) x1 = 2.0 * (Float(random()) / Float(RAND_MAX)) - 1.0 x2 = 2.0 * (Float(random()) / Float(RAND_MAX)) - 1.0 #else x1 = 2.0 * (Float(arc4random()) / Float(UInt32.max)) - 1.0 x2 = 2.0 * (Float(arc4random()) / Float(UInt32.max)) - 1.0 #endif w = x1 * x1 + x2 * x2 } while ( w >= 1.0 ) w = sqrt( (-2.0 * log( w ) ) / w ) y1 = x1 * w y2Float = x2 * w use_last = true } return( mean + y1 * standardDeviation ) } } #if os(Linux) #else open class MultivariateGaussian { // Parameters let dimension: Int let diagonalΣ : Bool var μ : [Double] // Mean var Σ : [Double] // Covariance. If diagonal, then vector, else column-major square matrix (column major for LAPACK) // Calculate values for computing probability var haveCalcValues = false var multiplier : Double // The 1/(2π) ^ (dimension / 2) sqrt(detΣ) var invΣ : [Double] // Inverse of Σ (1/Σ if diagonal) /// Create a multivariate gaussian. dimension should be 2 or greater public init(dimension: Int, diagonalCovariance: Bool = true) throws { self.dimension = dimension diagonalΣ = diagonalCovariance if (dimension < 2) { throw GaussianError.dimensionError } // Start with 0 mean μ = [Double](repeating: 0.0, count: dimension) // Start with the identity matrix for covariance if (diagonalΣ) { Σ = [Double](repeating: 1.0, count: dimension) invΣ = [Double](repeating: 1.0, count: dimension) } else { Σ = [Double](repeating: 0.0, count: dimension * dimension) for index in 0..<dimension { Σ[index * dimension + index] = 1.0 } invΣ = [Double](repeating: 0.0, count: dimension * dimension) // Will get calculated later } // Set the multiplier temporarily multiplier = 1.0 } fileprivate func getComputeValues() throws { var denominator = pow(2.0 * Double.pi, Double(dimension) * 0.5) // Get the determinant and inverse of the covariance matrix var sqrtDeterminant = 1.0 if (diagonalΣ) { for index in 0..<dimension { sqrtDeterminant *= Σ[index] invΣ[index] = 1.0 / Σ[index] } sqrtDeterminant = sqrt(sqrtDeterminant) } else { let uploChar = "U" as NSString var uplo : Int8 = Int8(uploChar.character(at: 0)) // use upper triangle var A = Σ // Make a copy so it isn't mangled var n : __CLPK_integer = __CLPK_integer(dimension) var info : __CLPK_integer = 0 dpotrf_(&uplo, &n, &A, &n, &info) if (info != 0) { throw GaussianError.inverseError } // Extract sqrtDeterminant from U by multiplying the diagonal (U is multiplied by Utranspose after factorization) for index in 0..<dimension { sqrtDeterminant *= A[index * dimension + index] } // Get the inverse dpotri_(&uplo, &n, &A, &n, &info) if (info != 0) { throw GaussianError.inverseError } // Convert inverse U into symmetric full matrix for matrix multiply routines for row in 0..<dimension { for column in row..<dimension { invΣ[row * dimension + column] = A[column * dimension + row] invΣ[column * dimension + row] = A[column * dimension + row] } } } denominator *= sqrtDeterminant if (denominator == 0.0) { throw GaussianError.zeroInVariance } multiplier = 1.0 / denominator haveCalcValues = true } /// Function to set the mean open func setMean(_ mean: [Double]) throws { if (mean.count != dimension) { throw GaussianError.dimensionError } μ = mean } /// Function to set the covariance values. Values are copied into symmetric sides of matrix open func setCoVariance(_ inputIndex1: Int, inputIndex2: Int, value: Double) throws { if (value < 0.0) { throw GaussianError.badVarianceValue } if (inputIndex1 < 0 || inputIndex1 >= dimension) { throw GaussianError.badVarianceValue } if (inputIndex2 < 0 || inputIndex2 >= dimension) { throw GaussianError.badVarianceValue } if (diagonalΣ && inputIndex1 != inputIndex2) { throw GaussianError.diagonalCovarianceOnly } Σ[inputIndex1 * dimension + inputIndex2] = value Σ[inputIndex2 * dimension + inputIndex1] = value haveCalcValues = false } open func setCovarianceMatrix(_ matrix: [Double]) throws { if (diagonalΣ && matrix.count != dimension) { throw GaussianError.diagonalCovarianceOnly } if (!diagonalΣ && matrix.count != dimension * dimension) { throw GaussianError.dimensionError } Σ = matrix haveCalcValues = false } open func setParameters(_ parameters: [Double]) throws { let requiredSize = getParameterDimension() if (parameters.count < requiredSize) { throw MachineLearningError.notEnoughData } μ = Array(parameters[0..<dimension]) try setCovarianceMatrix(Array(parameters[dimension..<requiredSize])) } open func getParameterDimension() -> Int { var numParameters = dimension // size of the mean if (diagonalΣ) { numParameters += dimension // size of diagonal covariance matrix } else { numParameters += dimension * dimension // size of full covariance matrix } return numParameters } open func getParameters() throws -> [Double] { var parameters = μ parameters += Σ return parameters } /// Function to get the probability of an input vector open func getProbability(_ inputs: [Double]) throws -> Double { if (inputs.count != dimension) { throw GaussianError.dimensionError } if (!haveCalcValues) { do { try getComputeValues() } catch let error { throw error } } // Subtract the mean var relative = [Double](repeating: 0.0, count: dimension) vDSP_vsubD(μ, 1, inputs, 1, &relative, 1, vDSP_Length(dimension)) // Determine the exponent var partial = [Double](repeating: 0.0, count: dimension) if (diagonalΣ) { vDSP_vmulD(relative, 1, invΣ, 1, &partial, 1, vDSP_Length(dimension)) } else { vDSP_mmulD(invΣ, 1, relative, 1, &partial, 1, vDSP_Length(dimension), vDSP_Length(1), vDSP_Length(dimension)) } var exponent = 1.0 vDSP_dotprD(partial, 1, relative, 1, &exponent, vDSP_Length(dimension)) exponent *= -0.5 return exp(exponent) * multiplier } /// Function to get a set of random vectors /// Setup is computationaly expensive, so call once to get multiple vectors open func random(_ count: Int) throws -> [[Double]] { var sqrtEigenValues = [Double](repeating: 0.0, count: dimension) var translationMatrix = [Double](repeating: 0.0, count: dimension*dimension) if (diagonalΣ) { // eigenValues are the diagonals - get sqrt of them for multiplication for element in 0..<dimension { sqrtEigenValues[element] = sqrt(Σ[element]) } } else { // If a non-diagonal covariance matrix, get the eigenvalues and eigenvectors // Get the SVD decomposition of the Σ matrix let jobZChar = "S" as NSString var jobZ : Int8 = Int8(jobZChar.character(at: 0)) // return min(m,n) rows of Σ var n : __CLPK_integer = __CLPK_integer(dimension) var u = [Double](repeating: 0.0, count: dimension * dimension) var work : [Double] = [0.0] var lwork : __CLPK_integer = -1 // Ask for the best size of the work array let iworkSize = 8 * dimension var iwork = [__CLPK_integer](repeating: 0, count: iworkSize) var info : __CLPK_integer = 0 var A = Σ // Leave Σ intact var eigenValues = [Double](repeating: 0.0, count: dimension) var eigenVectors = [Double](repeating: 0.0, count: dimension*dimension) dgesdd_(&jobZ, &n, &n, &A, &n, &eigenValues, &u, &n, &eigenVectors, &n, &work, &lwork, &iwork, &info) if (info != 0 || work[0] < 1) { throw GaussianError.errorInSVDParameters } lwork = __CLPK_integer(work[0]) work = [Double](repeating: 0.0, count: Int(work[0])) dgesdd_(&jobZ, &n, &n, &A, &n, &eigenValues, &u, &n, &eigenVectors, &n, &work, &lwork, &iwork, &info) if (info < 0) { throw GaussianError.errorInSVDParameters } if (info > 0) { throw GaussianError.svdDidNotConverge } // Extract the eigenvectors multiplied by the square root of the eigenvalues - make a row-major matrix for dataset vector multiplication using vDSP for vector in 0..<dimension { let sqrtEigenValue = sqrt(eigenValues[vector]) for column in 0..<dimension { translationMatrix[(vector * dimension) + column] = eigenValues[vector + (column * dimension)] * sqrtEigenValue } } } // Get a set of vectors var results : [[Double]] = [] for _ in 0..<count { // Get random uniform vector var entry = [Double](repeating: 0.0, count: dimension) for element in 0..<dimension { entry[element] = Gaussian.gaussianRandom(0.0, standardDeviation: 1.0) } // Extend vector based on the covariance matrix if (diagonalΣ) { // Since diagonal, the eigenvectors are unit vectors, so just multiply each element by the square root of the eigenvalues - which are the diagonal elements vDSP_vmulD(entry, 1, sqrtEigenValues, 1, &entry, 1, vDSP_Length(dimension)) } else { vDSP_mmulD(translationMatrix, 1, entry, 1, &entry, 1, vDSP_Length(dimension), vDSP_Length(1), vDSP_Length(dimension)) } // Add the mean vDSP_vaddD(entry, 1, μ, 1, &entry, 1, vDSP_Length(dimension)) // Insert vector into return results results.append((entry)) } return results } } #endif
apache-2.0
c267763229a83ba274131fa446bd08a7
35.512376
172
0.548573
4.122694
false
false
false
false
Keenan144/SpaceKase
SpaceKase/Rock.swift
1
827
// // Rock.swift // SpaceKase // // Created by Keenan Sturtevant on 6/4/16. // Copyright © 2016 Keenan Sturtevant. All rights reserved. // import Foundation import SpriteKit class Rock: SKSpriteNode { class func spawn() -> SKSpriteNode { let rockColor = UIColor.blueColor() let rockSize = CGSize(width: 30, height: 40) let rock = SKSpriteNode(color: rockColor, size: rockSize) rock.texture = SKTexture(imageNamed: "Rock") rock.physicsBody = SKPhysicsBody(texture: rock.texture!, alphaThreshold: 0, size: rockSize) rock.physicsBody?.dynamic = true rock.physicsBody?.usesPreciseCollisionDetection = true rock.physicsBody?.affectedByGravity = true rock.name = "Rock" print("ROCK: spawn") return rock } }
mit
e9fa9299169c8ec6770d3dfa5d2fe6f2
27.482759
99
0.642857
4.192893
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Extension/UIViewController+IF.swift
1
987
// // UIViewController+IF.swift // ifanr // // Created by sys on 16/7/21. // Copyright © 2016年 ifanrOrg. All rights reserved. // import Foundation extension UIViewController { func showProgress () { let progressView = UIActivityIndicatorView() progressView.activityIndicatorViewStyle = .gray progressView.hidesWhenStopped = true progressView.tag = 500 self.view.addSubview(progressView) progressView.snp.makeConstraints { (make) in make.center.equalTo(self.view) make.height.width.equalTo(20) } progressView.startAnimating() } func hiddenProgress() { for view in self.view.subviews { if view.tag == 500 { let indicatorView : UIActivityIndicatorView = view as! UIActivityIndicatorView indicatorView.stopAnimating() indicatorView.removeFromSuperview() } } } }
mit
0b6cf9923972bb25734baf8e0af223f4
25.594595
94
0.604675
5.262032
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Server Client/Response/MessageCharacteristics.swift
1
689
import Foundation public struct MessageCharacteristics: Identifyable { public var identifier: String public var authorName: String public var receivedDateTime: Date public var subject: String public var contents: String public var isRead: Bool public init( identifier: String, authorName: String, receivedDateTime: Date, subject: String, contents: String, isRead: Bool ) { self.identifier = identifier self.authorName = authorName self.receivedDateTime = receivedDateTime self.subject = subject self.contents = contents self.isRead = isRead } }
mit
f10bf10633569959952f51dea6af3a2f
22.758621
52
0.641509
5.341085
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCContractInfoViewController.swift
2
11601
// // NCContractInfoViewController.swift // Neocom // // Created by Artem Shimanski on 20.06.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import CoreData import Futures class NCContractContactRow: NCContactRow { let title: String init(title: String , contact: NSManagedObjectID?, dataManager: NCDataManager) { self.title = title super.init(prototype: Prototype.NCContactTableViewCell.attribute, contact: contact, dataManager: dataManager) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.text = title cell.subtitleLabel?.text = contact?.name cell.accessoryType = .none } } class NCContractItem: TreeRow { let item: ESI.Contracts.Item lazy var type: NCDBInvType? = { return NCDatabase.sharedDatabase?.invTypes[self.item.typeID] }() init(item: ESI.Contracts.Item) { self.item = item super.init(prototype: Prototype.NCDefaultTableViewCell.default, route: Router.Database.TypeInfo(item.typeID)) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.text = type?.typeName cell.iconView?.image = type?.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image cell.subtitleLabel?.text = NSLocalizedString("Quantity", comment: "") + ": " + NCUnitFormatter.localizedString(from: item.quantity, unit: .none, style: .full) cell.accessoryType = .disclosureIndicator } override var hash: Int { return item.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCContractItem)?.hashValue == hashValue } } class NCContractBidRow: NCContactRow { let bid: ESI.Contracts.Bid init(bid: ESI.Contracts.Bid , contact: NSManagedObjectID?, dataManager: NCDataManager) { self.bid = bid super.init(prototype: Prototype.NCContactTableViewCell.default, contact: contact, dataManager: dataManager) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.text = NCUnitFormatter.localizedString(from: bid.amount, unit: .isk, style: .full) cell.subtitleLabel?.text = contact?.name cell.accessoryType = .none } } class NCContractInfoViewController: NCTreeViewController { var contract: ESI.Contracts.Contract? override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCDefaultTableViewCell.default, Prototype.NCDefaultTableViewCell.attributeNoImage, Prototype.NCContactTableViewCell.attribute, Prototype.NCContactTableViewCell.default, Prototype.NCHeaderTableViewCell.default]) } override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> { guard NCAccount.current != nil, let contract = contract else { return .init(.failure(NCTreeViewControllerError.noResult)) } let progress = Progress(totalUnitCount: 2) return DispatchQueue.global(qos: .utility).async { () -> (CachedValue<[ESI.Contracts.Item]>, CachedValue<[ESI.Contracts.Bid]>) in let items = try progress.perform { self.dataManager.contractItems(contractID: Int64(contract.contractID))}.get() let bids = try progress.perform { self.dataManager.contractBids(contractID: Int64(contract.contractID))}.get() return (items, bids) }.then(on: .main) { (items, bids) -> [NCCacheRecord] in self.items = items self.bids = bids return [items.cacheRecord(in: NCCache.sharedCache!.viewContext), bids.cacheRecord(in: NCCache.sharedCache!.viewContext)] } } override func content() -> Future<TreeNode?> { let progress = Progress(totalUnitCount: 2) return DispatchQueue.global(qos: .utility).async { () -> ([Int64: NSManagedObjectID]?, [Int64: NCLocation]?) in guard let contract = self.contract else {return (nil, nil)} let contacts = progress.perform { () -> [Int64: NSManagedObjectID]? in var contactIDs = Set<Int64>() if contract.acceptorID > 0 { contactIDs.insert(Int64(contract.acceptorID)) } if contract.assigneeID > 0 { contactIDs.insert(Int64(contract.assigneeID)) } if contract.issuerID > 0 { contactIDs.insert(Int64(contract.issuerID)) } if let bids = self.bids?.value { contactIDs.formUnion(bids.map{Int64($0.bidderID)}) } return try? self.dataManager.contacts(ids: contactIDs).get() } let locations = progress.perform { () -> [Int64: NCLocation]? in var locationIDs = Set<Int64>() if let locationID = contract.startLocationID { locationIDs.insert(locationID) } if let locationID = contract.endLocationID { locationIDs.insert(locationID) } return try? self.dataManager.locations(ids: locationIDs).get() } return (contacts, locations) }.then(on: .main) { (contacts, locations) -> TreeNode? in guard let contract = self.contract else {throw NCTreeViewControllerError.noResult} var sections = [TreeNode]() var rows = [TreeNode]() rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Type", title: NSLocalizedString("Type", comment: "").uppercased(), subtitle: contract.type.title)) if let description = contract.title, !description.isEmpty { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Description", title: NSLocalizedString("Description", comment: "").uppercased(), subtitle: description)) } rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Availability", title: NSLocalizedString("Availability", comment: "").uppercased(), subtitle: contract.availability.title)) let status = contract.currentStatus rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Status", title: NSLocalizedString("Status", comment: "").uppercased(), subtitle: status.title)) if let contact = contacts?[Int64(contract.issuerID)] { rows.append(NCContractContactRow(title: NSLocalizedString("From", comment: "").uppercased(), contact: contact, dataManager: self.dataManager)) } if let contact = contacts?[Int64(contract.assigneeID)] { rows.append(NCContractContactRow(title: NSLocalizedString("To", comment: "").uppercased(), contact: contact, dataManager: self.dataManager)) } if let contact = contacts?[Int64(contract.acceptorID)] { rows.append(NCContractContactRow(title: NSLocalizedString("Acceptor", comment: "").uppercased(), contact: contact, dataManager: self.dataManager)) } if let fromID = contract.startLocationID, let toID = contract.endLocationID, fromID != toID, let from = locations?[fromID], let to = locations?[toID] { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "StartLocation", title: NSLocalizedString("Start Location", comment: "").uppercased(), attributedSubtitle: from.displayName)) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "EndLocation", title: NSLocalizedString("End Location", comment: "").uppercased(), attributedSubtitle: to.displayName)) } else if let locationID = contract.startLocationID, let location = locations?[locationID] { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Location", title: NSLocalizedString("Location", comment: "").uppercased(), attributedSubtitle: location.displayName)) } if let price = contract.price, price > 0 { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Price", title: NSLocalizedString("Buyer Will Pay", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: price, unit: .isk, style: .full))) } if let reward = contract.reward, reward > 0 { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Reward", title: NSLocalizedString("Buyer Will Get", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: reward, unit: .isk, style: .full))) } rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Issued", title: NSLocalizedString("Date Issued", comment: "").uppercased(), subtitle: DateFormatter.localizedString(from: contract.dateIssued, dateStyle: .medium, timeStyle: .medium))) rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Expired", title: NSLocalizedString("Date Expired", comment: "").uppercased(), subtitle: DateFormatter.localizedString(from: contract.dateExpired, dateStyle: .medium, timeStyle: .medium))) if let date = contract.dateAccepted { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Accepted", title: NSLocalizedString("Date Accepted", comment: "").uppercased(), subtitle: DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium))) } if let date = contract.dateCompleted { rows.append(DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.attributeNoImage, nodeIdentifier: "Completed", title: NSLocalizedString("Date Completed", comment: "").uppercased(), subtitle: DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .medium))) } sections.append(DefaultTreeSection(nodeIdentifier: "Details", title: NSLocalizedString("Details", comment: "").uppercased(), children: rows)) if let items = self.items?.value, !items.isEmpty { let get = items.filter {$0.isIncluded}.map ({NCContractItem(item: $0)}) let pay = items.filter {!$0.isIncluded}.map ({NCContractItem(item: $0)}) if !get.isEmpty { sections.append(DefaultTreeSection(nodeIdentifier: "BuyerWillGet", title: NSLocalizedString("Buyer Will Get", comment: "").uppercased(), children: get)) } if !pay.isEmpty { sections.append(DefaultTreeSection(nodeIdentifier: "BuyerWillPay", title: NSLocalizedString("Buyer Will Pay", comment: "").uppercased(), children: pay)) } } if let bids = self.bids?.value, !bids.isEmpty { let rows = bids.sorted {$0.amount > $1.amount}.map {NCContractBidRow(bid: $0, contact: contacts?[Int64($0.bidderID)], dataManager: self.dataManager)} sections.append(DefaultTreeSection(nodeIdentifier: "Bids", title: NSLocalizedString("Bids", comment: "").uppercased(), children: rows)) } guard !sections.isEmpty else {throw NCTreeViewControllerError.noResult} return RootNode(sections) } } private var items: CachedValue<[ESI.Contracts.Item]>? private var bids: CachedValue<[ESI.Contracts.Bid]>? }
lgpl-2.1
8ac3d91ad1716cfe18e6685cbedecd62
41.181818
160
0.696552
4.291528
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/GRPCAsyncClientCallTests.swift
1
8059
/* * Copyright 2021, 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. */ #if compiler(>=5.6) import EchoImplementation import EchoModel @testable import GRPC import NIOHPACK import NIOPosix import XCTest @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) class GRPCAsyncClientCallTests: GRPCTestCase { private var group: MultiThreadedEventLoopGroup? private var server: Server? private var channel: ClientConnection? private static let OKInitialMetadata = HPACKHeaders([ (":status", "200"), ("content-type", "application/grpc"), ]) private static let OKTrailingMetadata = HPACKHeaders([ ("grpc-status", "0"), ]) private func setUpServerAndChannel() throws -> ClientConnection { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) self.group = group let server = try Server.insecure(group: group) .withServiceProviders([EchoProvider()]) .withLogger(self.serverLogger) .bind(host: "127.0.0.1", port: 0) .wait() self.server = server let channel = ClientConnection.insecure(group: group) .withBackgroundActivityLogger(self.clientLogger) .connect(host: "127.0.0.1", port: server.channel.localAddress!.port!) self.channel = channel return channel } override func tearDown() { if let channel = self.channel { XCTAssertNoThrow(try channel.close().wait()) } if let server = self.server { XCTAssertNoThrow(try server.close().wait()) } if let group = self.group { XCTAssertNoThrow(try group.syncShutdownGracefully()) } super.tearDown() } func testAsyncUnaryCall() async throws { let channel = try self.setUpServerAndChannel() let get: GRPCAsyncUnaryCall<Echo_EchoRequest, Echo_EchoResponse> = channel.makeAsyncUnaryCall( path: "/echo.Echo/Get", request: .with { $0.text = "holt" }, callOptions: .init() ) await assertThat(try await get.initialMetadata, .is(.equalTo(Self.OKInitialMetadata))) await assertThat(try await get.response, .doesNotThrow()) await assertThat(try await get.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await get.status, .hasCode(.ok)) print(try await get.trailingMetadata) } func testAsyncClientStreamingCall() async throws { let channel = try self.setUpServerAndChannel() let collect: GRPCAsyncClientStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel .makeAsyncClientStreamingCall( path: "/echo.Echo/Collect", callOptions: .init() ) for word in ["boyle", "jeffers", "holt"] { try await collect.requestStream.send(.with { $0.text = word }) } collect.requestStream.finish() await assertThat(try await collect.initialMetadata, .is(.equalTo(Self.OKInitialMetadata))) await assertThat(try await collect.response, .doesNotThrow()) await assertThat(try await collect.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await collect.status, .hasCode(.ok)) } func testAsyncServerStreamingCall() async throws { let channel = try self.setUpServerAndChannel() let expand: GRPCAsyncServerStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel .makeAsyncServerStreamingCall( path: "/echo.Echo/Expand", request: .with { $0.text = "boyle jeffers holt" }, callOptions: .init() ) await assertThat(try await expand.initialMetadata, .is(.equalTo(Self.OKInitialMetadata))) let numResponses = try await expand.responseStream.map { _ in 1 }.reduce(0, +) await assertThat(numResponses, .is(.equalTo(3))) await assertThat(try await expand.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await expand.status, .hasCode(.ok)) } func testAsyncBidirectionalStreamingCall() async throws { let channel = try self.setUpServerAndChannel() let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel .makeAsyncBidirectionalStreamingCall( path: "/echo.Echo/Update", callOptions: .init() ) let requests = ["boyle", "jeffers", "holt"] .map { word in Echo_EchoRequest.with { $0.text = word } } for request in requests { try await update.requestStream.send(request) } try await update.requestStream.send(requests) update.requestStream.finish() let numResponses = try await update.responseStream.map { _ in 1 }.reduce(0, +) await assertThat(numResponses, .is(.equalTo(6))) await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await update.status, .hasCode(.ok)) } func testAsyncBidirectionalStreamingCall_InterleavedRequestsAndResponses() async throws { let channel = try self.setUpServerAndChannel() let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel .makeAsyncBidirectionalStreamingCall( path: "/echo.Echo/Update", callOptions: .init() ) await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata))) var responseStreamIterator = update.responseStream.makeAsyncIterator() for word in ["boyle", "jeffers", "holt"] { try await update.requestStream.send(.with { $0.text = word }) await assertThat(try await responseStreamIterator.next(), .is(.notNil())) } update.requestStream.finish() await assertThat(try await responseStreamIterator.next(), .is(.nil())) await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await update.status, .hasCode(.ok)) } func testAsyncBidirectionalStreamingCall_ConcurrentTasks() async throws { let channel = try self.setUpServerAndChannel() let update: GRPCAsyncBidirectionalStreamingCall<Echo_EchoRequest, Echo_EchoResponse> = channel .makeAsyncBidirectionalStreamingCall( path: "/echo.Echo/Update", callOptions: .init() ) await assertThat(try await update.initialMetadata, .is(.equalTo(Self.OKInitialMetadata))) let counter = RequestResponseCounter() // Send the requests and get responses in separate concurrent tasks and await the group. _ = await withThrowingTaskGroup(of: Void.self) { taskGroup in // Send requests, then end, in a task. taskGroup.addTask { for word in ["boyle", "jeffers", "holt"] { try await update.requestStream.send(.with { $0.text = word }) await counter.incrementRequests() } update.requestStream.finish() } // Get responses in a separate task. taskGroup.addTask { for try await _ in update.responseStream { await counter.incrementResponses() } } } await assertThat(await counter.numRequests, .is(.equalTo(3))) await assertThat(await counter.numResponses, .is(.equalTo(3))) await assertThat(try await update.trailingMetadata, .is(.equalTo(Self.OKTrailingMetadata))) await assertThat(await update.status, .hasCode(.ok)) } } // Workaround https://bugs.swift.org/browse/SR-15070 (compiler crashes when defining a class/actor // in an async context). @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) fileprivate actor RequestResponseCounter { var numResponses = 0 var numRequests = 0 func incrementResponses() async { self.numResponses += 1 } func incrementRequests() async { self.numRequests += 1 } } #endif
apache-2.0
17747215c7776b87c0a2d1f9d8311c91
34.502203
98
0.703933
4.234892
false
false
false
false
mz2/MPMailingListService
Mailing List Example/ViewController.swift
1
2388
// // ViewController.swift // Mailing List Example // // Created by Matias Piipari on 09/09/2016. // Copyright © 2016 Matias Piipari & Co. All rights reserved. // import Cocoa import MPMailingListService extension NSView { public func mp_addSubviewConstrainedToSuperViewEdges(aView:NSView, topOffset:CGFloat = 0, rightOffset:CGFloat = 0, bottomOffset:CGFloat = 0, leftOffset:CGFloat = 0) { aView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(aView) self.mp_addEdgeConstraint(.Left, constantOffset: leftOffset, subview: aView) self.mp_addEdgeConstraint(.Right, constantOffset: rightOffset, subview: aView) self.mp_addEdgeConstraint(.Top, constantOffset: topOffset, subview: aView) self.mp_addEdgeConstraint(.Bottom, constantOffset: bottomOffset, subview: aView) } public func mp_addEdgeConstraint(edge:NSLayoutAttribute, constantOffset:CGFloat = 0, subview:NSView) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint(item:subview, attribute:edge, relatedBy:.Equal, toItem:self, attribute:edge, multiplier:1, constant:constantOffset) self.addConstraint(constraint) return constraint; } } class ViewController: NSViewController { private var signupViewController:MailingListSignupViewController? override func viewDidLoad() { super.viewDidLoad() let bundle = NSBundle(forClass: MailingListSignupViewController.self) self.signupViewController = MailingListSignupViewController(nibName: nil, bundle:bundle) self.view.mp_addSubviewConstrainedToSuperViewEdges(signupViewController!.view) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
76eaf109f4386c52196097118610a87c
33.594203
96
0.556766
5.908416
false
false
false
false
teeeeeegz/DuckDuckDefine-iOS
DuckDuckDefine/SearchDefinition.swift
1
764
// // SearchDefinition.swift // DuckDuckDefine // // Created by Michael Tigas on 13/3/17. // Copyright © 2017 Michael Tigas. All rights reserved. // import Gloss /** Represents a Search Definition object */ struct SearchDefinition : Decodable { let heading: String? let abstractText: String? let type: ResultType? let imageUrl: URL? // MARK: - Deserialisation init?(json: JSON) { self.heading = "Heading" <~~ json self.abstractText = "AbstractText" <~~ json self.type = "Type" <~~ json self.imageUrl = "Image" <~~ json } enum ResultType: String { case Answer = "A" case Exclusive = "E" // Exclusive results include special cases like calculations } }
mit
d48e407167b48c1902a792897fea28fe
21.441176
89
0.610747
4.058511
false
false
false
false
PureSwift/Cacao
Sources/Cacao/UITableViewController.swift
1
5119
// // UITableViewController.swift // Cacao // // Created by Alsey Coleman Miller on 11/18/17. // import Foundation #if os(iOS) import UIKit import CoreGraphics #else import Silica #endif /// A controller object that manages a table view. open class UITableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Initializing the UITableViewController Object public convenience init() { // If you use the standard init method to initialize a UITableViewController object, // a table view in the plain style is created. // https://developer.apple.com/documentation/uikit/uitableviewcontroller/1614754-init self.init(style: .plain) } /// Initializes a table-view controller to manage a table view of a given style. public init(style: UITableViewStyle) { self.style = style super.init(nibName: nil, bundle: nil) } #if os(iOS) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } #endif // MARK: - Getting the Table View /// Returns the table view managed by the controller object. public var tableView: UITableView! { get { return self.view as? UITableView } set { newValue.delegate = self newValue.dataSource = self self.view = newValue } } // MARK: - Configuring the Table Behavior /// A Boolean value indicating if the controller clears the selection when the table appears. /// /// The default value of this property is `true`. /// When `true`, the table view controller clears the table’s current selection /// when it receives a `viewWillAppear(_:)` message. /// Setting this property to `false` preserves the selection. public var clearsSelectionOnViewWillAppear: Bool = true // MARK: - Refreshing the Table View /// The refresh control used to update the table contents. /// /// - Note: The default value of this property is nil. /// /// Assigning a refresh control to this property adds the control to the view controller’s associated interface. /// You do not need to set the frame of the refresh control before associating it with the view controller. /// The view controller updates the control’s height and width and sets its position appropriately. /// /// The table view controller does not automatically update table’s contents in response to user interactions /// with the refresh control. When the user initiates a refresh operation, the control generates a valueChanged event. /// You must associate a target and action method with this event and use them to refresh your table’s contents. public var refreshControl: UIRefreshControl? { get { return self.tableView.refreshControl } set { self.tableView.refreshControl = newValue } } // MARK: - Overriden Methods open override func loadView() { self.tableView = UITableView(frame: .zero, style: style) } open override func viewDidLoad() { super.viewDidLoad() assert(self.tableView != nil, "Table View not loaded") } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) /// Reload on first appearance if self.didReload == false { self.tableView.reloadData() self.didReload = true } // clear selection if self.clearsSelectionOnViewWillAppear, let selectedRow = self.tableView.indexPathForSelectedRow { self.tableView.deselectRow(at: selectedRow, animated: animated) } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // flash scroll indicators self.tableView.flashScrollIndicators() } // MARK: - CustomStringConvertible /* open override var description: String { return String(format: "<%@: %p; tableView = %@>", NSStringFromClass(type(of: self)) as! NSString, self, self.tableView) }*/ // MARK: - UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return 0 } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError("\(type(of: self)) cannot provide cells for \(#function)") } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { } // MARK: - Private private let style: UITableViewStyle private var didReload = false }
mit
fd6ae99a08baaaa5480fae4e50ad82c4
30.732919
127
0.635349
5.338558
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/UITextViewWithPlaceholder.swift
1
1755
// // ......... ......... // ...... ........... ..... // ... ..... .... // ... .... ... // ... ........ ... // .... .... .... ... // ... .... .... ... // ..... ....... .... // ... ..... .... // .... .... // .... .... // ..... ..... // ..... .... // ....... // ... // import UIKit @IBDesignable class UITextViewWithPlaceholder: UITextView { @IBInspectable var placeholder: String = "Description" { didSet { placeholderLabel.text = placeholder } } let placeholderLabel = UILabel() deinit { NotificationCenter.default.removeObserver(self) } override func layoutSubviews() { super.layoutSubviews() placeholderLabel.isHidden = !text.isEmpty } override func awakeFromNib() { super.awakeFromNib() NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: UITextView.textDidChangeNotification, object: nil) placeholderLabel.text = placeholder placeholderLabel.font = App.core.state.theme.font(withSize: 17) addSubview(placeholderLabel) placeholderLabel.sizeToFit() placeholderLabel.textColor = UIColor.white.withAlphaComponent(0.5) placeholderLabel.isHidden = !text.isEmpty placeholderLabel.frame.origin = CGPoint(x: 6, y: 8) placeholderLabel.numberOfLines = 0 } @objc func textViewDidChange(_ notification: Notification) { placeholderLabel.isHidden = !text.isEmpty } }
mit
2aa205a429741df46c324f5d02d89c75
29.258621
149
0.477493
5.131579
false
false
false
false
hughbe/swift
test/IDE/coloring.swift
1
23548
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s // RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s // XFAIL: broken_std_regex #line 17 "abc.swift" // CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str> @available(iOS 8.0, OSX 10.10, *) // CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *) func foo() { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>} if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"} } enum List<T> { case Nil // rdar://21927124 // CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List) indirect case Cons(T, List) } // CHECK: <kw>struct</kw> S { struct S { // CHECK: <kw>var</kw> x : <type>Int</type> var x : Int // CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type> var y : Int.Int // CHECK: <kw>var</kw> a, b : <type>Int</type> var a, b : Int } enum EnumWithDerivedEquatableConformance : Int { // CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} { case CaseA // CHECK-NEXT: <kw>case</kw> CaseA case CaseB, CaseC // CHECK-NEXT: <kw>case</kw> CaseB, CaseC case CaseD = 30, CaseE // CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE } // CHECK-NEXT: } // CHECK: <kw>class</kw> MyCls { class MyCls { // CHECK: <kw>var</kw> www : <type>Int</type> var www : Int // CHECK: <kw>func</kw> foo(x: <type>Int</type>) {} func foo(x: Int) {} // CHECK: <kw>var</kw> aaa : <type>Int</type> { var aaa : Int { // CHECK: <kw>get</kw> {} get {} // CHECK: <kw>set</kw> {} set {} } // CHECK: <kw>var</kw> bbb : <type>Int</type> { var bbb : Int { // CHECK: <kw>set</kw> { set { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } } // CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> { subscript (i : Int, j : Int) -> Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> i + j return i + j } // CHECK: <kw>set</kw>(v) { set(v) { // CHECK: v + i - j v + i - j } } // CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {} func multi(_ name: Int, otherpart x: Int) {} } // CHECK-LABEL: <kw>class</kw> Attributes { class Attributes { // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type> @IBOutlet var v0: Int // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @IBOutlet var v1: String // CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type> @objc @IBOutlet var v2: String // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @objc var v3: String // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {} @available(*, unavailable) func f1() {} // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {} @available(*, unavailable) @IBAction func f2() {} // CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {} @IBAction @available(*, unavailable) func f3() {} // CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {} mutating func func_mutating_1() {} // CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {} nonmutating func func_mutating_2() {} } func stringLikeLiterals() { // CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str> var us1: UnicodeScalar = "a" // CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str> var us2: UnicodeScalar = "ы" // CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str> var ch1: Character = "a" // CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str> var ch2: Character = "あ" // CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str> var s1 = "abc абвгд あいうえお" } // CHECK: <kw>var</kw> globComp : <type>Int</type> var globComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> <int>0</int> return 0 } } // CHECK: <comment-block>/* foo is the best */</comment-block> /* foo is the best */ // CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> { func foo(n: Float) -> Int { // CHECK: <kw>var</kw> fnComp : <type>Int</type> var fnComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> a: <type>Int</type> // CHECK: <kw>return</kw> <int>0</int> var a: Int return 0 } } // CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}() var q = MyCls() // CHECK: <kw>var</kw> ee = <str>"yoo"</str>; var ee = "yoo"; // CHECK: <kw>return</kw> <int>100009</int> return 100009 } ///- returns: single-line, no space // CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space /// - returns: single-line, 1 space // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space /// - returns: single-line, 2 spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces /// - returns: single-line, more spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces // CHECK: <kw>protocol</kw> Prot { protocol Prot { // CHECK: <kw>typealias</kw> Blarg typealias Blarg // CHECK: <kw>func</kw> protMeth(x: <type>Int</type>) func protMeth(x: Int) // CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> } var protocolProperty1: Int { get } // CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> } var protocolProperty2: Int { get set } } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}} infix operator *-* : FunnyPrecedence // CHECK: <kw>precedencegroup</kw> FunnyPrecedence // CHECK-NEXT: <kw>associativity</kw>: left{{$}} // CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence precedencegroup FunnyPrecedence { associativity: left higherThan: MultiplicationPrecedence } // CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence infix operator *-+* : FunnyPrecedence // CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-+*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}} infix operator *--* // CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *--*(l: Int, r: Int) -> Int { return l } // CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {} protocol Prot2 : Prot {} // CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {} class SubCls : MyCls, Prot {} // CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}} func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {} func f(x: Int) -> Int { // CHECK: <comment-line>// string interpolation is the best</comment-line> // string interpolation is the best // CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str> "This is string \(genFn({(a:Int -> Int) in a})) interpolation" // CHECK: <str>"This is unterminated</str> "This is unterminated // CHECK: <str>"This is unterminated with ignored \(interpolation) in it</str> "This is unterminated with ignored \(interpolation) in it // CHECK: <str>"This is terminated with invalid \(interpolation" + "in it"</str> "This is terminated with invalid \(interpolation" + "in it" // CHECK: <str>""" // CHECK-NEXT: This is a multiline string. // CHECK-NEXT: """</str> """ This is a multiline string. """ // CHECK: <str>""" // CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string // CHECK-NEXT: </str>\<anchor>(</anchor> // CHECK-NEXT: <str>""" // CHECK-NEXT: inner // CHECK-NEXT: """</str> // CHECK-NEXT: <anchor>)</anchor><str> // CHECK-NEXT: """</str> """ This is a multiline\( "interpolated" )string \( """ inner """ ) """ } // CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) { func bar(x: Int) -> (Int, Float) { // CHECK: foo({{(<type>)?}}Float{{(</type>)?}}()) foo(Float()) } class GenC<T1,T2> {} func test() { // CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>() var x = GenC<Int, Float>() } // CHECK: <kw>typealias</kw> MyInt = <type>Int</type> typealias MyInt = Int func test2(x: Int) { // CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str> "\(x)" } // CHECK: <kw>class</kw> Observers { class Observers { // CHECK: <kw>var</kw> p1 : <type>Int</type> { var p1 : Int { // CHECK: <kw>willSet</kw>(newValue) {} willSet(newValue) {} // CHECK: <kw>didSet</kw> {} didSet {} } // CHECK: <kw>var</kw> p2 : <type>Int</type> { var p2 : Int { // CHECK: <kw>didSet</kw> {} didSet {} // CHECK: <kw>willSet</kw> {} willSet {} } } // CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) { func test3(o: AnyObject) { // CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type> let x = o as! MyCls } // CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}} func test4(inout a: Int) { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}} if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}} // CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}} func test4b(a: inout Int) { } // CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> { class MySubClass : MyCls { // CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {} override func foo(x: Int) {} // CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {} convenience init(a: Int) {} } // CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> } var g1 = { (x: Int) -> Int in return 0 } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ { infix operator ~~ {} // CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ { prefix operator *~~ {} // CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* { postfix operator ~~* {} func test_defer() { defer { // CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int> let x : Int = 0 } } // FIXME: blah. // FIXME: blah blah // Something something, FIXME: blah // CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line> // CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line> /* FIXME: blah*/ // CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block> /* * FIXME: blah * Blah, blah. */ // CHECK: <comment-block>/* // CHECK: * <comment-marker>FIXME: blah</comment-marker> // CHECK: * Blah, blah. // CHECK: */</comment-block> // TODO: blah. // TTODO: blah. // MARK: blah. // CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line> // CHECK: <kw>func</kw> test5() -> <type>Int</type> { func test5() -> Int { // CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line> // TODO: something, something. // CHECK: <kw>return</kw> <int>0</int> return 0 } func test6<T : Prot>(x: T) {} // CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}} // http://whatever.com?ee=2&yy=1 and radar://123456 /* http://whatever.com FIXME: see in http://whatever.com/fixme http://whatever.com */ // CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line> // CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker> // CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block> // CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line> // http://whatever.com/what-ever // CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {} func <#test1#> () {} /// Brief. /// /// Simple case. /// /// - parameter x: A number /// - parameter y: Another number /// - PaRamEteR z-hyphen-q: Another number /// - parameter : A strange number... /// - parameternope1: Another number /// - parameter nope2 /// - parameter: nope3 /// -parameter nope4: Another number /// * parameter nope5: Another number /// - parameter nope6: Another number /// - Parameters: nope7 /// - seealso: yes /// - seealso: yes /// - seealso: /// -seealso: nope /// - seealso : nope /// - seealso nope /// - returns: `x + y` func foo(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number... // CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2 // CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3 // CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number // CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7 // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope // CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope // CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /// Brief. /// /// Simple case. /// /// - Parameters: /// - x: A number /// - y: Another number /// ///- note: NOTE1 /// /// - NOTE: NOTE2 /// - note: Not a Note field (not at top level) /// - returns: `x + y` func bar(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// - x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /** Does pretty much nothing. Not a parameter list: improper indentation. - Parameters: sdfadsf - WARNING: - WARNING: Should only have one field - $$$: Not a field. Empty field, OK: */ func baz() {} // CHECK: <doc-comment-block>/** // CHECK: Does pretty much nothing. // CHECK: Not a parameter list: improper indentation. // CHECK: - Parameters: sdfadsf // CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field // CHECK: - $$$: Not a field. // CHECK: Empty field, OK: // CHECK: */</doc-comment-block> // CHECK: <kw>func</kw> baz() {} /***/ func emptyDocBlockComment() {} // CHECK: <doc-comment-block>/***/</doc-comment-block> // CHECK: <kw>func</kw> emptyDocBlockComment() {} /** */ func emptyDocBlockComment2() {} // CHECK: <doc-comment-block>/** // CHECK: */ // CHECK: <kw>func</kw> emptyDocBlockComment2() {} /** */ func emptyDocBlockComment3() {} // CHECK: <doc-comment-block>/** */ // CHECK: <kw>func</kw> emptyDocBlockComment3() {} /**/ func malformedBlockComment(f : () throws -> ()) rethrows {} // CHECK: <doc-comment-block>/**/</doc-comment-block> // CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {} //: playground doc comment line func playgroundCommentLine(f : () throws -> ()) rethrows {} // CHECK: <comment-line>//: playground doc comment line</comment-line> /*: playground doc comment multi-line */ func playgroundCommentMultiLine(f : () throws -> ()) rethrows {} // CHECK: <comment-block>/*: // CHECK: playground doc comment multi-line // CHECK: */</comment-block> /// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings) // CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url> func funcTakingFor(for internalName: Int) {} // CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {} func funcTakingIn(in internalName: Int) {} // CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {} _ = 123 // CHECK: <int>123</int> _ = -123 // CHECK: <int>-123</int> _ = -1 // CHECK: <int>-1</int> _ = -0x123 // CHECK: <int>-0x123</int> _ = -3.1e-5 // CHECK: <float>-3.1e-5</float> /** aaa - returns: something */ // CHECK: - <doc-comment-field>returns</doc-comment-field>: something let filename = #file // CHECK: <kw>let</kw> filename = <kw>#file</kw> let line = #line // CHECK: <kw>let</kw> line = <kw>#line</kw> let column = #column // CHECK: <kw>let</kw> column = <kw>#column</kw> let function = #function // CHECK: <kw>let</kw> function = <kw>#function</kw> let image = #imageLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal> let file = #fileLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal> let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) // CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal> let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 1, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)] // CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>] "--\"\(x) --" // CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str> func keywordAsLabel1(in: Int) {} // CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {} func keywordAsLabel2(for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {} func keywordAsLabel3(if: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel4(_: Int) {} // CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {} func keywordAsLabel5(_: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel6(if let: Int) {} // CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {} func foo1() { // CHECK: <kw>func</kw> foo1() { keywordAsLabel1(in: 1) // CHECK: keywordAsLabel1(in: <int>1</int>) keywordAsLabel2(for: 1) // CHECK: keywordAsLabel2(for: <int>1</int>) keywordAsLabel3(if: 1, for: 2) // CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>) keywordAsLabel5(1, for: 2) // CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>) _ = (if: 0, for: 2) // CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>) _ = (_: 0, _: 2) // CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>) } func foo2(O1 : Int?, O2: Int?, O3: Int?) { guard let _ = O1, var _ = O2, let _ = O3 else { } // CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { } if let _ = O1, var _ = O2, let _ = O3 {} // CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {} } func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) { // CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) { switch(`for`, `in`) { case (let x, let y): // CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y): print(x, y) } } // Keep this as the last test /** Trailing off ... func unterminatedBlockComment() {} // CHECK: <comment-line>// Keep this as the last test</comment-line> // CHECK: <doc-comment-block>/** // CHECK: Trailing off ... // CHECK: func unterminatedBlockComment() {} // CHECK: </doc-comment-block>
apache-2.0
106f39d0f5df3f8a25a3c4742bcc23cf
36.026772
178
0.605436
2.906304
false
false
false
false
StanZabroda/Hydra
Hydra/HRInAlbumController.swift
1
5656
// // HRInAlbumController.swift // Hydra // // Created by Evgeny Abramov on 8/3/15. // Copyright © 2015 Evgeny Abramov. All rights reserved. // import UIKit class HRInAlbumController: UITableViewController { var audiosArray = Array<HRAudioItemModel>() var loading = false var album_id : Int! override func loadView() { super.loadView() } override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = 70 self.tableView.tableFooterView = UIView(frame: CGRectZero) self.loadMoreAudios() self.tableView.registerClass(HRAllMusicCell.self, forCellReuseIdentifier: "HRAllMusicCell") self.tableView.allowsMultipleSelectionDuringEditing = false self.addLeftBarButton() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // MARK: - load all audio func loadMoreAudios() { if loading == false { loading = true let getAudio = VKRequest(method: "audio.get", andParameters: ["count":100,"offset":self.audiosArray.count,"album_id":self.album_id], andHttpMethod: "GET") getAudio.executeWithResultBlock({ (response) -> Void in let json = response.json as! Dictionary<String,AnyObject> let items = json["items"] as! Array<Dictionary<String,AnyObject>> for audioDict in items { print(audioDict) let jsonAudioItem = JSON(audioDict) let audioItemModel = HRAudioItemModel(json: jsonAudioItem) self.audiosArray.append(audioItemModel) } self.tableView.reloadData() self.loading = false }, errorBlock: { (error) -> Void in // error print(error) }) } } // mark: - tableView delegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.audiosArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let audio = self.audiosArray[indexPath.row] let cell:HRAllMusicCell = self.tableView.dequeueReusableCellWithIdentifier("HRAllMusicCell", forIndexPath: indexPath) as! HRAllMusicCell cell.audioAristLabel.text = audio.artist cell.audioTitleLabel.text = audio.title //cell.audioDurationTime.text = self.durationFormater(Double(audio.duration)) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //self.tableView.deselectRowAtIndexPath(indexPath, animated: true) dispatch.async.main { () -> Void in let audioLocalModel = self.audiosArray[indexPath.row] HRPlayerManager.sharedInstance.items = self.audiosArray HRPlayerManager.sharedInstance.currentPlayIndex = indexPath.row HRPlayerManager.sharedInstance.playItem(audioLocalModel) self.presentViewController(PlayerController(), animated: true, completion: nil) } // self.presentViewController(PlayerController(), animated: true) { () -> Void in // dispatch.async.main { () -> Void in // var audioLocalModel = self.audiosArray[indexPath.row] // // HRPlayerManager.sharedInstance.playItem(audioLocalModel) // // } // } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { //add code here for when you hit delete } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.audiosArray.count - 7 { self.loadMoreAudios() } } //MARK :- stuff func durationFormater(duration:Double) -> String { let min = Int(floor(duration / 60)) let sec = Int(floor(duration % 60)) return "\(min):\(sec)" } func addLeftBarButton() { let button = UIBarButtonItem(image: UIImage(named: "backButton")?.imageWithColor(UIColor.whiteColor()), style: UIBarButtonItemStyle.Plain, target: self, action: "backButtonAction") self.navigationItem.leftBarButtonItem = button } func backButtonAction() { self.navigationController?.popViewControllerAnimated(true) } func openMenu() { HRInterfaceManager.sharedInstance.openMenu() } }
mit
79875f2adf93d16b1ad3cadbb9306950
30.071429
188
0.576658
5.655
false
false
false
false
theMedvedev/eduConnect
eduConnect/Extensions.swift
1
1182
// // Extensions.swift // eduConnect // // Created by Alexey Medvedev on 1/14/17. // Copyright © 2017 #nyc1-2devsandarussian. All rights reserved. // import Foundation import UIKit // MARK: Extension on Notification.Name to avoid errors in strings extension Notification.Name { static let closeSafariVC = Notification.Name("close-safari-view-controller") static let closeLoginVC = Notification.Name("close-login-view-controller") static let closeProfileVC = Notification.Name("close-profile-view-controller") } // MARK: Helper method for query parsing -> used in AppDelegate during OAuth extension URL { func getQueryItemValue(named name: String) -> String? { let components = URLComponents(url: self, resolvingAgainstBaseURL: false) let query = components?.queryItems return query?.filter({$0.name == name}).first?.value } } extension UIColor { class func getRandomColor() -> UIColor { let red: CGFloat = CGFloat(drand48()) let green: CGFloat = CGFloat(drand48()) let blue: CGFloat = CGFloat(drand48()) return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } }
mit
ebe4d3a131b7495e88287d613df50a2a
30.918919
82
0.686706
4.100694
false
false
false
false
CD1212/Doughnut
Pods/GRDB.swift/GRDB/Migration/DatabaseMigrator.swift
1
8489
/// A DatabaseMigrator registers and applies database migrations. /// /// Migrations are named blocks of SQL statements that are guaranteed to be /// applied in order, once and only once. /// /// When a user upgrades your application, only non-applied migration are run. /// /// Usage: /// /// var migrator = DatabaseMigrator() /// /// // v1.0 database /// migrator.registerMigration("createAuthors") { db in /// try db.execute(""" /// CREATE TABLE authors ( /// id INTEGER PRIMARY KEY, /// creationDate TEXT, /// name TEXT NOT NULL /// ) /// """) /// } /// /// migrator.registerMigration("createBooks") { db in /// try db.execute(""" /// CREATE TABLE books ( /// uuid TEXT PRIMARY KEY, /// authorID INTEGER NOT NULL /// REFERENCES authors(id) /// ON DELETE CASCADE ON UPDATE CASCADE, /// title TEXT NOT NULL /// ) /// """) /// } /// /// // v2.0 database /// migrator.registerMigration("AddBirthYearToAuthors") { db in /// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT") /// } /// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { /// A new migrator. public init() { } /// Registers a migration. /// /// migrator.registerMigration("createPlayers") { db in /// try db.execute(""" /// CREATE TABLE players ( /// id INTEGER PRIMARY KEY, /// creationDate TEXT, /// name TEXT NOT NULL /// ) /// """) /// } /// /// - parameters: /// - identifier: The migration identifier. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) { registerMigration(Migration(identifier: identifier, migrate: migrate)) } #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in /// try db.execute(""" /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); /// INSERT INTO new_players SELECT * FROM players; /// DROP TABLE players; /// ALTER TABLE new_players RENAME TO players; /// """) /// } /// /// While your migration code runs with disabled foreign key checks, those /// are re-enabled and checked at the end of the migration, regardless of /// eventual errors. /// /// - parameters: /// - identifier: The migration identifier. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) } #else @available(iOS 8.2, OSX 10.10, *) /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in /// try db.execute(""" /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); /// INSERT INTO new_players SELECT * FROM players; /// DROP TABLE players; /// ALTER TABLE new_players RENAME TO players; /// """) /// } /// /// While your migration code runs with disabled foreign key checks, those /// are re-enabled and checked at the end of the migration, regardless of /// eventual errors. /// /// - parameters: /// - identifier: The migration identifier. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) } #endif /// Iterate migrations in the same order as they were registered. If a /// migration has not yet been applied, its block is executed in /// a transaction. /// /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where /// migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { try writer.write { db in try setupMigrations(db) try runMigrations(db) } } /// Iterate migrations in the same order as they were registered, up to the /// provided target. If a migration has not yet been applied, its block is /// executed in a transaction. /// /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where /// migrations should apply. /// - targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { try writer.write { db in try setupMigrations(db) try runMigrations(db, upTo: targetIdentifier) } } // MARK: - Non public private var migrations: [Migration] = [] private mutating func registerMigration(_ migration: Migration) { GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") migrations.append(migration) } private func setupMigrations(_ db: Database) throws { try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") } private func appliedIdentifiers(_ db: Database) throws -> Set<String> { return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations")) } private func runMigrations(_ db: Database) throws { let appliedIdentifiers = try self.appliedIdentifiers(db) for migration in migrations where !appliedIdentifiers.contains(migration.identifier) { try migration.run(db) } } private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { var prefixMigrations: [Migration] = [] for migration in migrations { prefixMigrations.append(migration) if migration.identifier == targetIdentifier { break } } // targetIdentifier must refer to a registered migration GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied let appliedIdentifiers = try self.appliedIdentifiers(db) if prefixMigrations.count < migrations.count { let nextIdentifier = migrations[prefixMigrations.count].identifier GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { try migration.run(db) } } }
gpl-3.0
a7b849fd075a77bcab8cd41be30c28ce
42.533333
168
0.602898
5.023077
false
false
false
false
LeoMobileDeveloper/PullToRefreshKit
Demo/Demo/YoukuRefreshHeader.swift
1
3426
// // YoukuRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/31. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit import PullToRefreshKit class YoukuRefreshHeader:UIView,RefreshableHeader{ let iconImageView = UIImageView()// 这个ImageView用来显示下拉箭头 let rotatingImageView = UIImageView() //这个ImageView用来播放动图 let backgroundImageView = UIImageView() //这个ImageView用来显示广告的 override init(frame: CGRect) { super.init(frame: frame) iconImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25) iconImageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0) iconImageView.image = UIImage(named: "youku_down") rotatingImageView.image = UIImage(named: "youku_refreshing") rotatingImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25) backgroundImageView.image = UIImage(named: "youku_ad.jpeg") addSubview(backgroundImageView) addSubview(iconImageView) addSubview(rotatingImageView) } override func layoutSubviews() { super.layoutSubviews() backgroundImageView.frame = self.bounds iconImageView.center = CGPoint(x: self.bounds.width/2, y: self.frame.size.height - 30.0) rotatingImageView.center = CGPoint(x: self.bounds.width/2, y: self.frame.size.height - 30.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - RefreshableHeader - func heightForHeader() -> CGFloat { return UIScreen.main.bounds.size.width * 328.0/571.0 } func heightForFireRefreshing() -> CGFloat { return 60.0 } func heightForRefreshingState() -> CGFloat { return 60.0 } //监听状态变化 func stateDidChanged(_ oldState: RefreshHeaderState, newState: RefreshHeaderState) { if newState == .pulling && oldState == .idle{ UIView.animate(withDuration: 0.4, animations: { self.iconImageView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi+0.000001) }) } if newState == .idle{ UIView.animate(withDuration: 0.4, animations: { self.iconImageView.transform = CGAffineTransform.identity }) } } //松手即将刷新的状态 func didBeginRefreshingState(){ self.iconImageView.isHidden = true self.rotatingImageView.isHidden = false let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotateAnimation.toValue = NSNumber(value: Double.pi * 2.0) rotateAnimation.duration = 0.8 rotateAnimation.isCumulative = true rotateAnimation.repeatCount = 10000000 self.rotatingImageView.layer.add(rotateAnimation, forKey: "rotate") } //刷新结束,将要隐藏header func didBeginHideAnimation(_ result:RefreshResult){ self.rotatingImageView.isHidden = true self.iconImageView.isHidden = false self.iconImageView.layer.removeAllAnimations() self.iconImageView.layer.transform = CATransform3DIdentity self.iconImageView.image = UIImage(named: "youku_down") } //刷新结束,完全隐藏header func didCompleteHideAnimation(_ result:RefreshResult){ } }
mit
1f32600cf3d5e227616cf1d86319fb98
36.11236
101
0.66485
4.404
false
false
false
false
amosavian/FileProvider
Sources/FileProvider.swift
2
59625
// // FileProvider.swift // FileProvider // // Created by Amir Abbas Mousavian. // Copyright © 2016 Mousavian. Distributed under MIT license. // import Foundation #if os(iOS) || os(tvOS) import UIKit import ImageIO public typealias ImageClass = UIImage #elseif os(macOS) import Cocoa import ImageIO public typealias ImageClass = NSImage #endif /// Completion handler type with an error argument public typealias SimpleCompletionHandler = ((_ error: Error?) -> Void)? /// This protocol defines FileProvider neccesary functions and properties to connect and get contents list public protocol FileProviderBasic: class, NSSecureCoding, CustomDebugStringConvertible { /// An string to identify type of provider. static var type: String { get } /// An string to identify type of provider. var type: String { get } /// The url of which paths should resolve against. var baseURL: URL? { get } /** Dispatch queue usually used in query methods. Set it to a new object to switch between cuncurrent and serial queues. - **Default:** Cuncurrent `DispatchQueue` object. */ var dispatch_queue: DispatchQueue { get set } /// Operation queue ususlly used in file operation methods. /// use `maximumOperationTasks` property of provider to manage operation queue. var operation_queue: OperationQueue { get set } /// Delegate to update UI after finishing file operations. var delegate: FileProviderDelegate? { get set } /** login credential for provider. Should be set in `init` method. **Example initialization:** ```` provider.credential = URLCredential(user: "user", password: "password", persistence: .forSeession) ```` - Note: In OAuth based providers like `DropboxFileProvider` and `OneDriveFileProvider`, password is Token. use [OAuthSwift](https://github.com/OAuthSwift/OAuthSwift) library to fetch clientId and Token of user. */ var credential: URLCredential? { get set } /** Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty array. - Parameters: - path: path to target directory. If empty, root will be iterated. - completionHandler: a closure with result of directory entries or error. - contents: An array of `FileObject` identifying the the directory entries. - error: Error returned by system. */ func contentsOfDirectory(path: String, completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) /** Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty `FileObject`. - Parameters: - path: path to target directory. If empty, attributes of root will be returned. - completionHandler: a closure with result of directory entries or error. - attributes: A `FileObject` containing the attributes of the item. - error: Error returned by system. */ func attributesOfItem(path: String, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) /// Returns volume/provider information asynchronously. /// - Parameter volumeInfo: Information of filesystem/Provider returned by system/server. func storageProperties(completionHandler: @escaping (_ volumeInfo: VolumeObject?) -> Void) /** Search files inside directory using query asynchronously. - Note: Query string is limited to file name, to search based on other file attributes, use NSPredicate version. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: Simple string that file name begins with to be search, case-insensitive. - foundItemHandler: Closure which is called when a file is found - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. */ @discardableResult func searchFiles(path: String, recursive: Bool, query: String, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? /** Search files inside directory using query asynchronously. Sample predicates: ``` NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)") NSPredicate(format: "(modifiedDate >= %@)", Date()) NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder") ``` - Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate. - Important: A file name criteria should be provided for Dropbox. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`. - foundItemHandler: Closure which is called when a file is found - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. - Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items. */ @discardableResult func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? /** Returns an independent url to access the file. Some providers like `Dropbox` due to their nature. don't return an absolute url to be used to access file directly. - Parameter path: Relative path of file or directory. - Returns: An url, can be used to access to file directly. */ func url(of path: String) -> URL /// Returns the relative path of url, without percent encoding. Even if url is absolute or /// retrieved from another provider, it will try to resolve the url against `baseURL` of /// current provider. It's highly recomended to use this method for displaying purposes. /// /// - Parameter url: Absolute url to file or directory. /// - Returns: A `String` contains relative path of url against base url. func relativePathOf(url: URL) -> String /// Checks the connection to server or permission on local /// /// - Note: To prevent race condition, use this method wisely and avoid it as far possible. /// /// - Parameter success: indicated server is reachable or not. /// - Parameter error: `Error` returned by server if occured. func isReachable(completionHandler: @escaping(_ success: Bool, _ error: Error?) -> Void) } extension FileProviderBasic { public func searchFiles(path: String, recursive: Bool, query: String, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { let predicate = NSPredicate(format: "name BEGINSWITH[c] %@", query) return self.searchFiles(path: path, recursive: recursive, query: predicate, foundItemHandler: foundItemHandler, completionHandler: completionHandler) } /** Search files inside directory using query asynchronously. Sample predicates: ``` NSPredicate(format: "(name CONTAINS[c] 'hello') && (filesize >= 10000)") NSPredicate(format: "(modifiedDate >= %@)", Date()) NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder") ``` - Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate. - Important: A file name criteria should be provided for Dropbox. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`. - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. - Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items. */ func searchFiles(path: String, recursive: Bool, query: NSPredicate, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { return searchFiles(path: path, recursive: recursive, query: query, foundItemHandler: nil, completionHandler: completionHandler) } /// The maximum number of queued operations that can execute at the same time. /// /// The default value of this property is `OperationQueue.defaultMaxConcurrentOperationCount`. public var maximumOperationTasks: Int { get { return operation_queue.maxConcurrentOperationCount } set { operation_queue.maxConcurrentOperationCount = newValue } } public var debugDescription: String { let typeDesc = "\(Self.type) provider" let urlDesc = self.baseURL.map({ " - " + $0.absoluteString }) ?? "" let credentialDesc = self.credential?.user.map({ " - " + $0.debugDescription }) ?? "" return typeDesc + urlDesc + credentialDesc } } /// Checking equality of two file provider, regardless of current path queues and delegates. public func ==(lhs: FileProviderBasic, rhs: FileProviderBasic) -> Bool { if lhs === rhs { return true } if type(of: lhs) != type(of: rhs) { return false } return lhs.type == rhs.type && lhs.baseURL == rhs.baseURL && lhs.credential == rhs.credential } /// Cancels all active underlying tasks when deallocating remote providers public var fileProviderCancelTasksOnInvalidating = true /// Extending `FileProviderBasic` for web-based file providers public protocol FileProviderBasicRemote: FileProviderBasic { /// Underlying URLSession instance used for HTTP/S requests var session: URLSession { get } /** A `URLCache` to cache downloaded files and contents. - Note: It has no effect unless setting `useCache` property to `true`. - Warning: FileProvider doesn't manage/free `URLCache` object in a memory pressure scenario. It's upon you to clear cache memory when receiving `didReceiveMemoryWarning` or via observing `.UIApplicationDidReceiveMemoryWarning` notification. To clear memory usage use this code: ``` provider.cache?.removeAllCachedResponses() ``` */ var cache: URLCache? { get } /// Determine to use `cache` property to cache downloaded file objects. Doesn't have effect on query type methods. var useCache: Bool { get set } /// Validating cached data using E-Tag or Revision identifier if possible. var validatingCache: Bool { get set } } internal extension FileProviderBasicRemote { func returnCachedDate(with request: URLRequest, validatingCache: Bool, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> Bool { guard let cache = self.cache else { return false } if let response = cache.cachedResponse(for: request) { var validatedCache = !validatingCache let lastModifiedDate = (response.response as? HTTPURLResponse)?.allHeaderFields["Last-Modified"] as? String let eTag = (response.response as? HTTPURLResponse)?.allHeaderFields["ETag"] as? String if lastModifiedDate == nil && eTag == nil, validatingCache { var validateRequest = request validateRequest.httpMethod = "HEAD" let group = DispatchGroup() group.enter() self.session.dataTask(with: validateRequest, completionHandler: { (_, response, e) in if let httpResponse = response as? HTTPURLResponse { let currentETag = httpResponse.allHeaderFields["ETag"] as? String let currentLastModifiedDate = httpResponse.allHeaderFields["ETag"] as? String ?? "nonvalidetag" validatedCache = (eTag != nil && currentETag == eTag) || (lastModifiedDate != nil && currentLastModifiedDate == lastModifiedDate) } group.leave() }).resume() _ = group.wait(timeout: .now() + self.session.configuration.timeoutIntervalForRequest) } if validatedCache { completionHandler(response.data, response.response, nil) return true } } return false } func runDataTask(with request: URLRequest, operation: FileOperationType? = nil, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) { let useCache = self.useCache let validatingCache = self.validatingCache dispatch_queue.async { if useCache { if self.returnCachedDate(with: request, validatingCache: validatingCache, completionHandler: completionHandler) { return } } let task = self.session.dataTask(with: request, completionHandler: completionHandler) task.taskDescription = operation?.json task.resume() } } } /// Defines methods for common file operaions including create, copy/move and delete public protocol FileProviderOperations: FileProviderBasic { /// Delgate for managing operations involving the copying, moving, linking, or removal of files and directories. When you use an FileManager object to initiate a copy, move, link, or remove operation, the file provider asks its delegate whether the operation should begin at all and whether it should proceed when an error occurs. var fileOperationDelegate : FileOperationDelegate? { get set } /** Creates a new directory at the specified path asynchronously. This will create any necessary intermediate directories. - Parameters: - folder: Directory name. - at: Parent path of new directory. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func create(folder: String, at: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Moves a file or directory from `path` to designated path asynchronously. When you want move a file, destination path should also consists of file name. Either a new name or the old one. If file is already exist, an error will be returned via completionHandler. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func moveItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Moves a file or directory from `path` to designated path asynchronously. When you want move a file, destination path should also consists of file name. Either a new name or the old one. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func moveItem(path: String, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Copies a file or directory from `path` to designated path asynchronously. When want copy a file, destination path should also consists of file name. Either a new name or the old one. If file is already exist, an error will be returned via completionHandler. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Copies a file or directory from `path` to designated path asynchronously. When want copy a file, destination path should also consists of file name. Either a new name or the old one. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Removes the file or directory at the specified path. - Parameters: - path: file or directory path. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func removeItem(path: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Uploads a file from local file url to designated path asynchronously. Method will fail if source is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - localFile: a file url to file. - to: destination path of file, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. */ @discardableResult func copyItem(localFile: URL, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Uploads a file from local file url to designated path asynchronously. Method will fail if source is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - localFile: a file url to file. - to: destination path of file, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. */ @discardableResult func copyItem(localFile: URL, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Download a file from `path` to designated local file url asynchronously. Method will fail if destination is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - path: original file or directory path. - toLocalURL: destination local url of file, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, toLocalURL: URL, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderOperations { @discardableResult public func moveItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.moveItem(path: path, to: to, overwrite: false, completionHandler: completionHandler) } @discardableResult public func copyItem(localFile: URL, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.copyItem(localFile: localFile, to: to, overwrite: false, completionHandler: completionHandler) } @discardableResult public func copyItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.copyItem(path: path, to: to, overwrite: false, completionHandler: completionHandler) } } extension FileProviderOperations { internal func delegateNotify(_ operation: FileOperationType, error: Error? = nil) { DispatchQueue.main.async(execute: { if let error = error { self.delegate?.fileproviderFailed(self, operation: operation, error: error) } else { self.delegate?.fileproviderSucceed(self, operation: operation) } }) } internal func delegateNotify(_ operation: FileOperationType, progress: Double) { DispatchQueue.main.async(execute: { self.delegate?.fileproviderProgress(self, operation: operation, progress: Float(progress)) }) } } /// Defines method for fetching and modifying file contents public protocol FileProviderReadWrite: FileProviderBasic { /** Retreives a `Data` object with the contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - completionHandler: a closure with result of file contents or error. - contents: contents of file in a `Data` object. - error: `Error` returned by system if occured. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, completionHandler: @escaping (_ contents: Data?, _ error: Error?) -> Void) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - offset: First byte index which should be read. **Starts from 0.** - length: Bytes count of data. Pass `-1` to read until the end of file. - completionHandler: a closure with result of file contents or error. - contents: contents of file in a `Data` object. - error: Error returned by system if occured. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, offset: Int64, length: Int, completionHandler: @escaping (_ contents: Data?, _ error: Error?) -> Void) -> Progress? /** Write the contents of the `Data` to a location asynchronously. It will return error if file is already exists. Not attomically by default, unless the provider enforces it. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. It will return error if file is already exists. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - atomically: data will be written to a temporary file before writing to final location. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, atomically: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. Not attomically by default, unless the provider enforces it. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - overwrite: Destination file should be overwritten if file is already exists. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - overwrite: Destination file should be overwritten if file is already exists. Default is `false`. - atomically: data will be written to a temporary file before writing to final location. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, atomically: Bool, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderReadWrite { @discardableResult public func contents(path: String, completionHandler: @escaping ((_ contents: Data?, _ error: Error?) -> Void)) -> Progress? { return self.contents(path: path, offset: 0, length: -1, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: false, overwrite: false, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, atomically: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: atomically, overwrite: false, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: false, overwrite: overwrite, completionHandler: completionHandler) } } /// Defines method for fetching file contents progressivly public protocol FileProviderReadWriteProgressive { /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from zero. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - responseHandler: a closure which will be called after fetching server response. - response: `URLResponse` returned from server. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from zero. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - offset: First byte index which should be read. **Starts from 0.** - length: Bytes count of data. Pass `-1` to read until the end of file. - responseHandler: a closure which will be called after fetching server response. - response: `URLResponse` returned from server. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from offset. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, offset: Int64, length: Int, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderReadWriteProgressive { @discardableResult public func contents(path: String, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? { return contents(path: path, offset: 0, length: -1, responseHandler: nil, progressHandler: progressHandler, completionHandler: completionHandler) } @discardableResult public func contents(path: String, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? { return contents(path: path, offset: 0, length: -1, responseHandler: responseHandler, progressHandler: progressHandler, completionHandler: completionHandler) } } /// Allows a file provider to notify changes occured public protocol FileProviderMonitor: FileProviderBasic { /** Starts monitoring a path and its subpaths, including files and folders, for any change, including copy, move/rename, content changes, etc. To avoid thread congestion, `evetHandler` will be triggered with 0.2 seconds interval, and has a 0.25 second delay, to ensure it's called after updates. - Note: this functionality is available only in `LocalFileProvider` and `CloudFileProvider`. - Note: `eventHandler` is not called on main thread, for updating UI. dispatch routine to main thread. - Important: `eventHandler` may be called if file is changed in recursive subpaths of registered path. This may cause negative impact on performance if a root path is being monitored. - Parameters: - path: path of directory. - eventHandler: Closure executed after change, on a secondary thread. */ func registerNotifcation(path: String, eventHandler: @escaping () -> Void) /// Stops monitoring the path. /// /// - Parameter path: path of directory. func unregisterNotifcation(path: String) /// Investigate either the path is registered for change notification or not. /// /// - Parameter path: path of directory. /// - Returns: Directory is being monitored or not. func isRegisteredForNotification(path: String) -> Bool } #if os(macOS) || os(iOS) || os(tvOS) /// Allows undo file operations done by provider public protocol FileProvideUndoable: FileProviderOperations { /// To initialize undo manager either call `setupUndoManager()` or set it manually. /// /// - Note: Only some operations (moving/renaming, copying and creating) are supported for undoing. /// - Note: recording operations will occur after setting this object. var undoManager: UndoManager? { get set } /// UndoManager supports undoing this file operation /// - Parameter handle: determines wheither this progress can be rolled back or not. func canUndo(handle: Progress) -> Bool /// UndoManager supports undoing this operation /// - Parameter operation: determines wheither this operation can be rolled back or not. func canUndo(operation: FileOperationType) -> Bool } extension FileProvideUndoable { public func canUndo(operation: FileOperationType) -> Bool { return undoOperation(for: operation) != nil } public func canUndo(handle: Progress) -> Bool { if let operationType = handle.userInfo[.fileProvderOperationTypeKey] as? FileOperationType { return canUndo(operation: operationType) } return false } /// Reuturns roll back operation for provided `operation`. internal func undoOperation(for operation: FileOperationType) -> FileOperationType? { switch operation { case .create(path: let path): return .remove(path: path) case .modify(path: _): return nil case .copy(source: _, destination: let dest): return .remove(path: dest) case .move(source: let source, destination: let dest): return .move(source: dest, destination: source) case .link(link: let link, target: _): return .remove(path: link) case .remove(path: _): return nil default: return nil } } /// Initiates `self.undoManager` if equals with `nil`, and set `levelsOfUndo` to 10. public func setupUndoManager() { guard self.undoManager == nil else { return } self.undoManager = UndoManager() self.undoManager?.levelsOfUndo = 10 } public func _registerUndo(_ operation: FileOperationType) { #if os(macOS) || os(iOS) || os(tvOS) guard let undoManager = self.undoManager, let undoOp = self.undoOperation(for: operation) else { return } let undoBox = UndoBox(provider: self, operation: operation, undoOperation: undoOp) undoManager.beginUndoGrouping() undoManager.registerUndo(withTarget: undoBox, selector: #selector(UndoBox.doSimpleOperation(_:)), object: undoBox) undoManager.setActionName(operation.actionDescription) undoManager.endUndoGrouping() #endif } } class UndoBox: NSObject { weak var provider: FileProvideUndoable? let operation: FileOperationType let undoOperation: FileOperationType init(provider: FileProvideUndoable, operation: FileOperationType, undoOperation: FileOperationType) { self.provider = provider self.operation = operation self.undoOperation = undoOperation } @objc internal func doSimpleOperation(_ box: UndoBox) { switch self.undoOperation { case .move(source: let source, destination: let dest): _=provider?.moveItem(path: source, to: dest, completionHandler: nil) case .remove(let path): _=provider?.removeItem(path: path, completionHandler: nil) default: break } } } #endif /// This protocol defines method to share a public link with other users public protocol FileProviderSharing { /** Genrates a public url to a file to be shared with other users and can be downloaded without authentication. - Important: In some providers url will be available for a limitied time, determined in `expiration` argument. e.g. Dropbox links will be expired after 4 hours. - Parameters: - to: path of file, including file/directory name. - completionHandler: a closure with result of directory entries or error. - link: a url returned by Dropbox to share. - attribute: a `FileObject` containing the attributes of the item. - expiration: a `Date` object, determines when the public url will expires. - error: Error returned by server. */ func publicLink(to path: String, completionHandler: @escaping (_ link: URL?, _ attribute: FileObject?, _ expiration: Date?, _ error: Error?) -> Void) } //efines protocol for provider allows symbolic link operations. public protocol FileProviderSymbolicLink { /** Creates a symbolic link at the specified path that points to an item at the given path. This method does not traverse symbolic links contained in destination path, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component is a symbolic link, that link is not followed. - Parameters: - symbolicLink: The file path at which to create the new symbolic link. The last component of the path issued as the name of the link. - withDestinationPath: The path that contains the item to be pointed to by the link. In other words, this is the destination of the link. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. */ func create(symbolicLink path: String, withDestinationPath destPath: String, completionHandler: SimpleCompletionHandler) /// Returns the path of the item pointed to by a symbolic link. /// /// - Parameters: /// - path: The path of a file or directory. /// - completionHandler: Returns destination url of given symbolic link, or an `Error` object if it fails. func destination(ofSymbolicLink path: String, completionHandler: @escaping (_ file: FileObject?, _ error: Error?) -> Void) } /// Defines protocol for provider allows all common operations. public protocol FileProvider: FileProviderOperations, FileProviderReadWrite, NSCopying { } internal let pathTrimSet = CharacterSet(charactersIn: " /") extension FileProviderBasic { public var type: String { return Swift.type(of: self).type } public func url(of path: String) -> URL { var rpath: String = path rpath = rpath.addingPercentEncoding(withAllowedCharacters: .filePathAllowed) ?? rpath if let baseURL = baseURL?.absoluteURL { if rpath.hasPrefix("/") { rpath.remove(at: rpath.startIndex) } return URL(string: rpath, relativeTo: baseURL) ?? baseURL } else { return URL(string: rpath) ?? URL(string: "/")! } } public func relativePathOf(url: URL) -> String { // check if url derieved from current base url let relativePath = url.relativePath if !relativePath.isEmpty, url.baseURL == self.baseURL { return (relativePath.removingPercentEncoding ?? relativePath).replacingOccurrences(of: "/", with: "", options: .anchored) } // resolve url string against baseurl guard let baseURL = self.baseURL else { return url.absoluteString } let standardRelativePath = url.absoluteString.replacingOccurrences(of: baseURL.absoluteString, with: "/").replacingOccurrences(of: "/", with: "", options: .anchored) if URLComponents(string: standardRelativePath)?.host?.isEmpty ?? true { return standardRelativePath.removingPercentEncoding ?? standardRelativePath } else { return relativePath.replacingOccurrences(of: "/", with: "", options: .anchored) } } /// Returns a file name supposed to be unique with adding numbers to end of file. /// - Important: It's a synchronous method. Don't use it on main thread. /// - Parameter filePath: supposed path of file which should be examined. public func fileByUniqueName(_ filePath: String) -> String { //assert(!Thread.isMainThread, "\(#function) is not recommended to be executed on Main Thread.") let fileUrl = URL(fileURLWithPath: filePath) let dirPath = fileUrl.deletingLastPathComponent().path let fileName = fileUrl.deletingPathExtension().lastPathComponent let fileExt = fileUrl.pathExtension var result = fileName let group = DispatchGroup() group.enter() self.contentsOfDirectory(path: dirPath) { (contents, error) in var bareFileName = fileName let number = Int(fileName.components(separatedBy: " ").filter { !$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty }.last ?? "noname") if let _ = number { result = fileName.components(separatedBy: " ").filter { !$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty }.dropLast().joined(separator: " ") bareFileName = result } var i = number ?? 2 let similiar = contents.map { $0.url.lastPathComponent.isEmpty ? $0.name : $0.url.lastPathComponent }.filter { $0.hasPrefix(result) } while similiar.contains(result + (!fileExt.isEmpty ? "." + fileExt : "")) { result = "\(bareFileName) \(i)" i += 1 } group.leave() } _ = group.wait(timeout: .now() + 5) let finalFile = result + (!fileExt.isEmpty ? "." + fileExt : "") return dirPath.appendingPathComponent(finalFile) } internal func NotImplemented(_ fn: String = #function, file: StaticString = #file) { assert(false, "\(fn) method is not yet implemented. \(file)") } } /// Define methods to get preview and thumbnail for files or folders public protocol ExtendedFileProvider: FileProviderBasic { /// Returns true if provider supports fetching properties of file like dimensions, duration, etc. /// Usually media or document files support these meta-infotmations. /// /// - Parameter path: path of file. /// - Returns: A `Bool` idicates path can have properties. func propertiesOfFileSupported(path: String) -> Bool /** Fetching properties of file like dimensions, duration, etc. It's variant depending on file type. Images, videos and audio files meta-information will be returned. - Note: `LocalFileInformationGenerator` variables can be set to change default behavior of thumbnail and properties generator of `LocalFileProvider`. - Parameters: - path: path of file. - completionHandler: a closure with result of preview image or error. - propertiesDictionary: A `Dictionary` of proprty keys and values. - keys: An `Array` contains ordering of keys. - error: Error returned by system. */ @discardableResult func propertiesOfFile(path: String, completionHandler: @escaping (_ propertiesDictionary: [String: Any], _ keys: [String], _ error: Error?) -> Void) -> Progress? #if os(macOS) || os(iOS) || os(tvOS) /// Returuns true if thumbnail preview is supported by provider and file type accordingly. /// /// - Parameter path: path of file. /// - Returns: A `Bool` idicates path can have thumbnail. func thumbnailOfFileSupported(path: String) -> Bool /** Generates and returns a thumbnail preview of document asynchronously. The defualt dimension of returned image is different regarding provider type, usually 64x64 pixels. - Parameters: - path: path of file. - completionHandler: a closure with result of preview image or error. - image: `NSImage`/`UIImage` object contains preview. - error: `Error` returned by system. */ @discardableResult func thumbnailOfFile(path: String, completionHandler: @escaping (_ image: ImageClass?, _ error: Error?) -> Void) -> Progress? /** Generates and returns a thumbnail preview of document asynchronously. The defualt dimension of returned image is different regarding provider type, usually 64x64 pixels. Default value used when `dimenstion` is `nil`. - Note: `LocalFileInformationGenerator` variables can be set to change default behavior of thumbnail and properties generator of `LocalFileProvider`. - Parameters: - path: path of file. - dimension: width and height of result preview image. - completionHandler: a closure with result of preview image or error. - image: `NSImage`/`UIImage` object contains preview. - error: `Error` returned by system. */ @discardableResult func thumbnailOfFile(path: String, dimension: CGSize?, completionHandler: @escaping (_ image: ImageClass?, _ error: Error?) -> Void) -> Progress? #endif } #if os(macOS) || os(iOS) || os(tvOS) extension ExtendedFileProvider { @discardableResult public func thumbnailOfFile(path: String, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? { return self.thumbnailOfFile(path: path, dimension: nil, completionHandler: completionHandler) } internal static func convertToImage(pdfData: Data?, page: Int = 1, maxSize: CGSize?) -> ImageClass? { guard let pdfData = pdfData else { return nil } let cfPDFData: CFData = pdfData as CFData if let provider = CGDataProvider(data: cfPDFData), let reference = CGPDFDocument(provider), let pageRef = reference.page(at: page) { return self.convertToImage(pdfPage: pageRef, maxSize: maxSize) } return nil } internal static func convertToImage(pdfURL: URL, page: Int = 1, maxSize: CGSize?) -> ImageClass? { // To accelerate, supporting only local file URL guard pdfURL.isFileURL else { return nil } if let reference = CGPDFDocument(pdfURL as CFURL), let pageRef = reference.page(at: page) { return self.convertToImage(pdfPage: pageRef, maxSize: maxSize) } return nil } private static func convertToImage(pdfPage: CGPDFPage, maxSize: CGSize?) -> ImageClass? { let scale: CGFloat let frame = pdfPage.getBoxRect(CGPDFBox.mediaBox) if let maxSize = maxSize { scale = min(maxSize.width / frame.width, maxSize.height / frame.height) } else { #if os(macOS) scale = NSScreen.main?.backingScaleFactor ?? 1.0 // fetch device is retina or not #else scale = UIScreen.main.scale // fetch device is retina or not #endif } let rect = CGRect(origin: .zero, size: frame.size) let size = CGSize(width: frame.size.width * scale, height: frame.size.height * scale) let transform = pdfPage.getDrawingTransform(CGPDFBox.mediaBox, rect: rect, rotate: 0, preserveAspectRatio: true) #if os(macOS) let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) guard let context = NSGraphicsContext(bitmapImageRep: rep!) else { return nil } NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = context context.cgContext.concatenate(transform) context.cgContext.translateBy(x: 0, y: size.height) context.cgContext.scaleBy(x: scale, y: -scale) context.cgContext.drawPDFPage(pdfPage) let resultingImage = NSImage(size: size) resultingImage.addRepresentation(rep!) return resultingImage #else let handler : (CGContext) -> Void = { context in context.concatenate(transform) context.translateBy(x: 0, y: size.height) context.scaleBy(x: CGFloat(scale), y: CGFloat(-scale)) context.setFillColor(UIColor.white.cgColor) context.fill(rect) context.drawPDFPage(pdfPage) } if #available(iOS 10.0, tvOS 10.0, *) { return UIGraphicsImageRenderer(size: size).image { (rendererContext) in handler(rendererContext.cgContext) } } else { UIGraphicsBeginImageContext(size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.saveGState() handler(context) context.restoreGState() let resultingImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultingImage } #endif } internal static func scaleDown(fileURL: URL, toSize maxSize: CGSize?) -> ImageClass? { guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil) else { return nil } return scaleDown(source: source, toSize: maxSize) } internal static func scaleDown(data: Data, toSize maxSize: CGSize?) -> ImageClass? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return scaleDown(source: source, toSize: maxSize) } internal static func scaleDown(source: CGImageSource, toSize maxSize: CGSize?) -> ImageClass? { let options: [NSString: Any] if let maxSize = maxSize { let pixelSize: CGFloat let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) if let width: CGFloat = ((properties as NSDictionary?)?.object(forKey: kCGImagePropertyPixelWidth) as? CGFloat), let height: CGFloat = ((properties as NSDictionary?)?.object(forKey: kCGImagePropertyPixelHeight) as? CGFloat) { pixelSize = (width / maxSize.width < height / maxSize.height) ? maxSize.width : maxSize.height } else { pixelSize = max(maxSize.width, maxSize.height) } options = [ kCGImageSourceThumbnailMaxPixelSize: pixelSize, kCGImageSourceCreateThumbnailFromImageAlways: true] } else { options = [ kCGImageSourceCreateThumbnailFromImageAlways: true] } guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } #if os(macOS) return ImageClass(cgImage: image, size: .zero) #else return ImageClass(cgImage: image) #endif } } #endif /// Operation type description of file operation, included files path in associated values. public enum FileOperationType: CustomStringConvertible { /// Creating a file or directory in path. case create (path: String) /// Copying a file or directory from source to destination. case copy (source: String, destination: String) /// Moving a file or directory from source to destination. case move (source: String, destination: String) /// Modifying data of a file o in path by writing new data. case modify (path: String) /// Deleting file or directory in path. case remove (path: String) /// Creating a symbolic link or alias to target. case link (link: String, target: String) /// Fetching data in file located in path. case fetch (path: String) public var description: String { switch self { case .create: return "Create" case .copy: return "Copy" case .move: return "Move" case .modify: return "Modify" case .remove: return "Remove" case .link: return "Link" case .fetch: return "Fetch" } } /// present participle of action, like `Copying`. public var actionDescription: String { return description.trimmingCharacters(in: CharacterSet(charactersIn: "e")) + "ing" } /// Path of subjecting file. public var source: String { let reflect = Mirror(reflecting: self).children.first!.value let mirror = Mirror(reflecting: reflect) return reflect as? String ?? mirror.children.first?.value as! String } /// Path of subjecting file. public var path: String? { return source } /// Path of destination file. public var destination: String? { guard let reflect = Mirror(reflecting: self).children.first?.value else { return nil } let mirror = Mirror(reflecting: reflect) return mirror.children.dropFirst().first?.value as? String } init? (json: [String: Any]) { guard let type = json["type"] as? String, let source = json["source"] as? String else { return nil } let dest = json["dest"] as? String switch type { case "Fetch": self = .fetch(path: source) case "Create": self = .create(path: source) case "Modify": self = .modify(path: source) case "Remove": self = .remove(path: source) case "Copy": guard let dest = dest else { return nil } self = .copy(source: source, destination: dest) case "Move": guard let dest = dest else { return nil } self = .move(source: source, destination: dest) case "Link": guard let dest = dest else { return nil } self = .link(link: source, target: dest) default: return nil } } internal var json: String? { var dictionary: [String: Any] = ["type": self.description] dictionary["source"] = source dictionary["dest"] = destination return String(jsonDictionary: dictionary) } } /// Delegate methods for reporting provider's operation result and progress, when it's ready to update /// user interface. /// All methods are called in main thread to avoids UI bugs. public protocol FileProviderDelegate: class { /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation finished with success. /// This method is called in main thread to avoids UI bugs. func fileproviderSucceed(_ fileProvider: FileProviderOperations, operation: FileOperationType) /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation finished with failure. /// This method is called in main thread to avoids UI bugs. func fileproviderFailed(_ fileProvider: FileProviderOperations, operation: FileOperationType, error: Error) /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation progess. /// Supported by some providers, especially remote ones. /// This method is called in main thread to avoids UI bugs. func fileproviderProgress(_ fileProvider: FileProviderOperations, operation: FileOperationType, progress: Float) } /// The `FileOperationDelegate` protocol defines methods for managing operations involving the copying, moving, linking, or removal of files and directories. When you use an `FileProvider` object to initiate a copy, move, link, or remove operation, the file provider asks its delegate whether the operation should begin at all and whether it should proceed when an error occurs. public protocol FileOperationDelegate: class { /// fileProvider(_:shouldOperate:) gives the delegate an opportunity to filter the file operation. Returning true from this method will allow the copy to happen. Returning false from this method causes the item in question to be skipped. If the item skipped was a directory, no children of that directory will be subject of the operation, nor will the delegate be notified of those children. func fileProvider(_ fileProvider: FileProviderOperations, shouldDoOperation operation: FileOperationType) -> Bool /// fileProvider(_:shouldProceedAfterError:copyingItemAtPath:toPath:) gives the delegate an opportunity to recover from or continue copying after an error. If an error occurs, the error object will contain an ErrorType indicating the problem. The source path and destination paths are also provided. If this method returns true, the FileProvider instance will continue as if the error had not occurred. If this method returns false, the NSFileManager instance will stop copying, return false from copyItemAtPath:toPath:error: and the error will be provied there. func fileProvider(_ fileProvider: FileProviderOperations, shouldProceedAfterError error: Error, operation: FileOperationType) -> Bool }
mit
7d4aca26a5f9f630372bdb9490d06bc2
47.912223
566
0.674896
4.956276
false
false
false
false
fs/Social-iOS
@Test/Test/AppDelegate.swift
1
3331
// // AppDelegate.swift // Test // // Created by Vladimir Goncharov on 04.04.16. // Copyright © 2016 FlatStack. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
f1bafd8afe51f48f794b9ac88cb6f20f
53.590164
285
0.765165
6.178108
false
false
false
false
j4nnis/AImageFilters
ImageExperiments/ImagePlayground.swift
1
3849
// // ImagePlayground.swift // ImageExperiments // // Created by Jannis Muething on 05.10.14. // Copyright (c) 2014 Jannis Muething. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics /** It alomost goes without saying: The methods in this file are intented for academic purposes only. If you for example want to do the matrix convolution math yourself or something similar. :imageArray: A NxM matrix of arrays representing the red, green, blue and alpha channel (each gets a value between 0 and 255) :return: The image reference corresponding to the array supplied */ func imageArrayToCgImage(imageArray:[[[UInt8]]]) -> CGImageRef { var colorSpace = CGColorSpaceCreateDeviceRGB() var context = CGBitmapContextCreate(nil, UInt(imageArray[0].count), UInt(imageArray.count), 8, 0, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.toRaw())); for row in 0 ..< imageArray.count { for column in 0 ..< imageArray[0].count { CGContextSetRGBFillColor(context, CGFloat(imageArray[row][column][0]), CGFloat(imageArray[row][column][1]), CGFloat(imageArray[row][column][2]), CGFloat(imageArray[row][column][3])) CGContextFillRect(context, CGRectMake(CGFloat(row), CGFloat(column), 1, 1)) } } return CGBitmapContextCreateImage(context) } /** It alomost goes without saying: The methods in this file are intented for academic purposes only. If you for example want to do the matrix convolution math yourself or something similar. :img: the CGImageRef (UIImage.CGImage gets you one from a UIImage) :return: a NxM matrix of arrays representing the red, green, blue and alpha channel (each gets a value between 0 and 255) */ func cgImageToImageArray(img : CGImageRef) -> [[[UInt8]]] { let inProvider = CGImageGetDataProvider(img) let bitmapData = CGDataProviderCopyData(inProvider) let width = CGImageGetWidth(img) let height = CGImageGetHeight(img) let bytesPerRow = CGImageGetBytesPerRow(img) let bitsPerComponent = CGImageGetBitsPerComponent(img) let bitsPerPixel = CGImageGetBitsPerPixel(img) let bytesPerPixel = bitsPerPixel / bitsPerComponent var dataPtr : UnsafePointer<UInt8> = CFDataGetBytePtr(bitmapData) var rgbaArray = [[[UInt8]]]() for row in (0 ..< height) { rgbaArray.append([]) for column in (0 ..< width) { rgbaArray[Int(row)].append([]) let p = Int(row*bytesPerRow+column*bytesPerPixel) for x : Int in (0 ..< Int(bytesPerPixel)) { let value = dataPtr[p+x] rgbaArray[Int(row)][Int(column)].append(value) } } } return rgbaArray }
mit
a1a12e8236c7bdc028c7c40358ef1dfb
41.307692
193
0.703559
4.55503
false
false
false
false
qiuncheng/CuteAttribute
CuteAttribute/CuteAttribute+Convert.swift
1
1351
// // CuteAttribute+Convert.swift // Cute // // Created by vsccw on 2017/8/10. // Copyright © 2017年 https://vsccw.com. All rights reserved. // import Foundation public extension CuteAttribute { /// `String`, `NSString`, `NSMutableAttributedString` or `NSAttributedString` to `NSMutableAttributedString` /// /// - Parameter str: Any value. /// - Returns: NSMutableAttributedString static func convertToMutableAttributedString(_ str: Any) -> NSMutableAttributedString { let isValid = (str is String) || (str is NSString) || (str is NSAttributedString) || (str is NSMutableAttributedString) assert(isValid, "only support `String`, `NSString`, `NSAttributedString`, `NSMutableAttributedString`.") if let attribuedString = str as? NSMutableAttributedString { return attribuedString } else if let attribuedString = str as? NSAttributedString { return NSMutableAttributedString(attributedString: attribuedString) } else if let string = str as? NSString { return NSMutableAttributedString(string: string as String) } else if let string = str as? String { return NSMutableAttributedString(string: string) } else { return NSMutableAttributedString(string: "") } } }
mit
b712e4f6cdbdc66d76e237a62616c9b2
36.444444
112
0.658754
5.067669
false
false
false
false
gezhixin/MoreThanDrawerMenumDemo
special/BaseFrameWork/baseController/LeftRightMenuRootViewController.swift
1
5041
// // LeftRightMenuRootViewController.swift // special // // Created by 葛枝鑫 on 15/4/17. // Copyright (c) 2015年 葛枝鑫. All rights reserved. // import UIKit let CenterViewOffset : CGFloat = 218 class LeftRightMenuRootViewController: UIViewController, UIGestureRecognizerDelegate { var tapBtn : UIButton! var pan : UIPanGestureRecognizer! var currentCenterViewOffset4Pan : CGFloat = CenterViewOffset // 左边控制器 var leftNavigationController : UINavigationController! { willSet(newLNVC){ if self.leftNavigationController != nil { self.leftNavigationController.view.removeFromSuperview() self.leftNavigationController.removeFromParentViewController() } } didSet{ if self.leftNavigationController != nil { if (self.leftNavigationController.view.superview == nil) { self.addChildViewController(leftNavigationController) self.view.insertSubview(leftNavigationController.view, atIndex:0) } } } } //中间控制器 var centerNavigationController : UINavigationController! { willSet(newCNVC){ if self.centerNavigationController != nil { self.centerNavigationController.view.removeFromSuperview() self.centerNavigationController.removeFromParentViewController() } } didSet { if self.centerNavigationController != nil { if (self.centerNavigationController.view.superview == nil) { self.addChildViewController(centerNavigationController) self.view.insertSubview(centerNavigationController.view, atIndex:1) } } } } var isLeftViewOpened : Bool = false override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() tapBtn = UIButton(frame: UIScreen.mainScreen().bounds) tapBtn.addTarget(self, action: "tapBtnClicked:", forControlEvents: UIControlEvents.TouchUpInside) pan = UIPanGestureRecognizer(target: self, action: "pan:") pan.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func closeLeftView() { isLeftViewOpened = false tapBtn.removeFromSuperview() centerNavigationController.view.removeGestureRecognizer(pan) var c = self.centerNavigationController.view.frame let duration = NSTimeInterval(c.origin.x / CenterViewOffset * 0.45) c.origin.x = 0 UIView.animateWithDuration(duration, delay:0, usingSpringWithDamping:1.0, initialSpringVelocity:1.0, options:UIViewAnimationOptions.AllowUserInteraction,animations:{ self.centerNavigationController.view.frame = c },completion: { (finished: Bool) -> Void in }) } func openLeftView() { isLeftViewOpened = true centerNavigationController.view.addSubview(tapBtn) centerNavigationController.view.addGestureRecognizer(pan) var c = self.centerNavigationController.view.frame let duration = NSTimeInterval((CenterViewOffset - c.origin.x) / CenterViewOffset * 0.45) c.origin.x = CenterViewOffset UIView.animateWithDuration(duration, delay:0, usingSpringWithDamping:0.9, initialSpringVelocity:1.0, options:UIViewAnimationOptions.AllowUserInteraction,animations:{ self.centerNavigationController.view.frame = c ; },completion: { (finished: Bool) -> Void in }) } func menuBtnClicked() { if isLeftViewOpened { self.closeLeftView() } else { self.openLeftView() } } func setCenterViewOffset(offset:CGFloat) { if offset < 0 || offset > CenterViewOffset { return } self.centerNavigationController.view.x = offset } func tapBtnClicked(sender: UIButton) { closeLeftView() } func pan(panGesture: UIPanGestureRecognizer) { let point = panGesture.translationInView(centerNavigationController.view) setCenterViewOffset(currentCenterViewOffset4Pan + point.x) if pan.state == .Ended { closeLeftView() } } //MARK: - Gesture Delegate func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { currentCenterViewOffset4Pan = centerNavigationController.view.frame.origin.x return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { return true } }
mit
7a02a99a14a96dc43b4fca949ad2ab4c
29.907407
173
0.617735
5.478118
false
false
false
false
xedin/swift
stdlib/public/Darwin/Foundation/Pointers+DataProtocol.swift
24
863
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension UnsafeRawBufferPointer : DataProtocol { public var regions: CollectionOfOne<UnsafeRawBufferPointer> { return CollectionOfOne(self) } } extension UnsafeBufferPointer : DataProtocol where Element == UInt8 { public var regions: CollectionOfOne<UnsafeBufferPointer<Element>> { return CollectionOfOne(self) } }
apache-2.0
4c04445d5e29272c9a4554506f23d5ba
34.958333
80
0.604867
5.640523
false
false
false
false
shajrawi/swift
stdlib/public/core/CollectionOfOne.swift
3
5498
//===--- CollectionOfOne.swift - A Collection with one element ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection containing a single element. /// /// You can use a `CollectionOfOne` instance when you need to efficiently /// represent a single value as a collection. For example, you can add a /// single element to an array by using a `CollectionOfOne` instance with the /// concatenation operator (`+`): /// /// let a = [1, 2, 3, 4] /// let toAdd = 100 /// let b = a + CollectionOfOne(toAdd) /// // b == [1, 2, 3, 4, 100] @_fixed_layout // trivial-implementation public struct CollectionOfOne<Element> { @usableFromInline // trivial-implementation internal var _element: Element /// Creates an instance containing just the given element. /// /// - Parameter element: The element to store in the collection. @inlinable // trivial-implementation public init(_ element: Element) { self._element = element } } extension CollectionOfOne { /// An iterator that produces one or zero instances of an element. /// /// `IteratorOverOne` is the iterator for the `CollectionOfOne` type. @_fixed_layout // trivial-implementation public struct Iterator { @usableFromInline // trivial-implementation internal var _elements: Element? /// Construct an instance that generates `_element!`, or an empty /// sequence if `_element == nil`. @inlinable // trivial-implementation public // @testable init(_elements: Element?) { self._elements = _elements } } } extension CollectionOfOne.Iterator: IteratorProtocol { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. @inlinable // trivial-implementation public mutating func next() -> Element? { let result = _elements _elements = nil return result } } extension CollectionOfOne: RandomAccessCollection, MutableCollection { public typealias Index = Int public typealias Indices = Range<Int> public typealias SubSequence = Slice<CollectionOfOne<Element>> /// The position of the first element. /// /// In a `CollectionOfOne` instance, `startIndex` is always `0`. @inlinable // trivial-implementation public var startIndex: Index { return 0 } /// The "past the end" position---that is, the position one greater than the /// last valid subscript argument. /// /// In a `CollectionOfOne` instance, `endIndex` is always `1`. @inlinable // trivial-implementation public var endIndex: Index { return 1 } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be `0`. /// - Returns: The index value immediately after `i`. @inlinable // trivial-implementation public func index(after i: Index) -> Index { _precondition(i == startIndex) return 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be `1`. /// - Returns: The index value immediately before `i`. @inlinable // trivial-implementation public func index(before i: Index) -> Index { _precondition(i == endIndex) return 0 } /// Returns an iterator over the elements of this collection. /// /// - Complexity: O(1) @inlinable // trivial-implementation public __consuming func makeIterator() -> Iterator { return Iterator(_elements: _element) } /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. The only /// valid position in a `CollectionOfOne` instance is `0`. @inlinable // trivial-implementation public subscript(position: Int) -> Element { _read { _precondition(position == 0, "Index out of range") yield _element } _modify { _precondition(position == 0, "Index out of range") yield &_element } } @inlinable // trivial-implementation public subscript(bounds: Range<Int>) -> SubSequence { get { _failEarlyRangeCheck(bounds, bounds: 0..<1) return Slice(base: self, bounds: bounds) } set { _failEarlyRangeCheck(bounds, bounds: 0..<1) let n = newValue.count _precondition(bounds.count == n, "CollectionOfOne can't be resized") if n == 1 { self = newValue.base } } } /// The number of elements in the collection, which is always one. @inlinable // trivial-implementation public var count: Int { return 1 } } extension CollectionOfOne : CustomDebugStringConvertible { /// A textual representation of the collection, suitable for debugging. public var debugDescription: String { return "CollectionOfOne(\(String(reflecting: _element)))" } } extension CollectionOfOne : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["element": _element]) } }
apache-2.0
2219d3658d92f5f123bdc6d9c9f2ea7d
30.965116
80
0.665151
4.441034
false
false
false
false
wenjunos/DYZB
斗鱼/斗鱼/Classes/Home/View/DYAmuseMenuView.swift
1
2918
// // DYAmuseMenuView.swift // 斗鱼 // // Created by pba on 2017/2/13. // Copyright © 2017年 wenjun. All rights reserved. // 娱乐界面的顶部菜单 import UIKit private let menuViewCellID = "menuViewCellID" class DYAmuseMenuView: UIView { // MARK: - 控件属性 @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var collectionView: UICollectionView! // MARK: - 定义的属性 var AnchorGroups : [DYAnchorGroupModel]? { didSet { collectionView.reloadData() } } // MARK: - 系统回调 override func awakeFromNib() { collectionView.dataSource = self collectionView.delegate = self //注册cell collectionView.register(UINib(nibName: "DYAmuseMenuCell", bundle: nil), forCellWithReuseIdentifier: menuViewCellID) } override func layoutSubviews() { super.layoutSubviews() //设置布局 let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } // MARK: - 快速创建方法 extension DYAmuseMenuView { class func menuView() -> DYAmuseMenuView { return Bundle.main.loadNibNamed("DYAmuseMenuView", owner: nil, options: nil)?.first as! DYAmuseMenuView } } // MARK: - UICollectionViewDataSource extension DYAmuseMenuView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if AnchorGroups == nil { return 0 } let page = (AnchorGroups!.count-1) / 8 + 1 //设置pageControl的页数 pageControl.numberOfPages = page return page } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: menuViewCellID, for: indexPath) as! DYAmuseMenuCell //设置cell的数据 setCellData(cell: cell, indexPath: indexPath) return cell } //设置cell的数据 func setCellData(cell : DYAmuseMenuCell, indexPath : IndexPath){ //1.计算开始位置和结束位置 //0~7 //8~15 //16~23 let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 //2.防止越界 if endIndex > AnchorGroups!.count - 1 { endIndex = AnchorGroups!.count - 1 } //3.赋值 cell.AnchorGroups = Array(AnchorGroups![startIndex...endIndex]) } } // MARK: - UICollectionViewDelegate extension DYAmuseMenuView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { //设置pageControl的当前页 pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
mit
4952fa6115ffa55405e0893c72f74e79
29.076087
126
0.653054
4.729915
false
false
false
false
actorapp/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/iOSNotificationProvider.swift
2
2544
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import AVFoundation import AudioToolbox.AudioServices @objc class iOSNotificationProvider: NSObject, ACNotificationProvider { var isLoaded = false var internalMessage:SystemSoundID = 0 var sounds: [String: SystemSoundID] = [:] var lastSoundPlay: Double = 0 override init() { super.init() } func loadSound(_ soundFile:String? = ""){ if !isLoaded { isLoaded = true var path = Bundle.framework.url(forResource: "notification", withExtension: "caf") if let fileURL: URL = URL(fileURLWithPath: "/Library/Ringtones/\(soundFile)") { path = fileURL } AudioServicesCreateSystemSoundID(path! as CFURL, &internalMessage) } } func onMessageArriveInApp(with messenger: ACMessenger!) { let currentTime = Date().timeIntervalSinceReferenceDate if (currentTime - lastSoundPlay > 0.2) { let peer = ACPeer.user(with: jint(messenger.myUid())) let soundFileSting = messenger.getNotificationsSound(with: peer) loadSound(soundFileSting) AudioServicesPlaySystemSound(internalMessage) lastSoundPlay = currentTime } } func onNotification(with messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) { // Not Supported } func onUpdateNotification(with messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) { // Not Supported } func hideAllNotifications() { dispatchOnUi { () -> Void in // Clearing notifications if let number = Actor.getGlobalState().globalCounter.get() { UIApplication.shared.applicationIconBadgeNumber = 0 // If current value will equals to number + 1 UIApplication.shared.applicationIconBadgeNumber = number.intValue + 1 UIApplication.shared.applicationIconBadgeNumber = number.intValue } else { UIApplication.shared.applicationIconBadgeNumber = 0 } // Clearing local notifications UIApplication.shared.cancelAllLocalNotifications() } } }
agpl-3.0
d6ab4c2c9044ed0170f13c919c3bc939
35.869565
203
0.64033
5.506494
false
false
false
false
cclovett/iRemeber
iRemeber/Pods/Bits/Sources/Bits/Byte+Random.swift
2
883
#if os(Linux) @_exported import Glibc #else @_exported import Darwin.C #endif extension Byte { private static let max32 = UInt32(Byte.max) /** Create a single random byte */ public static func randomByte() -> Byte { #if os(Linux) let val = Byte(Glibc.random() % Int(max32)) #else let val = Byte(arc4random_uniform(max32)) #endif return val } } extension UnsignedInteger { /** Return a random value for the given type. This should NOT be considered cryptographically secure. */ public static func random() -> Self { let size = MemoryLayout<Self>.size var bytes: [Byte] = [] (1...size).forEach { _ in let randomByte = Byte.randomByte() bytes.append(randomByte) } return Self(bytes: bytes) } }
mit
15553d5887e192cbefa424e508c7f2cd
22.864865
63
0.563986
4.126168
false
false
false
false
appsquickly/Typhoon-Swift-Example
PocketForecast/Model/ForecastConditions.swift
1
2210
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class ForecastConditions : NSObject, NSCoding { private(set) var date : Date? private(set) var low : Temperature? private(set) var high : Temperature? private(set) var summary : String private(set) var imageUri : String public init(date : Date, low : Temperature?, high : Temperature?, summary : String, imageUri : String) { self.date = date self.low = low self.high = high self.summary = summary self.imageUri = imageUri } public required init?(coder : NSCoder) { self.date = coder.decodeObject(forKey: "date") as? Date self.low = coder.decodeObject(forKey: "low") as? Temperature self.high = coder.decodeObject(forKey: "high") as? Temperature self.summary = coder.decodeObject(forKey: "summary") as! String self.imageUri = coder.decodeObject(forKey: "imageUri") as! String } public func longDayOfTheWeek() -> String? { let formatter = DateFormatter() formatter.dateFormat = "EEEE" return formatter.string(from: self.date!) } public override var description: String { if self.low != nil && self.high != nil { return String(format: "Forecast : day=%@, low=%@, high=%@", self.longDayOfTheWeek()!, self.low!, self.high!) } else { return String(format: "Forecast : day=%@, low=%@, high=%@", self.longDayOfTheWeek()!, "", "") } } public func encode(with coder: NSCoder) { coder.encode(self.date, forKey:"date") coder.encode(self.low, forKey:"low") coder.encode(self.high, forKey:"high") coder.encode(self.summary, forKey:"summary") coder.encode(self.imageUri, forKey:"imageUri") } }
apache-2.0
e94d88f83bf10fac67e70760306a594f
35.229508
120
0.579638
4.40239
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/TouchesViewController.swift
1
4069
// // TouchesViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/23/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class TouchesViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white // draggable view let v0 = MyEventView0() v0.backgroundColor = UIColor.gray v0.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(v0) v0.widthAnchor.constraint(equalToConstant: 100).isActive = true v0.heightAnchor.constraint(equalToConstant: 100).isActive = true v0.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 5).isActive = true v0.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10).isActive = true let label0 = UILabel() label0.text = "Draggable" v0.addSubview(label0) label0.translatesAutoresizingMaskIntoConstraints = false label0.centerXAnchor.constraint(equalTo: v0.centerXAnchor, constant: 0).isActive = true label0.centerYAnchor.constraint(equalTo: v0.centerYAnchor, constant: 0).isActive = true // draggable h/v let v1 = MyEventView1() v1.backgroundColor = UIColor.red v1.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(v1) v1.widthAnchor.constraint(equalToConstant: 100).isActive = true v1.heightAnchor.constraint(equalToConstant: 100).isActive = true v1.topAnchor.constraint(equalTo: v0.bottomAnchor, constant: 10).isActive = true v1.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true let label1 = UILabel() label1.text = "Draggable Horiz/Vert" v1.addSubview(label1) label1.translatesAutoresizingMaskIntoConstraints = false label1.centerXAnchor.constraint(equalTo: v1.centerXAnchor, constant: 0).isActive = true label1.centerYAnchor.constraint(equalTo: v1.centerYAnchor, constant: 0).isActive = true // single/Double tap let v2 = MyEventView2() v2.backgroundColor = UIColor.green v2.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(v2) v2.widthAnchor.constraint(equalToConstant: 100).isActive = true v2.heightAnchor.constraint(equalToConstant: 100).isActive = true v2.topAnchor.constraint(equalTo: v1.bottomAnchor, constant: 10).isActive = true v2.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10).isActive = true let label2 = UILabel() label2.text = "Sing/Doub Tap" v2.addSubview(label2) label2.translatesAutoresizingMaskIntoConstraints = false label2.centerXAnchor.constraint(equalTo: v2.centerXAnchor, constant: 0).isActive = true label2.centerYAnchor.constraint(equalTo: v2.centerYAnchor, constant: 0).isActive = true // Both let v3 = MyEventView3() v3.backgroundColor = UIColor.yellow v3.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(v3) v3.widthAnchor.constraint(equalToConstant: 100).isActive = true v3.heightAnchor.constraint(equalToConstant: 100).isActive = true v3.topAnchor.constraint(equalTo: v2.bottomAnchor, constant: 10).isActive = true v3.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true let label3 = UILabel() label3.text = "Both" v3.addSubview(label3) label3.translatesAutoresizingMaskIntoConstraints = false label3.centerXAnchor.constraint(equalTo: v3.centerXAnchor).isActive = true label3.centerYAnchor.constraint(equalTo: v3.centerYAnchor).isActive = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
c16bad4e4d0f9d4d8e814f933eadf9e8
42.741935
103
0.687316
4.607022
false
false
false
false
kstaring/swift
test/SILGen/objc_metatypes.swift
4
2248
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo @objc class ObjCClass {} class A { // CHECK-LABEL: sil hidden @_TFC14objc_metatypes1A3foo // CHECK-LABEL: sil hidden [thunk] @_TToFC14objc_metatypes1A3foofMCS_9ObjCClassMS1_ dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type { // CHECK: bb0([[M:%[0-9]+]] : $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A // CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type // CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @_TFC14objc_metatypes1A3foo // CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[SELF_COPY]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type // CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type // CHECK: } // end sil function '_TToFC14objc_metatypes1A3foofMCS_9ObjCClassMS1_' return m } // CHECK-LABEL: sil hidden @_TZFC14objc_metatypes1A3bar // CHECK-LABEL: sil hidden [thunk] @_TToZFC14objc_metatypes1A3bar // CHECK: bb0([[SELF:%[0-9]+]] : $@objc_metatype A.Type): // CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type // CHECK: [[BAR:%[0-9]+]] = function_ref @_TZFC14objc_metatypes1A3bar // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> () // CHECK-NEXT: return [[RESULT]] : $() dynamic class func bar() { } dynamic func takeGizmo(_ g: Gizmo.Type) { } // CHECK-LABEL: sil hidden @_TFC14objc_metatypes1A7callFoo func callFoo() { // Make sure we peephole Type/thick_to_objc_metatype. // CHECK-NOT: thick_to_objc_metatype // CHECK: metatype $@objc_metatype ObjCClass.Type foo(ObjCClass.self) // CHECK: return } }
apache-2.0
6b143fabf995cc67ebb3c2ed4e88c6fc
46.829787
182
0.637011
3.197724
false
false
false
false
pascaljette/PokeBattleDemo
PokeBattleDemo/PokeBattleDemo/PokeApi/Base/PokeApiRequestWithPath.swift
1
2488
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // 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 /// A request where we provide only the API path. This is useful for static APIs /// define in the app itself where we don't want/need to provide the base url string. protocol PokeApiRequestWithPath : PokeApiRequestBase { /// Path of the function to call. var apiPath: String { get } } extension PokeApiRequestWithPath { /// Build absolute url based on all url components in the type. var absoluteUrl: NSURL? { let baseUrlString = GlobalConstants.POKEAPI_BASE_URL guard let url: NSURL = NSURL(string: baseUrlString) else { print("Could not form url from string \(baseUrlString)") return nil; } guard let components: NSURLComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: true) else { print("Could not find URL components from string \(baseUrlString)") return nil } // NSURLComponents does not get fully initialized, even passing a NSURL in its constructor. // We must do it manually. There might be a better way (XCode 7.3) components.scheme = url.scheme components.host = url.host components.path = apiPath components.queryItems = queryItems return components.URL } }
mit
d155e3426d14e2049853c5df32d09fcd
39.786885
111
0.69172
4.821705
false
false
false
false
OpenKitten/MongoKitten
Sources/MongoKittenCore/QueryPrimitives/QueryBuilder.swift
2
5095
import BSON public func ==(lhs: String, rhs: Primitive?) -> Document { return [ lhs: [ "$eq": rhs ?? Null() ] as Document ] } public func !=(lhs: String, rhs: Primitive?) -> Document { return [ lhs: [ "$ne": rhs ?? Null() ] as Document ] } public prefix func !(rhs: Primitive?) -> Document { return [ "$not": rhs ?? Null() ] } public func > (lhs: String, rhs: Primitive) -> Document { return [ lhs: [ "$gt": rhs ] as Document ] } public func < (lhs: String, rhs: Primitive) -> Document { return [ lhs: [ "$lt": rhs ] as Document ] } public func >= (lhs: String, rhs: Primitive) -> Document { return [ lhs: [ "$gte": rhs ] as Document ] } public func <= (lhs: String, rhs: Primitive) -> Document { return [ lhs: [ "$lte": rhs ] as Document ] } public protocol MongoKittenQuery { func makeDocument() -> Document } // MARK: && public struct AndQuery: MongoKittenQuery { private enum CodingKeys: String, CodingKey { case conditions = "$and" } public var conditions: [Document] public init(conditions: [Document]) { self.conditions = conditions } public func makeDocument() -> Document { switch conditions.count { case 0: return [:] case 1: return conditions[0] default: return ["$and": Document(array: conditions)] } } } public func && (lhs: AndQuery, rhs: MongoKittenQuery) -> AndQuery { return AndQuery(conditions: lhs.conditions + [rhs.makeDocument()]) } public func && (lhs: MongoKittenQuery, rhs: AndQuery) -> AndQuery { return AndQuery(conditions: [lhs.makeDocument()] + rhs.conditions) } public func && (lhs: AndQuery, rhs: AndQuery) -> AndQuery { return AndQuery(conditions: lhs.conditions + rhs.conditions) } public func && (lhs: MongoKittenQuery, rhs: MongoKittenQuery) -> AndQuery { return AndQuery(conditions: [lhs.makeDocument(), rhs.makeDocument()]) } public func && (lhs: Document, rhs: MongoKittenQuery) -> AndQuery { return AndQuery(conditions: [lhs, rhs.makeDocument()]) } public func && (lhs: MongoKittenQuery, rhs: Document) -> AndQuery { return AndQuery(conditions: [lhs.makeDocument(), rhs]) } public func && (lhs: Document, rhs: Document) -> AndQuery { return AndQuery(conditions: [lhs, rhs]) } public func && (lhs: AndQuery, rhs: Document) -> AndQuery { return AndQuery(conditions: lhs.conditions + [rhs]) } public func && (lhs: Document, rhs: AndQuery) -> AndQuery { return AndQuery(conditions: [lhs] + rhs.conditions) } // MARK: || public struct OrQuery: MongoKittenQuery { private enum CodingKeys: String, CodingKey { case conditions = "$or" } public var conditions: [Document] public init(conditions: [Document]) { self.conditions = conditions } public func makeDocument() -> Document { switch conditions.count { case 0: return [:] case 1: return conditions[0] default: return ["$or": Document(array: conditions)] } } } public func || (lhs: OrQuery, rhs: MongoKittenQuery) -> OrQuery { return OrQuery(conditions: lhs.conditions + [rhs.makeDocument()]) } public func || (lhs: MongoKittenQuery, rhs: OrQuery) -> OrQuery { return OrQuery(conditions: [lhs.makeDocument()] + rhs.conditions) } public func || (lhs: OrQuery, rhs: OrQuery) -> OrQuery { return OrQuery(conditions: lhs.conditions + rhs.conditions) } public func || (lhs: MongoKittenQuery, rhs: MongoKittenQuery) -> OrQuery { return OrQuery(conditions: [lhs.makeDocument(), rhs.makeDocument()]) } public func || (lhs: Document, rhs: MongoKittenQuery) -> OrQuery { return OrQuery(conditions: [lhs, rhs.makeDocument()]) } public func || (lhs: MongoKittenQuery, rhs: Document) -> OrQuery { return OrQuery(conditions: [lhs.makeDocument(), rhs]) } public func || (lhs: Document, rhs: Document) -> OrQuery { return OrQuery(conditions: [lhs, rhs]) } public func || (lhs: OrQuery, rhs: Document) -> OrQuery { return OrQuery(conditions: lhs.conditions + [rhs]) } public func || (lhs: Document, rhs: OrQuery) -> OrQuery { return OrQuery(conditions: [lhs] + rhs.conditions) } // MARK: &= public func &= (lhs: inout AndQuery, rhs: AndQuery) { lhs.conditions.append(contentsOf: rhs.conditions) } public func &= (lhs: inout AndQuery, rhs: MongoKittenQuery) { lhs.conditions.append(rhs.makeDocument()) } public func &= (lhs: inout AndQuery, rhs: Document) { lhs.conditions.append(rhs) } // MARK: |= public func |= (lhs: inout OrQuery, rhs: OrQuery) { lhs.conditions.append(contentsOf: rhs.conditions) } public func |= (lhs: inout OrQuery, rhs: MongoKittenQuery) { lhs.conditions.append(rhs.makeDocument()) } public func |= (lhs: inout OrQuery, rhs: Document) { lhs.conditions.append(rhs) }
mit
2b3744715ca3c03e7fac9c3f33a20526
23.37799
75
0.613346
3.708151
false
false
false
false
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Home/Presenter/FunnyPresenter.swift
1
1086
// // FunnyPresenter.swift // MSDouYuZB // // Created by jiayuan on 2017/8/9. // Copyright © 2017年 mrsong. All rights reserved. // import Foundation class FunnyPresenter: BaseTVCateVCDataSource { lazy var tvCateArr = [TVCate]() func requestFunnyData(responseCallback: (() -> ())? = nil ) { NetworkTools.get(urlString: "http://capi.douyucdn.cn/api/v1/getColumnRoom/3", parameters: ["limit": 30, "offset": 0]) { (result) in // 将 result 转成字典 guard let responseData = result as? [String: Any] else { return } // 获取字典里的 data 数据 guard let dataArray = responseData["data"] as? [[String: NSObject]] else { return } // 遍历数组里的字典,转成 model 对象 let cate = TVCate() for dict in dataArray { cate.roomArr.append(TVRoom(dict: dict)) } self.tvCateArr.append(cate) // 回调 if let callback = responseCallback { callback() } } } }
mit
f999f6e0db7ad8c18f276775d016184b
29.205882
139
0.555015
3.98062
false
false
false
false
russbishop/swift
test/Interpreter/SDK/objc_bridge_cast.swift
1
6158
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // Test dynamic casts that bridge value types through the runtime. import Foundation func genericForcedCast<T, U>(_ a: T) -> U { return a as! U } func genericConditionalCast<T, U>(_ a: T) -> U? { return a as? U } func testForcedValueToObjectBridging() { // CHECK: ---Forced value to object bridging--- print("---Forced value to object bridging---") let array: [String] = ["Hello", "World"] // Forced bridging (exact) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) print(genericForcedCast(array) as NSArray) // Forced bridging (superclass) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) print(genericForcedCast(array) as NSObject) // Forced bridging (AnyObject) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) print(genericForcedCast(array) as NSObject) // Forced bridging (existential success) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) print(genericForcedCast(array) as NSCoding) print("Done") } // CHECK: Done testForcedValueToObjectBridging() func testConditionalValueToObjectBridging() { // CHECK: ---Conditional value to object bridging--- print("---Conditional value to object bridging---") let array: [String] = ["Hello", "World"] // Conditional bridging (exact) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) if let nsArray = (genericConditionalCast(array) as NSArray?) { print("\(nsArray)") } else { print("Not an NSArray") } // Conditional bridging (superclass) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) if let nsObject = (genericConditionalCast(array) as NSObject?) { print("\(nsObject)") } else { print("Not an NSObject") } // Conditional bridging (AnyObject) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) if let anyObject = (genericConditionalCast(array) as AnyObject?) { print("\(anyObject)") } else { print("Not an AnyObject") } // Conditional bridging (existential success) // CHECK-NEXT: ( // CHECK-NEXT: Hello, // CHECK-NEXT: World // CHECK-NEXT: ) if let coding = (genericConditionalCast(array) as NSCoding?) { print("\(coding)") } else { print("Not an NSCoding") } // CHECK-NEXT: XMLParserDelegate if let delegate = (genericConditionalCast(array) as XMLParserDelegate?) { print("\(delegate)") } else { print("Not an XMLParserDelegate") } // Conditional bridging (unrelated class) // CHECK-NEXT: Not an NSString if let nsString = (genericConditionalCast(array) as NSString?) { print("\(nsString)") } else { print("Not an NSString") } print("Done") } // CHECK: Done testConditionalValueToObjectBridging() func testForcedObjectToValueBridging() { // CHECK: ---Forced object to value bridging--- print("---Forced object to value bridging---") let nsArray: NSArray = ["Hello", "World"] // Forced bridging (exact) // CHECK: ["Hello", "World"] print(genericForcedCast(nsArray) as [String]) // Forced bridging (superclass) // CHECK: ["Hello", "World"] let nsObject: NSObject = nsArray print(genericForcedCast(nsObject) as [String]) // Forced bridging (AnyObject) // CHECK: ["Hello", "World"] let anyObject: AnyObject = nsArray print(genericForcedCast(anyObject) as [String]) // Forced bridging (existential success) let nsCoding: NSCoding = nsArray print(genericForcedCast(nsCoding) as [String]) print("Done") } // CHECK: Done testForcedObjectToValueBridging() func testConditionalObjectToValueBridging() { // CHECK: ---Conditional object to value bridging--- print("---Conditional object to value bridging---") let nsArray: NSArray = ["Hello", "World"] let nsObject: NSObject = nsArray let anyObject: AnyObject = nsArray let nsCoding: NSCoding = nsArray let nsString: NSString = "Hello" // Conditional bridging (exact) // CHECK: ["Hello", "World"] if let arr = (genericConditionalCast(nsArray) as [String]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (superclass) // CHECK: ["Hello", "World"] if let arr = (genericConditionalCast(nsObject) as [String]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (AnyObject) // CHECK: ["Hello", "World"] if let arr = (genericConditionalCast(anyObject) as [String]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (existential success) // CHECK: ["Hello", "World"] if let arr = (genericConditionalCast(nsCoding) as [String]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (existential failure) // Not a [Int] if let arr = (genericConditionalCast(nsCoding) as [Int]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (unrelated class type) // CHECK: Not a [String] if let arr = (genericConditionalCast(nsString) as [String]?) { print(arr) } else { print("Not a [String]") } // Conditional bridging (unrelated element type) // CHECK: Not a [Int] if let arr = (genericConditionalCast(nsArray) as [Int]?) { print(arr) } else { print("Not a [Int]") } print("Done") } // CHECK: Done testConditionalObjectToValueBridging() // rdar://problem/22587077 class Canary: NSObject { deinit { print("died") } } var CanaryAssocObjectHandle = 0 func testValueToObjectBridgingInSwitch() { autoreleasepool { let string = "hello" let nsString = string as NSString objc_setAssociatedObject(nsString, &CanaryAssocObjectHandle, Canary(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) switch nsString as AnyObject { case let s as String: print("Got string \(s)") default: print("Not a string") } } print("Done") } // CHECK: died // CHECK: Done testValueToObjectBridgingInSwitch()
apache-2.0
046ee6ac0b779f680e22ee93c0c1570f
23.339921
75
0.648912
3.805933
false
false
false
false
lacklock/ReactiveCocoaExtension
Pods/ReactiveSwift/Sources/Observer.swift
6
2613
// // Observer.swift // ReactiveSwift // // Created by Andy Matuschak on 10/2/15. // Copyright © 2015 GitHub. All rights reserved. // /// A protocol for type-constrained extensions of `Observer`. public protocol ObserverProtocol { associatedtype Value associatedtype Error: Swift.Error /// Puts a `value` event into `self`. func send(value: Value) /// Puts a failed event into `self`. func send(error: Error) /// Puts a `completed` event into `self`. func sendCompleted() /// Puts an `interrupted` event into `self`. func sendInterrupted() } /// An Observer is a simple wrapper around a function which can receive Events /// (typically from a Signal). public final class Observer<Value, Error: Swift.Error> { public typealias Action = (Event<Value, Error>) -> Void /// An action that will be performed upon arrival of the event. public let action: Action /// An initializer that accepts a closure accepting an event for the /// observer. /// /// - parameters: /// - action: A closure to lift over received event. public init(_ action: @escaping Action) { self.action = action } /// An initializer that accepts closures for different event types. /// /// - parameters: /// - value: Optional closure executed when a `value` event is observed. /// - failed: Optional closure that accepts an `Error` parameter when a /// failed event is observed. /// - completed: Optional closure executed when a `completed` event is /// observed. /// - interruped: Optional closure executed when an `interrupted` event is /// observed. public convenience init( value: ((Value) -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil ) { self.init { event in switch event { case let .value(v): value?(v) case let .failed(error): failed?(error) case .completed: completed?() case .interrupted: interrupted?() } } } } extension Observer: ObserverProtocol { /// Puts a `value` event into `self`. /// /// - parameters: /// - value: A value sent with the `value` event. public func send(value: Value) { action(.value(value)) } /// Puts a failed event into `self`. /// /// - parameters: /// - error: An error object sent with failed event. public func send(error: Error) { action(.failed(error)) } /// Puts a `completed` event into `self`. public func sendCompleted() { action(.completed) } /// Puts an `interrupted` event into `self`. public func sendInterrupted() { action(.interrupted) } }
mit
995c694296099819a34e883ba45759a8
24.115385
78
0.650077
3.578082
false
false
false
false
benlangmuir/swift
test/Distributed/distributed_protocol_isolation.swift
5
12632
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -strict-concurrency=targeted -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed import Distributed import FakeDistributedActorSystems /// Use the existential wrapper as the default actor system. typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ----------------------------------------------------------------------- // MARK: Distributed actor protocols protocol WrongDistFuncs { distributed func notDistActor() // expected-error{{'distributed' method can only be declared within 'distributed actor'}}{{5-17=}} {{25-25=: DistributedActor}} } protocol DistProtocol: DistributedActor { // FIXME(distributed): avoid issuing these warnings, these originate from the call on the DistProtocol where we marked this func as dist isolated, func local() -> String // (the note appears a few times, because we misuse the call many times) // expected-note@-2{{distributed actor-isolated instance method 'local()' declared here}} // expected-note@-3{{distributed actor-isolated instance method 'local()' declared here}} // expected-note@-4{{distributed actor-isolated instance method 'local()' declared here}} distributed func dist() -> String distributed func dist(string: String) -> String distributed func distAsync() async -> String distributed func distThrows() throws -> String distributed func distAsyncThrows() async throws -> String } distributed actor SpecificDist: DistProtocol { nonisolated func local() -> String { "hi" } distributed func dist() -> String { "dist!" } distributed func dist(string: String) -> String { string } distributed func distAsync() async -> String { "dist!" } distributed func distThrows() throws -> String { "dist!" } distributed func distAsyncThrows() async throws -> String { "dist!" } func inside() async throws { _ = self.local() // ok _ = self.dist() // ok _ = self.dist(string: "") // ok _ = await self.distAsync() // ok _ = try self.distThrows() // ok _ = try await self.distAsyncThrows() // ok } } func outside_good(dp: SpecificDist) async throws { _ = dp.local() _ = try await dp.dist() // implicit async throws _ = try await dp.dist(string: "") // implicit async throws _ = try await dp.distAsync() // implicit throws _ = try await dp.distThrows() // implicit async _ = try await dp.distAsyncThrows() // ok } func outside_good_generic<DP: DistProtocol>(dp: DP) async throws { _ = dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} _ = await dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} // the below warning is expected because we don't apply the "implicitly async" to the not-callable func // expected-warning@-2{{no 'async' operations occur within 'await' expression}} _ = try dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} // the below warning is expected because we don't apply the "implicitly throwing" to the not-callable func // expected-warning@-2{{no calls to throwing functions occur within 'try' expression}} _ = try await dp.dist() // implicit async throws _ = try await dp.dist(string: "") // implicit async throws _ = try await dp.distAsync() // implicit throws _ = try await dp.distThrows() // implicit async _ = try await dp.distAsyncThrows() // ok } func outside_good_ext<DP: DistProtocol>(dp: DP) async throws { _ = try await dp.dist() // implicit async throws _ = try await dp.dist(string: "") // implicit async throws _ = try await dp.distAsync() // implicit throws _ = try await dp.distThrows() // implicit async _ = try await dp.distAsyncThrows() // ok } // ==== ------------------------------------------------------------------------ // MARK: General protocols implemented by distributed actors /// A distributed actor could only conform to this by making everything 'nonisolated': protocol StrictlyLocal { func local() // expected-note@-1 2{{mark the protocol requirement 'local()' 'async throws' to allow actor-isolated conformances}}{{15-15= async throws}} func localThrows() throws // expected-note@-1 2{{mark the protocol requirement 'localThrows()' 'async' to allow actor-isolated conformances}}{{22-22=async }} func localAsync() async // expected-note@-1 2{{mark the protocol requirement 'localAsync()' 'throws' to allow actor-isolated conformances}} } distributed actor Nope1_StrictlyLocal: StrictlyLocal { func local() {} // expected-error@-1{{distributed actor-isolated instance method 'local()' cannot be used to satisfy nonisolated protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'local()' to make this instance method not isolated to the actor}} func localThrows() throws {} // expected-error@-1{{distributed actor-isolated instance method 'localThrows()' cannot be used to satisfy nonisolated protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'localThrows()' to make this instance method not isolated to the actor}} func localAsync() async {} // expected-error@-1{{distributed actor-isolated instance method 'localAsync()' cannot be used to satisfy nonisolated protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'localAsync()' to make this instance method not isolated to the actor}} } distributed actor Nope2_StrictlyLocal: StrictlyLocal { distributed func local() {} // expected-error@-1{{actor-isolated distributed instance method 'local()' cannot be used to satisfy nonisolated protocol requirement}} distributed func localThrows() throws {} // expected-error@-1{{actor-isolated distributed instance method 'localThrows()' cannot be used to satisfy nonisolated protocol requirement}} distributed func localAsync() async {} // expected-error@-1{{actor-isolated distributed instance method 'localAsync()' cannot be used to satisfy nonisolated protocol requirement}} } distributed actor OK_StrictlyLocal: StrictlyLocal { nonisolated func local() {} nonisolated func localThrows() throws {} nonisolated func localAsync() async {} } protocol Server { func send<Message: Codable & Sendable>(message: Message) async throws -> String } actor MyServer : Server { func send<Message: Codable & Sendable>(message: Message) throws -> String { "" } // OK } protocol AsyncThrowsAll { func maybe(param: String, int: Int) async throws -> Int // expected-note@-1{{'maybe(param:int:)' declared here}} } actor LocalOK_AsyncThrowsAll: AsyncThrowsAll { func maybe(param: String, int: Int) async throws -> Int { 1111 } } actor LocalOK_ImplicitlyThrows_AsyncThrowsAll: AsyncThrowsAll { func maybe(param: String, int: Int) async -> Int { 1111 } } actor LocalOK_ImplicitlyAsync_AsyncThrowsAll: AsyncThrowsAll { func maybe(param: String, int: Int) throws -> Int { 1111 } } actor LocalOK_ImplicitlyThrowsAsync_AsyncThrowsAll: AsyncThrowsAll { func maybe(param: String, int: Int) -> Int { 1111 } } distributed actor Nope1_AsyncThrowsAll: AsyncThrowsAll { func maybe(param: String, int: Int) async throws -> Int { 111 } // expected-error@-1{{distributed actor-isolated instance method 'maybe(param:int:)' cannot be used to satisfy nonisolated protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'maybe(param:int:)' to make this instance method not isolated to the actor}} // expected-note@-3{{add 'distributed' to 'maybe(param:int:)' to make this instance method satisfy the protocol requirement}} } distributed actor OK_AsyncThrowsAll: AsyncThrowsAll { distributed func maybe(param: String, int: Int) async throws -> Int { 222 } } distributed actor OK_Implicitly_AsyncThrowsAll: AsyncThrowsAll { distributed func maybe(param: String, int: Int) -> Int { 333 } } func testAsyncThrowsAll(p: AsyncThrowsAll, dap: OK_AsyncThrowsAll, dapi: OK_Implicitly_AsyncThrowsAll) async throws { _ = try await p.maybe(param: "", int: 0) _ = try await dap.maybe(param: "", int: 0) _ = try await dapi.maybe(param: "", int: 0) // Such conversion is sound: let pp: AsyncThrowsAll = dapi _ = try await pp.maybe(param: "", int: 0) } // ==== ----------------------------------------------------------------------- // MARK: Distributed actor protocols can have non-dist requirements protocol TerminationWatchingA { func terminated(a: String) async // expected-note@-1{{mark the protocol requirement 'terminated(a:)' 'throws' to allow actor-isolated conformances}} } protocol TerminationWatchingDA: DistributedActor { func terminated(da: String) async // expected-note 3 {{distributed actor-isolated instance method 'terminated(da:)' declared here}} } actor A_TerminationWatchingA: TerminationWatchingA { func terminated(a: String) { } // ok, since: actor -> implicitly async } func test_watching_A(a: A_TerminationWatchingA) async throws { await a.terminated(a: "normal") } distributed actor DA_TerminationWatchingA: TerminationWatchingA { func terminated(a: String) { } // expected-error@-1{{distributed actor-isolated instance method 'terminated(a:)' cannot be used to satisfy nonisolated protocol requirement}} // expected-note@-2{{add 'nonisolated' to 'terminated(a:)' to make this instance method not isolated to the actor}} } distributed actor DA_TerminationWatchingDA: TerminationWatchingDA { distributed func test() {} func terminated(da: String) { } // expected-note@-1{{distributed actor-isolated instance method 'terminated(da:)' declared here}} } func test_watchingDA(da: DA_TerminationWatchingDA) async throws { try await da.test() // ok da.terminated(da: "the terminated func is not distributed") // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} } func test_watchingDA<WDA: TerminationWatchingDA>(da: WDA) async throws { try await da.terminated(da: "the terminated func is not distributed") // expected-error@-1{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} // expected-warning@-2{{no calls to throwing functions occur within 'try' expression}} let __secretlyKnownToBeLocal = da await __secretlyKnownToBeLocal.terminated(da: "local calls are okey!") // OK await da.whenLocal { __secretlyKnownToBeLocal in await __secretlyKnownToBeLocal.terminated(da: "local calls are okey!") // OK } } func test_watchingDA_erased(da: DA_TerminationWatchingDA) async throws { let wda: any TerminationWatchingDA = da try await wda.terminated(da: "the terminated func is not distributed") // expected-error@-1{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} // expected-warning@-2{{no calls to throwing functions occur within 'try' expression}} let __secretlyKnownToBeLocal = wda await __secretlyKnownToBeLocal.terminated(da: "local calls are okey!") // OK await wda.whenLocal { __secretlyKnownToBeLocal in await __secretlyKnownToBeLocal.terminated(da: "local calls are okey!") // OK } } func test_watchingDA_any(da: any TerminationWatchingDA) async throws { try await da.terminated(da: "the terminated func is not distributed") // expected-error@-1{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} // expected-warning@-2{{no calls to throwing functions occur within 'try' expression}} } // ==== ------------------------------------------------------------------------ // MARK: Distributed Actor requiring protocol witnessing async throws requirements struct Salsa: Codable, Sendable {} protocol TacoPreparation { func makeTacos(with salsa: Salsa) async throws } protocol DistributedTacoMaker: DistributedActor, TacoPreparation { } extension DistributedTacoMaker { distributed func makeTacos(with: Salsa) {} } extension TacoPreparation { distributed func makeSalsa() -> Salsa {} // expected-error@-1{{'distributed' method can only be declared within 'distributed actor'}} } distributed actor TacoWorker: DistributedTacoMaker {} // implemented in extensions extension DistributedTacoMaker where SerializationRequirement == Codable { distributed func makeGreatTacos(with: Salsa) {} }
apache-2.0
4bcac46b6c00fb480eb5387d253c2a28
44.602888
219
0.715722
4.210667
false
false
false
false
ken0nek/swift
test/Generics/function_defs.swift
1
11104
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Type-check function definitions //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Basic type checking //===----------------------------------------------------------------------===// protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool { var b1 = t1.isEqual(t2) if b1 { return true } return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}} expected-note {{expected an argument list of type '(T)'}} } protocol MethodLessComparable { func isLess(_ other: Self) -> Bool } func min<T : MethodLessComparable>(_ x: T, y: T) -> T { if (y.isLess(x)) { return y } return x } //===----------------------------------------------------------------------===// // Interaction with existential types //===----------------------------------------------------------------------===// func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) { var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} eqComp = u if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}} // expected-note @-1 {{expected an argument list of type '(T)'}} if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}} } protocol OtherEqualComparable { func isEqual(_ other: Self) -> Bool } func otherExistential<T : EqualComparable>(_ t1: T) { var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp2 _ = t1 as protocol<EqualComparable, OtherEqualComparable> // expected-error{{'T' is not convertible to 'protocol<EqualComparable, OtherEqualComparable>'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} } protocol Runcible { func runce<A>(_ x: A) func spoon(_ x: Self) } func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}} x.runce(5) } //===----------------------------------------------------------------------===// // Overloading //===----------------------------------------------------------------------===// protocol Overload { associatedtype A associatedtype B func getA() -> A func getB() -> B func f1(_: A) -> A func f1(_: B) -> B func f2(_: Int) -> A // expected-note{{found this candidate}} func f2(_: Int) -> B // expected-note{{found this candidate}} func f3(_: Int) -> Int // expected-note {{found this candidate}} func f3(_: Float) -> Float // expected-note {{found this candidate}} func f3(_: Self) -> Self // expected-note {{found this candidate}} var prop : Self { get } } func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl, other: OtherOvl) { var a = ovl.getA() var b = ovl.getB() // Overloading based on arguments _ = ovl.f1(a) a = ovl.f1(a) _ = ovl.f1(b) b = ovl.f1(b) // Overloading based on return type a = ovl.f2(17) b = ovl.f2(17) ovl.f2(17) // expected-error{{ambiguous use of 'f2'}} // Check associated types from different objects/different types. a = ovl2.f2(17) a = ovl2.f1(a) other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}} // expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}} // Overloading based on context var f3i : (Int) -> Int = ovl.f3 var f3f : (Float) -> Float = ovl.f3 var f3ovl_1 : (Ovl) -> Ovl = ovl.f3 var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3 var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}} var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3 var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3 var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3 var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3 var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3 } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol Subscriptable { associatedtype Index associatedtype Value func getIndex() -> Index func getValue() -> Value subscript (index : Index) -> Value { get set } } protocol IntSubscriptable { associatedtype ElementType func getElement() -> ElementType subscript (index : Int) -> ElementType { get } } func subscripting<T : protocol<Subscriptable, IntSubscriptable>>(_ t: T) { var index = t.getIndex() var value = t.getValue() var element = t.getElement() value = t[index] t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}} element = t[17] t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}} // Suggests the Int form because we prefer concrete matches to generic matches in diagnosis. t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}} } //===----------------------------------------------------------------------===// // Static functions //===----------------------------------------------------------------------===// protocol StaticEq { static func isEqual(_ x: Self, y: Self) -> Bool } func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) { if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} if T.isEqual(t, y: t) { return } if U.isEqual(u, y: u) { return } T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}} expected-note {{expected an argument list of type '(T, y: T)'}} } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Ordered { func <(lhs: Self, rhs: Self) -> Bool } func testOrdered<T : Ordered>(_ x: T, y: Int) { if y < 100 || 500 < y { return } if x < x { return } } //===----------------------------------------------------------------------===// // Requires clauses //===----------------------------------------------------------------------===// func conformanceViaRequires<T where T : EqualComparable, T : MethodLessComparable >(_ t1: T, t2: T) -> Bool { let b1 = t1.isEqual(t2) if b1 || t1.isLess(t2) { return true } } protocol GeneratesAnElement { associatedtype Element : EqualComparable func makeIterator() -> Element } protocol AcceptsAnElement { associatedtype Element : MethodLessComparable func accept(_ e : Element) } func impliedSameType<T : GeneratesAnElement where T : AcceptsAnElement>(_ t: T) { t.accept(t.makeIterator()) let e = t.makeIterator(), e2 = t.makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } protocol GeneratesAssoc1 { associatedtype Assoc1 : EqualComparable func get() -> Assoc1 } protocol GeneratesAssoc2 { associatedtype Assoc2 : MethodLessComparable func get() -> Assoc2 } func simpleSameType <T : GeneratesAssoc1, U : GeneratesAssoc2 where T.Assoc1 == U.Assoc2> (_ t: T, u: U) -> Bool { return t.get().isEqual(u.get()) || u.get().isLess(t.get()) } protocol GeneratesMetaAssoc1 { associatedtype MetaAssoc1 : GeneratesAnElement func get() -> MetaAssoc1 } protocol GeneratesMetaAssoc2 { associatedtype MetaAssoc2 : AcceptsAnElement func get() -> MetaAssoc2 } func recursiveSameType <T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1 where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2> (_ t: T, u: U) { t.get().accept(t.get().makeIterator()) let e = t.get().makeIterator(), e2 = t.get().makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } // <rdar://problem/13985164> protocol P1 { associatedtype Element } protocol P2 { associatedtype AssocP1 : P1 func getAssocP1() -> AssocP1 } func beginsWith2< E0: P1, E1: P1 where E0.Element == E1.Element, E0.Element : EqualComparable >(_ e0: E0, _ e1: E1) -> Bool { } func beginsWith3< S0: P2, S1: P2 where S0.AssocP1.Element == S1.AssocP1.Element, S1.AssocP1.Element : EqualComparable >(_ seq1: S0, _ seq2: S1) -> Bool { return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1()) } // FIXME: Test same-type constraints that try to equate things we // don't want to equate, e.g., T == U. //===----------------------------------------------------------------------===// // Bogus requirements //===----------------------------------------------------------------------===// func nonTypeReq<T where T : Wibble>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}} func badProtocolReq<T where T : Int>(_: T) {} // expected-error{{type 'T' constrained to non-protocol type 'Int'}} func nonTypeSameType<T where T == Wibble>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}} func nonTypeSameType2<T where Wibble == T>(_: T) {} // expected-error{{use of undeclared type 'Wibble'}} func sameTypeEq<T where T = T>(_: T) {} // expected-error{{use '==' for same-type requirements rather than '='}} {{27-28===}} func badTypeConformance1<T where Int : EqualComparable>(_: T) {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T where T.Blarg : EqualComparable>(_: T) { } // expected-error{{'Blarg' is not a member type of 'T'}} func badSameType<T, U : GeneratesAnElement, V // expected-error{{generic parameter 'V' is not used in function signature}} where T == U.Element, U.Element == V // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}} >(_: T) {}
apache-2.0
af80df6198b26d1bebb26dfde58ef844
35.051948
393
0.573217
4.034884
false
false
false
false
MichaelSelsky/TheBeatingAtTheGates
BeatingGatesCommon/LaneNode.swift
1
915
// // LaneNode.swift // The Beating at the Gates // // Created by Grant Butler on 1/30/16. // Copyright © 2016 Grant J. Butler. All rights reserved. // import SpriteKit public class LaneNode: SKNode { public let length: Int public init(length: Int, alternate: Bool = false) { self.length = length super.init() var xOffset: CGFloat = 0.0 for tileIndex in 0 ..< length { let variant: Int = ((tileIndex + Int(alternate)) % 2) + 1 let spriteNode = SKSpriteNode(imageNamed: "Dirt\(variant)") spriteNode.name = "Tile\(tileIndex)" let calculatedFrame = spriteNode.calculateAccumulatedFrame() spriteNode.position = CGPoint(x: xOffset + calculatedFrame.maxX, y: calculatedFrame.height / 2.0) addChild(spriteNode) xOffset += calculatedFrame.width } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0578d1cb6d564af048c21e63790ffbbb
22.435897
100
0.681619
3.43609
false
false
false
false
jgonfer/JGFLabRoom
JGFLabRoom/Controller/Security/Common Crypto/CommonCryptoViewController.swift
1
6121
// // CommonCryptoViewController.swift // JGFLabRoom // // Created by Josep González on 21/1/16. // Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved. // import UIKit class CommonCryptoViewController: UIViewController { @IBOutlet weak var topInput: UITextView! @IBOutlet weak var bottomInput: UITextView! @IBOutlet weak var originalTitleLabel: UILabel! @IBOutlet weak var originalMessageLabel: UITextView! @IBOutlet weak var base64DecryptTitleLabel: UILabel! @IBOutlet weak var base64DecryptMessageLabel: UITextView! @IBOutlet weak var CCAlgorithmButton: UIButton! @IBOutlet weak var CCBlockSizeButton: UIButton! @IBOutlet weak var CCContextSizeButton: UIButton! @IBOutlet weak var CCKeySizeButton: UIButton! @IBOutlet weak var CCOptionButton: UIButton! @IBOutlet weak var fixedStringSwitch: UISwitch! var randomKey = Utils.generateRandomStringKey() var dataEncryptedMessage: NSData? var settingsType: CCSettings? var tagSelected: Int? var titlesEncryption = ["AES 128", "AES 128", "AES 128", "AES 128", "PKCS7 Padding"] var valuesEncryption = [kCCAlgorithmAES128, kCCBlockSizeAES128, kCCContextSizeAES128, kCCKeySizeAES128, kCCOptionPKCS7Padding] override func viewDidLoad() { super.viewDidLoad() setupController() } private func setupController() { Utils.cleanBackButtonTitle(navigationController) topInput.layer.borderColor = kColorPrimary.CGColor topInput.layer.borderWidth = 2 topInput.layer.masksToBounds = true topInput.layer.cornerRadius = 8.0 bottomInput.layer.borderColor = kColorPrimaryAlpha.CGColor bottomInput.layer.borderWidth = 2 bottomInput.layer.masksToBounds = true bottomInput.layer.cornerRadius = 8.0 originalMessageLabel.text = randomKey updateTitleButtons() let tapGesture = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tapGesture) } private func updateTitleButtons() { CCAlgorithmButton.setTitle(titlesEncryption[0], forState: .Normal) CCBlockSizeButton.setTitle(titlesEncryption[1], forState: .Normal) CCContextSizeButton.setTitle(titlesEncryption[2], forState: .Normal) CCKeySizeButton.setTitle(titlesEncryption[3], forState: .Normal) CCOptionButton.setTitle(titlesEncryption[4], forState: .Normal) } func dismissKeyboard() { topInput.resignFirstResponder() bottomInput.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let settingsType = settingsType else { return } if let vcToShow = segue.destinationViewController as? CCSettingsViewController { vcToShow.settingsType = settingsType vcToShow.title = CCSettings.getTitle(settingsType) vcToShow.delegate = self } } // MARK: IBAction Methods @IBAction func chooseSettingsForAESEncryption(sender: UIButton) { switch sender.tag { case 0: settingsType = .CCAlgorithm case 1: settingsType = .CCBlockSize case 2: settingsType = .CCContextSize case 3: settingsType = .CCKeySize case 4: settingsType = .CCOption default: break } tagSelected = sender.tag performSegueWithIdentifier(kSegueIdCCSettings, sender: sender) } @IBAction func encryptMessage(sender: UIButton) { guard !topInput.text!.isEmpty else { return } if !fixedStringSwitch.on { randomKey = Utils.generateRandomStringKey() } originalMessageLabel.text = randomKey if let messageEncrypted = Utils.AESEncryption(topInput.text!, key: randomKey, algorithm: valuesEncryption[0], blockSize: valuesEncryption[1], contextSize: valuesEncryption[2], keySize: valuesEncryption[3], option: valuesEncryption[4]) { dataEncryptedMessage = messageEncrypted.data bottomInput.text = messageEncrypted.text dismissKeyboard() } else { bottomInput.text = "" } } @IBAction func cleanOriginalText(sender: UIButton) { topInput.text = "" base64DecryptTitleLabel.hidden = true base64DecryptMessageLabel.text = "" } @IBAction func decryptMessage(sender: UIButton) { guard !bottomInput.text!.isEmpty else { return } guard let dataEncryptedMessage = dataEncryptedMessage else { return } originalMessageLabel.text = randomKey if let messageEncrypted = Utils.AESDecryption(dataEncryptedMessage, key: randomKey, algorithm: valuesEncryption[0], blockSize: valuesEncryption[1], contextSize: valuesEncryption[2], keySize: valuesEncryption[3], option: valuesEncryption[4]) { base64DecryptTitleLabel.hidden = false base64DecryptMessageLabel.text = messageEncrypted.text topInput.text = NSString(data: messageEncrypted.data, encoding: NSUTF8StringEncoding) as? String dismissKeyboard() } else { base64DecryptTitleLabel.hidden = true base64DecryptMessageLabel.text = "" topInput.text = "" } } @IBAction func cleanEncryptedText(sender: UIButton) { bottomInput.text = "" } } extension CommonCryptoViewController: CCSettingsViewControllerDelegate { func valueSelected(row: Int) { let titles = CCSettings.getTitlesArray(settingsType!) let values = CCSettings.getValuesArray(settingsType!) titlesEncryption[tagSelected!] = titles[row] valuesEncryption[tagSelected!] = values[row] updateTitleButtons() } }
mit
44822d3fbf597a1b225363766f84a896
36.310976
250
0.668737
4.974797
false
false
false
false
seansu4you87/kupo
sandbox/apple/kids.playground/Contents.swift
1
3555
//: Playground - noun: a place where people can play /* class Fruit { var type=1 var name="Apple" var delicious=true } // We can get at some info about an instance of an object using reflect(), which returns a Mirror. reflect(Fruit()).count reflect(Fruit())[1].0 reflect(Fruit())[1].1.summary // Dump a bunch of info about the object using reflection. dump(Fruit()) // Let's make an instance and print all its properties to the console. var theFruit=Fruit() for var index=0; index<reflect(theFruit).count; ++index { println(reflect(theFruit)[index].0 + ": "+reflect(theFruit)[index].1.summary) } */ import Foundation public func curry<A, B, C, D>(function: (A, B, C) -> D) -> A -> B -> C -> D { return { `a` in { `b` in { `c` in function(`a`, `b`, `c`) } } } } infix operator <^> { associativity left precedence 130 } infix operator <*> { associativity left precedence 130 } //func <^> <A, B>(@noescape f: A -> B, ) struct User { let id: Int let firstName: String let lastName: String let email: String } protocol MassProducable { associatedtype Me = Self static func massProduce() -> Me } protocol Fakable { associatedtype Me = Self static func fake() -> Me } func fakeFirstName() -> String { return "Sean" } func fakeLastName() -> String { return "Yu" } func fakeEmail() -> String { return "[email protected]" } public enum JSON { case Object([Swift.String: JSON]) case Array([JSON]) case String(Swift.String) case Number(NSNumber) case Bool(Swift.Bool) case Null } extension NSNumber { var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } } extension Dictionary { func map<T>(@noescape f: Value -> T) -> [Key: T] { var accum = Dictionary<Key, T>(minimumCapacity: self.count) for (key, value) in self { accum[key] = f(value) } return accum } } public extension JSON { /** Transform an `AnyObject` instance into `JSON`. This is used to move from a loosely typed object (like those returned from `NSJSONSerialization`) to the strongly typed `JSON` tree structure. - parameter json: A loosely typed object */ init(_ json: AnyObject) { switch json { case let v as [AnyObject]: self = .Array(v.map(JSON.init)) case let v as [Swift.String: AnyObject]: self = .Object(v.map(JSON.init)) case let v as Swift.String: self = .String(v) case let v as NSNumber: if v.isBool { self = .Bool(v as Swift.Bool) } else { self = .Number(v) } default: self = .Null } } } extension Int: Fakable { static func fake() -> Int { return 1 } } extension User: MassProducable { static func massProduce() -> User { let json = JSON([ "id": Int.fake(), "firstName": fakeFirstName(), "lastName": fakeLastName(), "email": fakeEmail(), ] as AnyObject) return User.decode(json) } } //extension User: MassProducable { // static func massProduce() -> User { // return curry(User.init) // <^> fake // <*> fakeFirstName // <*> fakeLastName // <*> fakeEmail // } //} /* Faker */
mit
7d4635ebec651364a2fcf745b4350d54
20.415663
98
0.553305
3.855748
false
false
false
false
vegather/MOON-Graph
Sample Code/OS X (deprecated)/OS X Example/OS X Example/ViewController.swift
2
4741
// // ViewController.swift // OS X Example // // Created by Vegard Solheim Theriault on 28/02/16. // Copyright © 2016 MOON Wearables. All rights reserved. // // .___ ___. ______ ______ .__ __. // | \/ | / __ \ / __ \ | \ | | // | \ / | | | | | | | | | | \| | // | |\/| | | | | | | | | | | . ` | // | | | | | `--' | | `--' | | |\ | // |__| |__| \______/ \______/ |__| \__| // ___ _____ _____ _ ___ ___ ___ ___ // | \| __\ \ / / __| | / _ \| _ \ __| _ \ // | |) | _| \ V /| _|| |_| (_) | _/ _|| / // |___/|___| \_/ |___|____\___/|_| |___|_|_\ // import Cocoa import MOONGraphView class ViewController: NSViewController { @IBOutlet weak var graph1: MOONGraphView! @IBOutlet weak var graph2: MOONGraphView! @IBOutlet weak var graph3: MOONGraphView! @IBOutlet weak var graph4: MOONGraphView! @IBOutlet weak var graph5: MOONGraphView! @IBOutlet weak var graph6: MOONGraphView! @IBOutlet weak var graph7: MOONGraphView! var displayLink: CVDisplayLink? var i = 0.0 override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true view.layer?.backgroundColor = NSColor.whiteColor().CGColor graph1.themeColor = .Gray graph1.title = "Dates" graph1.subtitle = "λ = 690nm" graph1.maxSamples = 50 graph2.themeColor = .Red graph2.title = "Orange" graph2.subtitle = "λ = 590nm" graph2.graphDirection = .LeftToRight graph2.maxSamples = 500 graph2.maxValue = 8.0 graph2.minValue = -8.0 graph3.themeColor = .Green graph3.title = "Kiwi" graph3.subtitle = "λ = 530nm" graph3.graphDirection = .LeftToRight graph3.maxSamples = 400 graph3.maxValue = 2.0 graph3.minValue = -2.0 graph4.themeColor = .Yellow graph4.title = "Lemon" graph4.subtitle = "λ = 575nm" graph4.roundedCorners = false graph4.maxSamples = 400 graph4.maxValue = 2.0 graph4.numberOfGraphs = 3 graph5.themeColor = .Purple graph5.graphType = .Scatter graph5.title = "Aubergine" graph5.subtitle = "λ = 430nm" graph5.roundedCorners = false graph5.maxSamples = 200 graph5.numberOfGraphs = 3 graph6.themeColor = .Blue graph6.title = "Blueberry" graph6.subtitle = "λ = 460nm" graph6.maxSamples = 1000 graph6.maxValue = 5.0 graph6.minValue = -1.1 graph7.themeColor = .Turquoise graph7.title = "Blue Grapes" graph7.subtitle = "λ = 480nm" graph7.maxSamples = 400 graph7.maxValue = 6.0 graph7.minValue = -6.0 func displayLinkOutputCallback( displayLink : CVDisplayLink, _ inNow : UnsafePointer<CVTimeStamp>, _ inOutputTime : UnsafePointer<CVTimeStamp>, _ flagsIn : CVOptionFlags, _ flagsOut : UnsafeMutablePointer<CVOptionFlags>, _ displayLinkContext: UnsafeMutablePointer<Void>) -> CVReturn { unsafeBitCast(displayLinkContext, ViewController.self).update() return kCVReturnSuccess } CVDisplayLinkCreateWithActiveCGDisplays(&displayLink) if let displayLink = displayLink { CVDisplayLinkSetOutputCallback(displayLink, displayLinkOutputCallback, UnsafeMutablePointer<Void>(unsafeAddressOf(self))) CVDisplayLinkStart(displayLink) } } func squareForI(input: Double) -> Double { return (1...20).filter({$0 % 2 != 0}).reduce(0.0, combine: {$0 + sin(input * Double($1))}) } func triangleForI(input: Double) -> Double { return (1...20).reduce(0.0, combine: {$0 + sin(input * Double($1))}) } func update() { dispatch_async(dispatch_get_main_queue()) { let value = sin(self.i) self.graph1.addSamples(value) self.graph2.addSamples(self.triangleForI(self.i)) self.graph3.addSamples(value + sin(self.i * 5) / 3.0) self.graph6.addSamples(value) self.graph7.addSamples(self.squareForI(self.i)) self.graph4.addSamples(sin(self.i * 19) / 2.0 + sin(self.i * 21) / 2.0, cos(self.i), cos(self.i + M_PI)) self.graph5.addSamples(value, sin(self.i + 2 * M_PI / 3), sin(self.i + 4 * M_PI / 3)) self.i += 0.1 } } }
mit
7c268fd15b8e0cfe2e5e155dc979959f
32.807143
133
0.515529
3.646379
false
false
false
false
hq7781/MoneyBook
MoneyBook/Misc/Extension/Extension+String.swift
1
1592
// // Extension+String.swift // MoneyBook // // Created by HongQuan on 2017/05/01. // Copyright © 2017年 Roan.Hong. All rights reserved. // import Foundation extension String { var length: Int { return self.characters.count } /* /// return string of the MD5 result var md5: String! { let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.dealloc(digestLen) return hash.copy() as! String } */ subscript (i: Int) -> String { return self[Range(i ..< i + 1)] } func substring(from: Int) -> String { return self[Range(min(from, length) ..< length)] } func substring(to: Int) -> String { return self[Range(0 ..< max(0, to))] } subscript (r: Range<Int>) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return self[Range(start ..< end)] } }
mit
ce847deb559c4cddb96f550de8ade04e
26.396552
86
0.565135
4.095361
false
false
false
false
OscarSwanros/swift
test/Sema/enum_equatable_hashable.swift
2
7415
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift -verify-ignore-unknown enum Foo { case A, B } if Foo.A == .B { } var aHash: Int = Foo.A.hashValue enum Generic<T> { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } if Generic<Foo>.A == .B { } var gaHash: Int = Generic<Foo>.A.hashValue func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B var hashValue: Int { return 0 } } func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note 3 {{non-matching type}} return true } if CustomHashable.A == .B { } var custHash: Int = CustomHashable.A.hashValue // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-note{{previously declared here}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note 3 {{non-matching type}} return "" } if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue var i: Int = InvalidCustomHashable.A.hashValue // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue func getFromOtherFile() -> AlsoFromOtherFile { return .A } if .A == getFromOtherFile() {} func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } if .A == overloadFromOtherFile() {} // Complex enums are not implicitly Equatable or Hashable. enum Complex { case A(Int) case B } if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } if GenericHashable<String>.A("a") == .B { } var genericHashableHash: Int = GenericHashable<String>.A("a").hashValue // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error {{does not conform}} case A(T) case B } if GenericNotHashable<String>.A("a") == .B { } var genericNotHashableHash: Int = GenericNotHashable<String>.A("a").hashValue // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hashValue'}} // An enum with no cases should not derive conformance. enum NoCases: Hashable {} // expected-error 2 {{does not conform}} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note 2 {{non-matching type}} return true } // No explicit conformance; it could be derived, but we don't support extensions // yet. extension Complex : Hashable {} // expected-error 2 {{cannot be automatically synthesized in an extension}} // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { // expected-note 2 {{non-matching type}} return true } var hashValue: Int { return 0 } } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
eba7451169ab673df85869fd16e87a0f
30.688034
168
0.722454
3.849948
false
false
false
false
pandazheng/FoodPin-master
FoodPin/MapViewController.swift
2
2731
// // MapViewController.swift // FoodPin // // Created by scott on 14-11-2. // Copyright (c) 2014年 scott. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController,MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var restaurant:Restaurant! // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() self.title = restaurant.name self.mapView.delegate = self let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(restaurant.location, completionHandler: { (placemarks:[AnyObject]!, error:NSError!) -> Void in if error != nil{ println(error) return } if placemarks != nil && placemarks.count > 0 { let placemark = placemarks[0] as! CLPlacemark let annotation = MKPointAnnotation() annotation.title = self.restaurant.name annotation.subtitle = self.restaurant.type annotation.coordinate = placemark.location.coordinate self.mapView.showAnnotations([annotation], animated: true) self.mapView.selectAnnotation(annotation, animated: true) } }) } // MARK: - memory override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let identifier = "mypin" if annotation.isKindOfClass(MKUserLocation) { return nil } var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView.canShowCallout = true } let leftIconView = UIImageView(frame: CGRectMake(0, 0, 47, 47)) leftIconView.image = UIImage(data: restaurant.image) annotationView.leftCalloutAccessoryView = leftIconView return annotationView } /* // 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. } */ }
mit
182194b2fc7ababff5b24c4618963d42
30.367816
132
0.617076
5.721174
false
false
false
false
bluejava/GeoTools4iOS
GeoTools4iOS/SCNUtils.swift
1
8341
// // SCNUtils.swift // GeoTools4iOS // // Created by Glenn Crownover on 5/4/15. // Copyright (c) 2015 bluejava. All rights reserved. // import SceneKit class SCNUtils { class func getNodeFromDAE(name: String) -> SCNNode? { var rnode = SCNNode() let nscene = SCNScene(named: name) if let nodeArray = nscene?.rootNode.childNodes { for cn in nodeArray { rnode.addChildNode(cn as! SCNNode) } return rnode } println("DAE File not found: \(name)!!") return nil } class func getStaticNodeFromDAE(name: String) -> SCNNode? { if let node = getNodeFromDAE(name) { // debugNode(node) node.physicsBody = SCNPhysicsBody(type: .Static, shape: SCNPhysicsShape(node: node, options: [ SCNPhysicsShapeTypeKey: SCNPhysicsShapeTypeConcavePolyhedron])) return node } return nil } class func debugNode(node: SCNNode) { println("node: \(node.name)") for cn in node.childNodes { debugNode(cn as! SCNNode) } } class func getMat(textureFilename: String, ureps: Float = 1.0, vreps: Float = 1.0, directory: String? = nil, normalFilename: String? = nil, specularFilename: String? = nil) -> SCNMaterial { var nsb = NSBundle.mainBundle().pathForResource(textureFilename, ofType: nil, inDirectory: directory) let im = UIImage(contentsOfFile: nsb!) let mat = SCNMaterial() mat.diffuse.contents = im if(normalFilename != nil) { mat.normal.contents = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(normalFilename, ofType: nil, inDirectory: directory)!) } if(specularFilename != nil) { mat.specular.contents = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(specularFilename, ofType: nil, inDirectory: directory)!) } repeatMat(mat, wRepeat: ureps,hRepeat: vreps) return mat } class func repeatMat(mat: SCNMaterial, wRepeat: Float, hRepeat: Float) { mat.diffuse.contentsTransform = SCNMatrix4MakeScale(wRepeat, hRepeat, 1.0) mat.diffuse.wrapS = .Repeat mat.diffuse.wrapT = .Repeat mat.normal.wrapS = .Repeat mat.normal.wrapT = .Repeat mat.specular.wrapS = .Repeat mat.specular.wrapT = .Repeat } // Return the normal against the plane defined by the 3 vertices, specified in // counter-clockwise order. // note, this is an un-normalized normal. (ha.. wtf? yah, thats right) class func getNormal(v0: SCNVector3, v1: SCNVector3, v2: SCNVector3) -> SCNVector3 { // there are three edges defined by these 3 vertices, but we only need 2 to define the plane var edgev0v1 = v1 - v0 var edgev1v2 = v2 - v1 // Assume the verts are expressed in counter-clockwise order to determine normal return edgev0v1.cross(edgev1v2) } } // The following SCNVector3 extension comes from https://github.com/devindazzle/SCNVector3Extensions - with some changes by me extension CGPoint { init(x: Float, y: Float) { self.init(x: CGFloat(x), y: CGFloat(y)) } } extension SCNVector3 { /** * Negates the vector described by SCNVector3 and returns * the result as a new SCNVector3. */ func negate() -> SCNVector3 { return self * -1 } /** * Negates the vector described by SCNVector3 */ mutating func negated() -> SCNVector3 { self = negate() return self } /** * Returns the length (magnitude) of the vector described by the SCNVector3 */ func length() -> Float { return sqrt(x*x + y*y + z*z) } /** * Normalizes the vector described by the SCNVector3 to length 1.0 and returns * the result as a new SCNVector3. */ func normalized() -> SCNVector3? { var len = length() if(len > 0) { return self / length() } else { return nil } } /** * Normalizes the vector described by the SCNVector3 to length 1.0. */ mutating func normalize() -> SCNVector3? { if let vn = normalized() { self = vn return self } return nil } /** * Calculates the distance between two SCNVector3. Pythagoras! */ func distance(vector: SCNVector3) -> Float { return (self - vector).length() } /** * Calculates the dot product between two SCNVector3. */ func dot(vector: SCNVector3) -> Float { return x * vector.x + y * vector.y + z * vector.z } /** * Calculates the cross product between two SCNVector3. */ func cross(vector: SCNVector3) -> SCNVector3 { return SCNVector3Make(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x) } func toString() -> String { return "SCNVector3(x:\(x), y:\(y), z:\(z)" } // Return the angle between this vector and the specified vector v func angle(v: SCNVector3) -> Float { // angle between 3d vectors P and Q is equal to the arc cos of their dot products over the product of // their magnitudes (lengths). // theta = arccos( (P • Q) / (|P||Q|) ) let dp = dot(v) // dot product let magProduct = length() * v.length() // product of lengths (magnitudes) return acos(dp / magProduct) // DONE } mutating func constrain(min: SCNVector3, max: SCNVector3) -> SCNVector3 { if(x < min.x) { self.x = min.x } if(x > max.x) { self.x = max.x } if(y < min.y) { self.y = min.y } if(y > max.y) { self.y = max.y } if(z < min.z) { self.z = min.z } if(z > max.z) { self.z = max.z } return self } } /** * Adds two SCNVector3 vectors and returns the result as a new SCNVector3. */ func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z) } /** * Increments a SCNVector3 with the value of another. */ func += (inout left: SCNVector3, right: SCNVector3) { left = left + right } /** * Subtracts two SCNVector3 vectors and returns the result as a new SCNVector3. */ func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z) } /** * Decrements a SCNVector3 with the value of another. */ func -= (inout left: SCNVector3, right: SCNVector3) { left = left - right } /** * Multiplies two SCNVector3 vectors and returns the result as a new SCNVector3. */ func * (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x * right.x, left.y * right.y, left.z * right.z) } /** * Multiplies a SCNVector3 with another. */ func *= (inout left: SCNVector3, right: SCNVector3) { left = left * right } /** * Multiplies the x, y and z fields of a SCNVector3 with the same scalar value and * returns the result as a new SCNVector3. */ func * (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar) } /** * Multiplies the x and y fields of a SCNVector3 with the same scalar value. */ func *= (inout vector: SCNVector3, scalar: Float) { vector = vector * scalar } /** * Divides two SCNVector3 vectors abd returns the result as a new SCNVector3 */ func / (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x / right.x, left.y / right.y, left.z / right.z) } /** * Divides a SCNVector3 by another. */ func /= (inout left: SCNVector3, right: SCNVector3) { left = left / right } /** * Divides the x, y and z fields of a SCNVector3 by the same scalar value and * returns the result as a new SCNVector3. */ func / (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar) } /** * Divides the x, y and z of a SCNVector3 by the same scalar value. */ func /= (inout vector: SCNVector3, scalar: Float) { vector = vector / scalar } /** * Calculates the SCNVector from lerping between two SCNVector3 vectors */ func SCNVector3Lerp(vectorStart: SCNVector3, vectorEnd: SCNVector3, t: Float) -> SCNVector3 { return SCNVector3Make(vectorStart.x + ((vectorEnd.x - vectorStart.x) * t), vectorStart.y + ((vectorEnd.y - vectorStart.y) * t), vectorStart.z + ((vectorEnd.z - vectorStart.z) * t)) } /** * Project the vector, vectorToProject, onto the vector, projectionVector. */ func SCNVector3Project(vectorToProject: SCNVector3, projectionVector: SCNVector3) -> SCNVector3 { let scale: Float = projectionVector.dot(vectorToProject) / projectionVector.dot(projectionVector) let v: SCNVector3 = projectionVector * scale return v } // Define a couple structures that hold GLFloats (3 and 2) struct Float3 { var x, y, z: GLfloat } struct Float2 { var s, t: GLfloat }
mit
5bbc1a03a5ee85a5d901136388af623c
24.89441
181
0.681818
3.175171
false
false
false
false
TurfDb/Turf
Turf/Extensions/SecondaryIndex/PreparedQueries/Connection+PreparedQuery.swift
1
3283
extension Connection { /** Prepare a query for retrieving a single value from `collection`. Use a prepared query for performance critcal areas where a query will be executed regularly. - warning: Prepared queries can only be used on the `Connection` they were created from. - parameter collection: Secondary indexed collection where a matching value will be searched for. - parameter valueWhere: Query clause. */ public func prepareQueryFor<TCollection: IndexedCollection>(_ collection: TCollection, valueWhere clause: WhereClause) throws -> PreparedValueWhereQuery<Collections> { var stmt: OpaquePointer? = nil let sql = "SELECT targetPrimaryKey FROM `\(collection.index.tableName)` WHERE \(clause.sql)" guard sqlite3_prepare_v2(sqlite.db, sql, -1, &stmt, nil).isOK else { sqlite3_finalize(stmt) throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(sqlite.db), String(cString: sqlite3_errmsg(sqlite.db))) } return PreparedValueWhereQuery(clause: clause, stmt: stmt!, connection: self) } /** Prepare a query for retrieving values from `collection`. Use a prepared query for performance critcal areas where a query will be executed regularly. - warning: Prepared queries can only be used on the `Connection` they were created from. - parameter collection: Secondary indexed collection where matching values will be searched for. - parameter valuesWhere: Query clause. */ public func prepareQueryFor<TCollection: IndexedCollection>(_ collection: TCollection, valuesWhere clause: WhereClause) throws -> PreparedValuesWhereQuery<Collections> { var stmt: OpaquePointer? = nil let sql = "SELECT targetPrimaryKey FROM `\(collection.index.tableName)` WHERE \(clause.sql)" guard sqlite3_prepare_v2(sqlite.db, sql, -1, &stmt, nil).isOK else { sqlite3_finalize(stmt) throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(sqlite.db), String(cString: sqlite3_errmsg(sqlite.db))) } return PreparedValuesWhereQuery(clause: clause, stmt: stmt!, connection: self) } /** Prepare a query for retrieving a count of values matching `countWhere` in `collection`. Use a prepared query for performance critcal areas where a query will be executed regularly. - warning: Prepared queries can only be used on the `Connection` they were created from. - parameter collection: Secondary indexed collection where matching values will be counted. - parameter countWhere: Query clause. */ public func prepareQueryFor<TCollection: IndexedCollection>(_ collection: TCollection, countWhere clause: WhereClause) throws -> PreparedCountWhereQuery<Collections> { var stmt: OpaquePointer? = nil let sql = "SELECT COUNT(targetPrimaryKey) FROM `\(collection.index.tableName)` WHERE \(clause.sql)" guard sqlite3_prepare_v2(sqlite.db, sql, -1, &stmt, nil).isOK else { sqlite3_finalize(stmt) throw SQLiteError.failedToPrepareStatement(sqlite3_errcode(sqlite.db), String(cString: sqlite3_errmsg(sqlite.db))) } return PreparedCountWhereQuery(clause: clause, stmt: stmt!, connection: self) } }
mit
f006ed4cd368dc2bf810b88315f4c68f
55.603448
173
0.713677
4.572423
false
false
false
false
grandiere/box
box/Model/Boards/MBoards.swift
1
2955
import Foundation class MBoards { private(set) var sort:MBoardsSortProtocol private(set) var items:[MBoardsItem] private weak var controller:CBoards? private let kSortWait:TimeInterval = 1 init() { sort = MBoardsSortScore() items = [] } //MARK: private private func asyncLoad() { let path:String = FDb.user FMain.sharedInstance.db.listenOnce( path:path, nodeType:FDbUser.self) { [weak self] (data:FDbProtocol?) in guard let users:FDbUser = data as? FDbUser else { return } self?.loadedUsers(users:users) } } private func loadedUsers(users:FDbUser) { var items:[MBoardsItem] = [] let userIds:[String] = Array(users.items.keys) for userId:String in userIds { guard let firebaseUser:FDbUserItem = users.items[userId], let handler:String = firebaseUser.handler else { continue } if handler.characters.count > 0 { let item:MBoardsItem = MBoardsItem( score:firebaseUser.score, kills:firebaseUser.kills, handler:handler, userId:userId) items.append(item) } } self.items = items itemsLoaded() } private func itemsLoaded() { items = sort.sort(items:items) numberItems() controller?.boardsLoaded() } private func numberItems() { var position:Int = 1 for item:MBoardsItem in items { item.position = position position += 1 } } //MARK: public func load(controller:CBoards) { self.controller = controller DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncLoad() } } func sortScore() { controller?.viewBoards.startLoading() sort = MBoardsSortScore() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).asyncAfter( deadline:DispatchTime.now() + kSortWait) { [weak self] in self?.itemsLoaded() } } func sortKills() { controller?.viewBoards.startLoading() sort = MBoardsSortKills() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).asyncAfter( deadline:DispatchTime.now() + kSortWait) { [weak self] in self?.itemsLoaded() } } }
mit
e8334440660651077c34a2db19274c00
21.906977
77
0.483926
4.949749
false
false
false
false
clappr/clappr-ios
Sources/Clappr/Classes/Extension/AVFoundationPlayback+DVR.swift
1
2346
import AVFoundation extension AVFoundationPlayback { open override var minDvrSize: Double { return options[kMinDvrSize] as? Double ?? 60.0 } open override var isDvrInUse: Bool { if state == .paused && isDvrAvailable { return true } guard let end = dvrWindowEnd, playbackType == .live else { return false } guard let currentTime = player.currentItem?.currentTime().seconds else { return false } return end - liveHeadTolerance > currentTime } open override var isDvrAvailable: Bool { guard playbackType == .live else { return false } return duration >= minDvrSize } open override var currentDate: Date? { return player.currentItem?.currentDate() } open override var currentLiveDate: Date? { guard let currentDate = currentDate, playbackType == .live else { return nil } let liveDate = currentDate.timeIntervalSince1970 + (duration - TimeInterval(position)) return Date(timeIntervalSince1970: liveDate) } open override var seekableTimeRanges: [NSValue] { guard let ranges = player.currentItem?.seekableTimeRanges else { return [] } return ranges } open override var loadedTimeRanges: [NSValue] { guard let ranges = player.currentItem?.loadedTimeRanges else { return [] } return ranges } open override var epochDvrWindowStart: TimeInterval { guard let currentDate = currentDate else { return 0 } return currentDate.timeIntervalSince1970 - position } var dvrWindowStart: Double? { guard let end = dvrWindowEnd, isDvrAvailable, playbackType == .live else { return nil } return end - duration } var dvrWindowEnd: Double? { guard isDvrAvailable, playbackType == .live else { return nil } return seekableTimeRanges.max { rangeA, rangeB in rangeA.timeRangeValue.end.seconds < rangeB.timeRangeValue.end.seconds }?.timeRangeValue.end.seconds } fileprivate var liveHeadTolerance: Double { return 5 } func isEpochInsideDVRWindow(_ epoch: Double?) -> Bool { guard let epoch = epoch else { return false } let position = epoch - epochDvrWindowStart return position > 0 && position < duration } }
bsd-3-clause
14fd364536c6536234942eb9fada2639
34.014925
157
0.653879
4.778004
false
false
false
false
pocketlabs/ASTextFieldNode
example/ASTextFieldNodeExample/ASTextFieldNodeExample/ViewController.swift
1
3289
// // ViewController.swift // ASTextFieldNodeExample // // Created by Kyle Shank on 2/11/17. // Copyright © 2017 Pocket Labs. All rights reserved. // import UIKit import AsyncDisplayKit import ASTextFieldNode class ViewController: ASViewController<LoginViewNode> { init(){ super.init( node : LoginViewNode() ) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class LoginViewNode : ASDisplayNode { let loginField = ASTextFieldNode() let passwordField = ASTextFieldNode() let emailLabel = ASTextNode() let passwordLabel = ASTextNode() override init(){ super.init() self.automaticallyManagesSubnodes = true } override func didLoad() { super.didLoad() self.backgroundColor = UIColor.white self.layer.borderColor = UIColor.gray.cgColor self.layer.borderWidth = 1.0 self.layer.cornerRadius = 3.0 emailLabel.attributedText = NSAttributedString(string: "Email address", attributes: [NSForegroundColorAttributeName : UIColor.black, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14.0)]) passwordLabel.attributedText = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName : UIColor.black, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14.0)]) loginField.autocapitalizationType = .none loginField.autocorrectionType = .no loginField.keyboardType = .emailAddress loginField.font = UIFont.systemFont(ofSize: 16.0) loginField.textField.attributedPlaceholder = NSAttributedString(string: "[email protected]", attributes: [NSForegroundColorAttributeName : UIColor.lightGray, NSFontAttributeName : UIFont.systemFont(ofSize: 16.0)]) passwordField.isSecureTextEntry = true passwordField.keyboardType = .asciiCapable passwordField.font = UIFont.systemFont(ofSize: 16.0) passwordField.textField.attributedPlaceholder = NSAttributedString(string: "******", attributes: [NSForegroundColorAttributeName : UIColor.lightGray, NSFontAttributeName : UIFont.systemFont(ofSize: 16.0)]) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let verticalStack = ASStackLayoutSpec.vertical() let verticalStack1 = ASStackLayoutSpec.vertical() verticalStack1.children = [emailLabel, loginField] verticalStack1.spacing = 8.0 let verticalStack1Layout = ASInsetLayoutSpec(insets: UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0), child: verticalStack1) let verticalStack2 = ASStackLayoutSpec.vertical() verticalStack2.children = [passwordLabel, passwordField] verticalStack2.spacing = 8.0 let verticalStack2Layout = ASInsetLayoutSpec(insets: UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0), child: verticalStack2) verticalStack.children = [verticalStack1Layout, verticalStack2Layout] verticalStack.style.width = ASDimension(unit: .points, value: 180.0) return ASCenterLayoutSpec(centeringOptions: .XY, sizingOptions: .minimumXY, child: verticalStack) } }
bsd-3-clause
04a0235280f188dd5f3553a847cff5b2
41.153846
218
0.700426
4.974281
false
false
false
false
truemetal/xcode-ios-icon-creation
scale_artworks.swift
1
1758
#!/usr/bin/env xcrun swift import Foundation import AppKit func scaleIcon(iconPath: String, resolution: Int) { let p = Process() p.launchPath = "/usr/bin/sips" p.arguments = ["-Z", "\(resolution)", iconPath] p.launch() p.waitUntilExit() } func copyAndScaleImage(sourceIconPath: String, desctinationIconPath: String, newResolution: Int) throws { if FileManager.default.fileExists(atPath: desctinationIconPath) { print("icon \((desctinationIconPath as NSString).lastPathComponent) already exists; skipping.") } else { try FileManager.default.copyItem(atPath: sourceIconPath, toPath: desctinationIconPath) scaleIcon(iconPath: desctinationIconPath, resolution: Int(newResolution)) } } // ======= let predicate = NSPredicate(format : "self endswith '@3x.png'") let filePaths = try FileManager.default.subpathsOfDirectory(atPath: FileManager.default.currentDirectoryPath) let imagePaths = (filePaths as NSArray).filtered(using: predicate) for filePath in imagePaths as! [String] { if let img = NSImage(contentsOfFile: filePath) { let icon2xPath = filePath.replacingOccurrences(of: "@3x.png", with: "@2x.png") let icon1xPath = filePath.replacingOccurrences(of: "@3x.png", with: ".png") // note: by default, NSImage would assume scale of 3 for @3x images, hence size would be already in points let icon1xResolution = Int(img.size.width) let icon2xResolution = Int(img.size.width * 2) try copyAndScaleImage(sourceIconPath: filePath, desctinationIconPath: icon1xPath, newResolution: icon1xResolution) try copyAndScaleImage(sourceIconPath: filePath, desctinationIconPath: icon2xPath, newResolution: icon2xResolution) } }
mit
971f2181e0d5518ff89e7634d96e3099
40.857143
122
0.716724
4.050691
false
false
false
false
velvetroom/columbus
Source/View/Global/Format/VFormat+Distance.swift
1
2736
import Foundation extension VFormat { //MARK: private private static func distanceConvert( metres:Float, distanceSettings:DSettingsDistance) -> Float { guard let divisor:Float = VFormat.Constants.distanceConversion[distanceSettings] else { return metres } let converted:Float = metres / divisor return converted } private static func factorySuffixMap() -> [DSettingsDistance:String] { let suffixMap:[DSettingsDistance:String] = [ DSettingsDistance.kilometres : String.localizedView(key:"VFormat_distanceKilometres"), DSettingsDistance.miles : String.localizedView(key:"VFormat_distanceMiles")] return suffixMap } private static func factoryFormatter(distanceSettings:DSettingsDistance) -> NumberFormatter? { let suffixes:[DSettingsDistance:String] = factorySuffixMap() guard let suffix:String = suffixes[distanceSettings] else { return nil } let formatter:NumberFormatter = factoryNumberFormatter() formatter.positiveSuffix = suffix return formatter } //MARK: internal static func factoryDistance( distance:Double, distanceSettings:DSettingsDistance) -> String? { let distanceFloat:Float = Float(distance) let distanceString:String? = factoryDistance( distance:distanceFloat, distanceSettings:distanceSettings) return distanceString } static func factoryDistance( travels:[DPlanTravel], distanceSettings:DSettingsDistance) -> String? { let distance:Float = DPlanTravel.factoryDistance( travels:travels) let string:String? = factoryDistance( distance:distance, distanceSettings:distanceSettings) return string } static func factoryDistance( distance:Float, distanceSettings:DSettingsDistance) -> String? { let distance:Float = distanceConvert( metres:distance, distanceSettings:distanceSettings) let distanceNumber:NSNumber = NSNumber(value:distance) guard let formatter:NumberFormatter = factoryFormatter(distanceSettings:distanceSettings), let string:String = formatter.string(from:distanceNumber) else { return nil } return string } }
mit
27d09f0e4e726266a83d2f18e6c0da28
25.307692
98
0.583333
5.641237
false
false
false
false
FoodForTech/Handy-Man
HandyMan/HandyMan/HandyManCore/Spring/Spring.swift
1
20604
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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 protocol Springable : class { var autostart: Bool { get set } var autohide: Bool { get set } var animation: String { get set } var force: CGFloat { get set } var delay: CGFloat { get set } var duration: CGFloat { get set } var damping: CGFloat { get set } var velocity: CGFloat { get set } var repeatCount: Float { get set } var x: CGFloat { get set } var y: CGFloat { get set } var scaleX: CGFloat { get set } var scaleY: CGFloat { get set } var rotate: CGFloat { get set } var opacity: CGFloat { get set } var animateFrom: Bool { get set } var curve: String { get set } // UIView var layer : CALayer { get } var transform : CGAffineTransform { get set } var alpha : CGFloat { get set } func animate() func animateNext(_ completion: @escaping () -> ()) func animateTo() func animateToNext(_ completion: @escaping () -> ()) } open class Spring : NSObject { fileprivate unowned var view : Springable fileprivate var shouldAnimateAfterActive = false init(_ view: Springable) { self.view = view super.init() commonInit() } func commonInit() { NotificationCenter.default.addObserver(self, selector: #selector(Spring.didBecomeActiveNotification(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } func didBecomeActiveNotification(_ notification: Notification) { if shouldAnimateAfterActive { alpha = 0 animate() shouldAnimateAfterActive = false } } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } fileprivate var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }} fileprivate var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }} fileprivate var animation: String { set { self.view.animation = newValue } get { return self.view.animation }} fileprivate var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }} fileprivate var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }} fileprivate var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }} fileprivate var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }} fileprivate var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }} fileprivate var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }} fileprivate var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }} fileprivate var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }} fileprivate var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }} fileprivate var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }} fileprivate var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }} fileprivate var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }} fileprivate var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }} fileprivate var curve: String { set { self.view.curve = newValue } get { return self.view.curve }} // UIView fileprivate var layer : CALayer { return view.layer } fileprivate var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }} fileprivate var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } } func animatePreset() { alpha = 0.99 if animation == "" { return } switch animation { case "slideLeft": x = 300*force case "slideRight": x = -300*force case "slideDown": y = -300*force case "slideUp": y = 300*force case "squeezeLeft": x = 300 scaleX = 3*force case "squeezeRight": x = -300 scaleX = 3*force case "squeezeDown": y = -300 scaleY = 3*force case "squeezeUp": y = 300 scaleY = 3*force case "fadeIn": opacity = 0 case "fadeOut": animateFrom = false opacity = 0 case "fadeOutIn": let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.autoreverses = true layer.add(animation, forKey: "fade") case "fadeInLeft": opacity = 0 x = 300*force case "fadeInRight": x = -300*force opacity = 0 case "fadeInDown": y = -300*force opacity = 0 case "fadeInUp": y = 300*force opacity = 0 case "zoomIn": opacity = 0 scaleX = 2*force scaleY = 2*force case "zoomOut": animateFrom = false opacity = 0 scaleX = 2*force scaleY = 2*force case "fall": animateFrom = false rotate = 15 * CGFloat(M_PI/180) y = 600*force case "shake": let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 30*force, -30*force, 30*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "shake") case "pop": let animation = CAKeyframeAnimation() animation.keyPath = "transform.scale" animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "pop") case "flipX": rotate = 0 scaleX = 1 scaleY = 1 var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(caTransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(caTransform3D: CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.add(animation, forKey: "3d") case "flipY": var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(caTransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(caTransform3D: CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.add(animation, forKey: "3d") case "morph": let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.7, 1.3*force, 0.7, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphY, forKey: "morphY") case "squeeze": let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.5, 1, 0.5, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(morphY, forKey: "morphY") case "flash": let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.duration = CFTimeInterval(duration) animation.repeatCount = repeatCount * 2.0 animation.autoreverses = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "flash") case "wobble": let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "wobble") let x = CAKeyframeAnimation() x.keyPath = "position.x" x.values = [0, 30*force, -30*force, 30*force, 0] x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] x.timingFunction = getTimingFunction(curve) x.duration = CFTimeInterval(duration) x.isAdditive = true x.repeatCount = repeatCount x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(x, forKey: "x") case "swing": let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.isAdditive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.add(animation, forKey: "swing") default: x = 300 } } func getTimingFunction(_ curve: String) -> CAMediaTimingFunction { switch curve { case "easeIn": return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case "easeOut": return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case "easeInOut": return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) case "linear": return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case "spring": return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1) case "easeInSine": return CAMediaTimingFunction(controlPoints: 0.47, 0, 0.745, 0.715) case "easeOutSine": return CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1) case "easeInOutSine": return CAMediaTimingFunction(controlPoints: 0.445, 0.05, 0.55, 0.95) case "easeInQuad": return CAMediaTimingFunction(controlPoints: 0.55, 0.085, 0.68, 0.53) case "easeOutQuad": return CAMediaTimingFunction(controlPoints: 0.25, 0.46, 0.45, 0.94) case "easeInOutQuad": return CAMediaTimingFunction(controlPoints: 0.455, 0.03, 0.515, 0.955) case "easeInCubic": return CAMediaTimingFunction(controlPoints: 0.55, 0.055, 0.675, 0.19) case "easeOutCubic": return CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1) case "easeInOutCubic": return CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1) case "easeInQuart": return CAMediaTimingFunction(controlPoints: 0.895, 0.03, 0.685, 0.22) case "easeOutQuart": return CAMediaTimingFunction(controlPoints: 0.165, 0.84, 0.44, 1) case "easeInOutQuart": return CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1) case "easeInQuint": return CAMediaTimingFunction(controlPoints: 0.755, 0.05, 0.855, 0.06) case "easeOutQuint": return CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1) case "easeInOutQuint": return CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1) case "easeInExpo": return CAMediaTimingFunction(controlPoints: 0.95, 0.05, 0.795, 0.035) case "easeOutExpo": return CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) case "easeInOutExpo": return CAMediaTimingFunction(controlPoints: 1, 0, 0, 1) case "easeInCirc": return CAMediaTimingFunction(controlPoints: 0.6, 0.04, 0.98, 0.335) case "easeOutCirc": return CAMediaTimingFunction(controlPoints: 0.075, 0.82, 0.165, 1) case "easeInOutCirc": return CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86) case "easeInBack": return CAMediaTimingFunction(controlPoints: 0.6, -0.28, 0.735, 0.045) case "easeOutBack": return CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275) case "easeInOutBack": return CAMediaTimingFunction(controlPoints: 0.68, -0.55, 0.265, 1.55) default: return CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) } } func getAnimationOptions(_ curve: String) -> UIViewAnimationOptions { switch curve { case "easeIn": return UIViewAnimationOptions.curveEaseIn case "easeOut": return UIViewAnimationOptions.curveEaseOut case "easeInOut": return UIViewAnimationOptions() case "linear": return UIViewAnimationOptions.curveLinear case "spring": return UIViewAnimationOptions.curveLinear default: return UIViewAnimationOptions.curveLinear } } open func animate() { animateFrom = true animatePreset() setView {} } open func animateNext(_ completion: @escaping () -> ()) { animateFrom = true animatePreset() setView { completion() } } open func animateTo() { animateFrom = false animatePreset() setView {} } open func animateToNext(_ completion: @escaping () -> ()) { animateFrom = false animatePreset() setView { completion() } } open func customAwakeFromNib() { if autohide { alpha = 0 } } open func customDidMoveToWindow() { if autostart { if UIApplication.shared.applicationState != .active { shouldAnimateAfterActive = true return } alpha = 0 animate() } } func setView(_ completion: @escaping () -> ()) { if animateFrom { let translate = CGAffineTransform(translationX: self.x, y: self.y) let scale = CGAffineTransform(scaleX: self.scaleX, y: self.scaleY) let rotate = CGAffineTransform(rotationAngle: self.rotate) let translateAndScale = translate.concatenating(scale) self.transform = rotate.concatenating(translateAndScale) self.alpha = self.opacity } UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: getAnimationOptions(curve), animations: { [weak self] in if let _self = self { if _self.animateFrom { _self.transform = CGAffineTransform.identity _self.alpha = 1 } else { let translate = CGAffineTransform(translationX: _self.x, y: _self.y) let scale = CGAffineTransform(scaleX: _self.scaleX, y: _self.scaleY) let rotate = CGAffineTransform(rotationAngle: _self.rotate) let translateAndScale = translate.concatenating(scale) _self.transform = rotate.concatenating(translateAndScale) _self.alpha = _self.opacity } } }, completion: { [weak self] finished in completion() self?.resetAll() }) } func reset() { x = 0 y = 0 opacity = 1 } func resetAll() { x = 0 y = 0 animation = "" opacity = 1 scaleX = 1 scaleY = 1 rotate = 0 damping = 0.7 velocity = 0.7 repeatCount = 1 delay = 0 duration = 0.7 } }
mit
85d7423545e424d5682535fd3dd5f5a4
39.880952
182
0.594593
4.725688
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Marshroute/PhotoLibraryV2/Router/PhotoLibraryV2MarshrouteRouter.swift
1
1971
import Marshroute import UIKit final class PhotoLibraryV2MarshrouteRouter: BaseRouter, PhotoLibraryV2Router { typealias AssemblyFactory = MediaPickerMarshrouteAssemblyFactory & NewCameraMarshrouteAssemblyFactory private let assemblyFactory: AssemblyFactory private let cameraService: CameraService init(assemblyFactory: AssemblyFactory, cameraService: CameraService, routerSeed: RouterSeed) { self.assemblyFactory = assemblyFactory self.cameraService = cameraService super.init(routerSeed: routerSeed) } // MARK: - PhotoLibraryV2Router func showMediaPicker( data: MediaPickerData, overridenTheme: PaparazzoUITheme?, isNewFlowPrototype: Bool, configure: (MediaPickerModule) -> ()) { pushViewControllerDerivedFrom { routerSeed in let assembly = assemblyFactory.mediaPickerAssembly() return assembly.module( data: data, overridenTheme: overridenTheme, routerSeed: routerSeed, isNewFlowPrototype: isNewFlowPrototype, configure: configure ) } } func showNewCamera( selectedImagesStorage: SelectedImageStorage, mediaPickerData: MediaPickerData, shouldAllowFinishingWithNoPhotos: Bool, configure: (NewCameraModule) -> ()) { presentModalViewControllerDerivedFrom { routerSeed in let assembly = assemblyFactory.newCameraAssembly() return assembly.module( selectedImagesStorage: selectedImagesStorage, mediaPickerData: mediaPickerData, cameraService: cameraService, shouldAllowFinishingWithNoPhotos: shouldAllowFinishingWithNoPhotos, routerSeed: routerSeed, configure: configure ) } } }
mit
42c75f259e82c81d67d8575981a28c70
32.982759
105
0.63724
6.27707
false
true
false
false
adevelopers/prosvet
Prosvet/Common/Network/NetApi.swift
1
2183
// // NetApi.swift // iForexLevels // // Created by adeveloper on 17.02.17. // Copyright © 2017 adeveloper. All rights reserved. // import Foundation import SwiftyJSON /** * * Singleton */ class NetApi { static let shared = NetApi() private var baseUrl:String = "" private init(){ } func setBase(_ url:String) -> Self { baseUrl = url return self } func get(link: String, completionHandler: @escaping (JSON, NSError?) -> Void ) { let link = self.baseUrl + link print("link: \(link)") let url = NSURL(string: link)! let request = NSMutableURLRequest(url: url as URL) let urlSession = URLSession.init(configuration: URLSessionConfiguration.ephemeral) request.httpMethod = "GET" let task = urlSession.dataTask(with: request as URLRequest) { data, response, error -> Void in if error != nil { let json = JSON(data: data!) completionHandler(json, error as NSError?) return } let json = JSON(data: data!) completionHandler(json,nil) } task.resume() } func post(link: String, params:String, completionHandler: @escaping (JSON, NSError?) -> Void ) { let fullLink = self.baseUrl + link let url = NSURL(string: fullLink)! let request = NSMutableURLRequest(url: url as URL) let urlSession = URLSession.shared let paramsString = params request.httpMethod = "POST" request.httpBody = paramsString.data(using: .utf8) let task = urlSession.dataTask(with: request as URLRequest) { data, response, error -> Void in if error != nil { let json = JSON(data: data!) completionHandler(json, error as NSError?) return } let json = JSON(data: data!) completionHandler(json,nil) } task.resume() } }
mit
3571ca9ef4cfc1ef2fabf5c9ff0d5f80
23.795455
102
0.525206
4.848889
false
false
false
false
jlyu/swift-demo
HeavyRotation/HeavyRotation/AppDelegate.swift
1
3277
// // AppDelegate.swift // HeavyRotation // // Created by chain on 14-6-23. // Copyright (c) 2014 chain. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { var device: UIDevice = UIDevice.currentDevice() device.beginGeneratingDeviceOrientationNotifications() device.proximityMonitoringEnabled = true var nc: NSNotificationCenter = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: device) nc.addObserver(self, selector: "proximityMonitoring:", name: UIDeviceProximityStateDidChangeNotification, object: device) var storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let rorViewControll: RotationViewController = storyBoard.instantiateViewControllerWithIdentifier("RotationViewController") as RotationViewController self.window!.rootViewController = rorViewControll return true } func orientationChanged(note: NSNotification) { println("orientationChanged -> ") } func proximityMonitoring(note: NSNotification) { println("proximityMonitoring ->") } 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
a2298834c1b2008e0e1ce2fd05a7574e
43.890411
285
0.702777
6.091078
false
false
false
false
raphacarletti/JiraTracker
JiraTracker/UI/CustomProgressButton/CustomProgressButton.swift
1
3791
// // CustomProgressButton.swift // JiraTracker // // Created by Raphael Carletti on 10/23/17. // Copyright © 2017 Raphael Carletti. All rights reserved. // import Foundation import UIKit protocol CustomProgressButtonDelegate { func didTapCTAButton(_ sender: Any) } class CustomProgressButton : UIView { //MARK: - IBOutlets @IBOutlet private var contentView: UIView! @IBOutlet private var progressBarWidthConstraint: NSLayoutConstraint! @IBOutlet private var CTAButton: UIButton! @IBOutlet private var progressBar: UIView! //MARK: - Variables var delegate: CustomProgressButtonDelegate? var currentProgress: Float = 0.0 //MARK: - Functions override init(frame: CGRect) { super.init(frame: frame) setUpView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpView() } private func setUpView() { let view = viewFromNibForClass() view.frame = bounds addSubview(view) self.progressBar.backgroundColor = UIColor.gray } private func viewFromNibForClass() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView return view } func enableCTA(enable: Bool) { self.CTAButton.isEnabled = enable } //MARK: - IBActions @IBAction func didTapCTAButton(_ sender: Any) { self.delegate?.didTapCTAButton(sender) } //MARK: - Progress Bar func setProgressBar(progress: Float, animated: Bool, completion: (() -> Void)?) { self.setProgressBar(progress: progress, buttonTitle: "Yeah", progressBarColor: self.progressBar.backgroundColor, buttonTitleColor: self.CTAButton.titleColor(for: .normal), animated: animated, completion: completion) } func setProgressBar(progress: Float, buttonTitle: String, progressBarColor: UIColor?, buttonTitleColor: UIColor?, animated: Bool, completion: (() -> Void)?) { self.currentProgress = progress if (self.currentProgress < 0.0) { self.currentProgress = 0.0 } else if (self.currentProgress > 1.0) { self.currentProgress = 1.0 } self.CTAButton.isEnabled = false self.progressBarWidthConstraint.constant = CGFloat(self.currentProgress) * self.contentView.frame.width UIView.animate(withDuration: animated ? 1.0 : 0.0, animations: { self.setNeedsLayout() self.layoutIfNeeded() if let progressBarColor = progressBarColor { self.progressBar.backgroundColor = progressBarColor } if let buttonTitleColor = buttonTitleColor { self.CTAButton.setTitleColor(buttonTitleColor, for: .normal) } self.CTAButton.setTitle(buttonTitle, for: .normal) }) { (success) in completion?() } } func setProgressBarColor(color: UIColor) { self.progressBar.backgroundColor = color } func setInitialState(animated: Bool) { self.progressBarWidthConstraint.constant = 0 UIView.animate(withDuration: animated ? 1.0 : 0.0, animations: { self.setNeedsLayout() self.layoutIfNeeded() self.progressBar.backgroundColor = Colors.progressBlue self.CTAButton.setTitleColor(UIColor.white, for: .normal) self.CTAButton.setTitle("Sign In", for: .normal) }, completion: { (success) in if success { self.CTAButton.isEnabled = true } }) } }
mit
ead3d04c061bd7eb3aaa6ecf718e5451
31.956522
223
0.62876
4.7375
false
false
false
false
carabina/Decodable
Decodable/DecodingError.swift
2
1773
// // DecodingError.swift // Decodable // // Created by Johannes Lund on 2015-07-17. // Copyright © 2015 anviking. All rights reserved. // import Foundation public enum DecodingError: ErrorType, CustomDebugStringConvertible { public struct Info { public init(object: AnyObject, rootObject: AnyObject? = nil, path: [String] = []) { self.object = object self.rootObject = rootObject self.path = path } var path: [String] var object: AnyObject? var rootObject: AnyObject? var formattedPath: String { return path.joinWithSeparator(".") } } case MissingKey(key: String, info: Info) case TypeMismatch(type: Any.Type, expectedType: Any.Type, info: Info) var info: Info { get { switch self { case MissingKey(key: _, let info): return info case TypeMismatch(_, _, let info): return info } } set { switch self { case MissingKey(let key, _): self = MissingKey(key: key, info: newValue) case TypeMismatch(let type, let expectedType, _): self = TypeMismatch(type: type, expectedType: expectedType, info: newValue) } } } public var debugDescription: String { switch self { case .MissingKey(let key, let info): return "Missing Key \(key) in \(info.formattedPath) \(info.object)" case .TypeMismatch(let type, let expectedType, let info): return "TypeMismatch \(type), expected: \(expectedType) in \(info.formattedPath) object: \(info.object)" } } }
mit
1e0c1b115be2233bcc3d13832be5c9c9
27.580645
116
0.55079
4.763441
false
false
false
false
Suninus/ruby-china-ios
RubyChina/Views/FailureView.swift
5
1106
// // FailureView.swift // RubyChina // // Created by Jianqiu Xiao on 5/22/15. // Copyright (c) 2015 Jianqiu Xiao. All rights reserved. // import UIKit class FailureView: UIView { override func didMoveToSuperview() { if superview == nil { return } autoresizingMask = .FlexibleWidth | .FlexibleHeight frame = superview!.frame hidden = true let iconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) iconLabel.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleTopMargin | .FlexibleBottomMargin iconLabel.center = center iconLabel.font = .systemFontOfSize(16) iconLabel.layer.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.5).CGColor iconLabel.layer.cornerRadius = 12 iconLabel.layer.masksToBounds = true iconLabel.text = "!" iconLabel.textAlignment = .Center iconLabel.textColor = .whiteColor() addSubview(iconLabel) } func show() { hidden = false } func hide() { hidden = true } }
mit
935e3aa8bb2d1bd0506921732af99ae3
26.65
124
0.641953
4.706383
false
false
false
false
garygriswold/Bible.js
SafeBible2/SafeBible_ios/SafeBible/ViewControllers/AppViewController.swift
1
1766
// // AppViewController.swift // Settings // // Created by Gary Griswold on 10/25/18. // Copyright © 2018 ShortSands. All rights reserved. // import UIKit class AppViewController : UIViewController { override var preferredStatusBarStyle: UIStatusBarStyle { get { return AppFont.nightMode ? .lightContent : .default } } override func loadView() { super.loadView() if let navBar = self.navigationController?.navigationBar { // Controls Navbar background color navBar.barTintColor = AppFont.backgroundColor // Controls Navbar text color navBar.barStyle = (AppFont.nightMode) ? .black : .default } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.backgroundColor = AppFont.backgroundColor NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(note:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil) } /** * iOS 10 includes: .adjustsFontForContentSizeCategory, which can be set to each label to * perform automatic text size adjustment */ @objc func preferredContentSizeChanged(note: NSNotification) { AppFont.userFontDelta = 1.0 // Reset App Text Slider to middle AppFont.updateSearchFontSize() ReaderViewQueue.shared.updateCSS(css: DynamicCSS.shared.fontSize.genRule()) } }
mit
17de031e104e1204286f0b3754c51e11
32.942308
119
0.666289
5.20649
false
false
false
false
klaus01/Centipede
Centipede/UIKit/CE_UIVideoEditorController.swift
1
3612
// // CE_UIVideoEditorController.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import UIKit extension UIVideoEditorController { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: UIVideoEditorController_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIVideoEditorController_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: UIVideoEditorController_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is UIVideoEditorController_Delegate { return obj as! UIVideoEditorController_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal override func getDelegateInstance() -> UIVideoEditorController_Delegate { return UIVideoEditorController_Delegate() } @discardableResult public func ce_videoEditorController_didSaveEditedVideoToPath(handle: @escaping (UIVideoEditorController, String) -> Void) -> Self { ce._videoEditorController_didSaveEditedVideoToPath = handle rebindingDelegate() return self } @discardableResult public func ce_videoEditorController_didFailWithError(handle: @escaping (UIVideoEditorController, Error) -> Void) -> Self { ce._videoEditorController_didFailWithError = handle rebindingDelegate() return self } @discardableResult public func ce_videoEditorControllerDidCancel(handle: @escaping (UIVideoEditorController) -> Void) -> Self { ce._videoEditorControllerDidCancel = handle rebindingDelegate() return self } } internal class UIVideoEditorController_Delegate: UINavigationController_Delegate, UIVideoEditorControllerDelegate { var _videoEditorController_didSaveEditedVideoToPath: ((UIVideoEditorController, String) -> Void)? var _videoEditorController_didFailWithError: ((UIVideoEditorController, Error) -> Void)? var _videoEditorControllerDidCancel: ((UIVideoEditorController) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(videoEditorController(_:didSaveEditedVideoToPath:)) : _videoEditorController_didSaveEditedVideoToPath, #selector(videoEditorController(_:didFailWithError:)) : _videoEditorController_didFailWithError, #selector(videoEditorControllerDidCancel(_:)) : _videoEditorControllerDidCancel, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func videoEditorController(_ editor: UIVideoEditorController, didSaveEditedVideoToPath editedVideoPath: String) { _videoEditorController_didSaveEditedVideoToPath!(editor, editedVideoPath) } @objc func videoEditorController(_ editor: UIVideoEditorController, didFailWithError error: Error) { _videoEditorController_didFailWithError!(editor, error) } @objc func videoEditorControllerDidCancel(_ editor: UIVideoEditorController) { _videoEditorControllerDidCancel!(editor) } }
mit
bfb640d9d86e939ea8cd4b5bd5797d09
37
136
0.690582
4.891599
false
false
false
false
richeterre/jumu-nordost-ios
Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/Quick/Externals/Nimble/Sources/Nimble/Matchers/HaveCount.swift
9
2795
import Foundation // The `haveCount` matchers do not print the full string representation of the collection value, // instead they only print the type name and the expected count. This makes it easier to understand // the reason for failed expectations. See: https://github.com/Quick/Nimble/issues/308. // The representation of the collection content is provided in a new line as an `extendedMessage`. /// A Nimble matcher that succeeds when the actual CollectionType's count equals /// the expected value public func haveCount<T: CollectionType>(expectedValue: T.Index.Distance) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(actualValue.count)" failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))" return result } else { return false } } } /// A Nimble matcher that succeeds when the actual collection's count equals /// the expected value public func haveCount(expectedValue: Int) -> MatcherFunc<NMBCollection> { return MatcherFunc { actualExpression, failureMessage in if let actualValue = try actualExpression.evaluate() { failureMessage.postfixMessage = "have \(prettyCollectionType(actualValue)) with count \(stringify(expectedValue))" let result = expectedValue == actualValue.count failureMessage.actualValue = "\(actualValue.count)" failureMessage.extendedMessage = "Actual Value: \(stringify(actualValue))" return result } else { return false } } } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func haveCountMatcher(expected: NSNumber) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() if let value = actualValue as? NMBCollection { let expr = Expression(expression: ({ value as NMBCollection}), location: location) return try! haveCount(expected.integerValue).matches(expr, failureMessage: failureMessage) } else if let actualValue = actualValue { failureMessage.postfixMessage = "get type of NSArray, NSSet, NSDictionary, or NSHashTable" failureMessage.actualValue = "\(classAsString(actualValue.dynamicType))" } return false } } } #endif
mit
1d070197feec3fca2f15caeefb7c6db6
48.035088
126
0.687299
5.545635
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront.swift
1
1727
// // Storefront.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public class Storefront { public static func buildQuery(inContext: InContextDirective? = nil, subfields: (QueryRootQuery) -> Void) -> QueryRootQuery { let root = QueryRootQuery() root.directives = [inContext].compactMap({ $0 }) subfields(root) return root } public static func buildMutation(inContext: InContextDirective? = nil, subfields: (MutationQuery) -> Void) -> MutationQuery { let root = MutationQuery() root.directives = [inContext].compactMap({ $0 }) subfields(root) return root } }
mit
9c14f265984ddcbda95453f544a50872
37.377778
126
0.736537
4.082742
false
false
false
false
dvor/Antidote
Antidote/PinInputView.swift
1
12318
// 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 private struct Constants { static let DotsSize: CGFloat = 16 static let ButtonSize: CGFloat = 75 static let VerticalOffsetSmall: CGFloat = 12 static let VerticalOffsetBig: CGFloat = 17 static let HorizontalOffset: CGFloat = 17 } protocol PinInputViewDelegate: class { func pinInputView(_ view: PinInputView, numericButtonPressed i: Int) func pinInputViewDeleteButtonPressed(_ view: PinInputView) } class PinInputView: UIView { weak var delegate: PinInputViewDelegate? /// Entered numbers. Must be in 0...pinLength range. var enteredNumbersCount: Int = 0 { didSet { enteredNumbersCount = max(enteredNumbersCount, 0) enteredNumbersCount = min(enteredNumbersCount, pinLength) updateDotsImages() } } var topText: String { get { return topLabel.text! } set { topLabel.text = newValue } } var descriptionText: String? { get { return descriptionLabel.text } set { descriptionLabel.text = newValue } } fileprivate let pinLength: Int fileprivate let topColorComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) fileprivate let bottomColorComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) fileprivate var topLabel: UILabel! fileprivate var descriptionLabel: UILabel! fileprivate var dotsContainer: UIView! fileprivate var dotsImageViews = [UIImageView]() fileprivate var numericButtons = [UIButton]() fileprivate var deleteButton: UIButton! init(pinLength: Int, topColor: UIColor, bottomColor: UIColor) { self.pinLength = pinLength self.topColorComponents = topColor.components() self.bottomColorComponents = bottomColor.components() super.init(frame: CGRect.zero) createLabels() createDotsImageViews() createNumericButtons() createDeleteButton() installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Applies gradient colors to all subviews. Call this method after adding PinInputView to superview. */ func applyColors() { guard superview != nil else { fatalError("superview shouldn't be nil") } layoutIfNeeded() updateButtonColors() updateOtherColors() updateDotsImages() } } extension PinInputView { func numericButtonPressed(_ button: UIButton) { guard let i = numericButtons.index(of: button) else { return } delegate?.pinInputView(self, numericButtonPressed: i) } func deleteButtonPressed(_ button: UIButton) { delegate?.pinInputViewDeleteButtonPressed(self) } } private extension PinInputView { func createLabels() { topLabel = UILabel() topLabel.font = UIFont.antidoteFontWithSize(18.0, weight: .medium) addSubview(topLabel) descriptionLabel = UILabel() descriptionLabel.font = UIFont.antidoteFontWithSize(16.0, weight: .light) addSubview(descriptionLabel) } func createDotsImageViews() { for _ in 0..<pinLength { dotsContainer = UIView() dotsContainer.backgroundColor = .clear addSubview(dotsContainer) let imageView = UIImageView() dotsContainer.addSubview(imageView) dotsImageViews.append(imageView) } } func createNumericButtons() { for i in 0...9 { let button = UIButton() button.setTitle("\(i)", for: UIControlState()) button.titleLabel?.font = UIFont.systemFont(ofSize: 28.0) button.addTarget(self, action: #selector(PinInputView.numericButtonPressed(_:)), for: .touchUpInside) addSubview(button) numericButtons.append(button) } } func createDeleteButton() { deleteButton = UIButton(type: .system) // No localication on purpose deleteButton.setTitle("Delete", for: UIControlState()) deleteButton.titleLabel?.font = .systemFont(ofSize: 20.0) deleteButton.addTarget(self, action: #selector(PinInputView.deleteButtonPressed(_:)), for: .touchUpInside) addSubview(deleteButton) } func installConstraints() { topLabel.snp.makeConstraints { $0.top.equalTo(self) $0.centerX.equalTo(self) } descriptionLabel.snp.makeConstraints { $0.top.equalTo(topLabel.snp.bottom).offset(Constants.VerticalOffsetSmall) $0.centerX.equalTo(self) } installConstraintsForDotsViews() installConstraintsForZeroButton() installConstraintsForNumericButtons() deleteButton.snp.makeConstraints { $0.centerX.equalTo(numericButtons[9]) $0.centerY.equalTo(numericButtons[0]) } } func installConstraintsForDotsViews() { dotsContainer.snp.makeConstraints { $0.top.equalTo(descriptionLabel.snp.bottom).offset(Constants.VerticalOffsetBig) $0.centerX.equalTo(self) } for i in 0..<dotsImageViews.count { let imageView = dotsImageViews[i] imageView.snp.makeConstraints { $0.top.equalTo(dotsContainer) $0.bottom.equalTo(dotsContainer) $0.size.equalTo(Constants.DotsSize) if i == 0 { $0.left.equalTo(dotsContainer) } else { $0.left.equalTo(dotsImageViews[i - 1].snp.right).offset(Constants.DotsSize) } if i == (dotsImageViews.count - 1) { $0.right.equalTo(dotsContainer) } } } } func installConstraintsForZeroButton() { numericButtons[0].snp.makeConstraints { $0.top.equalTo(numericButtons[8].snp.bottom).offset(Constants.VerticalOffsetSmall) $0.bottom.equalTo(self) $0.centerX.equalTo(numericButtons[8]) $0.size.equalTo(Constants.ButtonSize) } } func installConstraintsForNumericButtons() { for i in 1...9 { let button = numericButtons[i] button.snp.makeConstraints { $0.size.equalTo(Constants.ButtonSize) switch i % 3 { case 1: $0.left.equalTo(self) case 2: $0.left.equalTo(numericButtons[i - 1].snp.right).offset(Constants.HorizontalOffset) default: $0.left.equalTo(numericButtons[i - 1].snp.right).offset(Constants.HorizontalOffset) $0.right.equalTo(self) } if i <= 3 { $0.top.equalTo(dotsContainer.snp.bottom).offset(Constants.VerticalOffsetBig) } else if i <= 6 { $0.top.equalTo(numericButtons[i - 3].snp.bottom).offset(Constants.VerticalOffsetSmall) } else { $0.top.equalTo(numericButtons[i - 3].snp.bottom).offset(Constants.VerticalOffsetSmall) } } } } func updateButtonColors() { for button in numericButtons { let topColor = gradientColorAtPointY(button.frame.minY) let centerColor = gradientColorAtPointY(button.center.y) let bottomColor = gradientColorAtPointY(button.frame.maxY) let image = gradientCircleImage(topColor: topColor, bottomColor: bottomColor, size: Constants.ButtonSize, filled: false) let highlightedImage = gradientCircleImage(topColor: topColor, bottomColor: bottomColor, size: Constants.ButtonSize, filled: true) button.setBackgroundImage(image, for: UIControlState()) button.setBackgroundImage(highlightedImage, for: .highlighted) button.setTitleColor(centerColor, for: UIControlState()) button.setTitleColor(.white, for: .highlighted) } } func updateOtherColors() { topLabel.textColor = gradientColorAtPointY(topLabel.center.y) descriptionLabel.textColor = gradientColorAtPointY(descriptionLabel.center.y) deleteButton.setTitleColor(gradientColorAtPointY(deleteButton.center.y), for: UIControlState()) } func updateDotsImages() { let topColor = gradientColorAtPointY(dotsImageViews[0].frame.minY) let bottomColor = gradientColorAtPointY(dotsImageViews[0].frame.maxY) let empty = gradientCircleImage(topColor: topColor, bottomColor: bottomColor, size: Constants.DotsSize, filled: false) let filled = gradientCircleImage(topColor: topColor, bottomColor: bottomColor, size: Constants.DotsSize, filled: true) for i in 0..<dotsImageViews.count { let imageView = dotsImageViews[i] imageView.image = (i < enteredNumbersCount) ? filled : empty } } func gradientColorAtPointY(_ y: CGFloat) -> UIColor { guard self.frame.size.height > 0 else { log("PinInputView should not be nil") return .clear } guard y >= 0 && y <= self.frame.size.height else { log("Point y \(y) is outside of view") return .clear } let percent = y / self.frame.size.height let red = topColorComponents.red + percent * (bottomColorComponents.red - topColorComponents.red) let green = topColorComponents.green + percent * (bottomColorComponents.green - topColorComponents.green) let blue = topColorComponents.blue + percent * (bottomColorComponents.blue - topColorComponents.blue) let alpha = topColorComponents.alpha + percent * (bottomColorComponents.alpha - topColorComponents.alpha) return UIColor(red: red, green: green, blue: blue, alpha: alpha) } func gradientCircleImage(topColor: UIColor, bottomColor: UIColor, size: CGFloat, filled: Bool) -> UIImage { let radius = size * UIScreen.main.scale / 2 let gradientLayer = CAGradientLayer() gradientLayer.frame.size.width = 2 * radius gradientLayer.frame.size.height = 2 * radius gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor] gradientLayer.masksToBounds = true gradientLayer.cornerRadius = radius if !filled { // apply mask let lineWidth: CGFloat = 2.0 let path = UIBezierPath() path.addArc(withCenter: CGPoint(x: radius, y: radius), radius: radius - lineWidth, startAngle: 0.0, endAngle: CGFloat(2 * M_PI), clockwise: true) let mask = CAShapeLayer() mask.frame = gradientLayer.frame mask.path = path.cgPath mask.lineWidth = lineWidth mask.fillColor = UIColor.clear.cgColor mask.strokeColor = UIColor.black.cgColor gradientLayer.mask = mask } UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
54f6ef05ce45260524331643b386413a
33.895184
114
0.589381
5.077494
false
false
false
false
stephentyrone/swift
test/Driver/PrivateDependencies/crash-added-fine.swift
5
2751
/// crash ==> main | crash --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/crash-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // CHECK-INITIAL-NOT: warning // CHECK-INITIAL: Handled main.swift // CHECK-INITIAL: Handled other.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift ./crash.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps // CHECK-ADDED-NOT: Handled // CHECK-ADDED: Handled crash.swift // CHECK-ADDED-NOT: Handled // CHECK-RECORD-ADDED-DAG: "./crash.swift": !private [ // CHECK-RECORD-ADDED-DAG: "./main.swift": [ // CHECK-RECORD-ADDED-DAG: "./other.swift": [ // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/crash-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./crash.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -enable-direct-intramodule-dependencies ./crash.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIXED %s // CHECK-FIXED-DAG: Handled crash.swift // CHECK-FIXED-DAG: Handled main.swift // CHECK-FIXED-DAG: Handled other.swift
apache-2.0
1857b196b775a7eb255962622e1f3a9e
69.538462
377
0.727372
3.217544
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Solutions/Functions 2_Exercises_Solutions.playground/Contents.swift
1
5639
//: ## Functions 2 Exercises //: In these exercise, you will be given the description for functions and their expected output assuming they are implemented correctly. It will be your job to finish the implementations. /*: ### Exercise 1 Write two versions of a function called overloadingFun. One version accepts a single `String` parameter and the other accepts a single `Int` parameter. Both functions should return a `String` describing the input value. Hint: See the example function calls to determine how to implement each function. */ func overloadingFun(s1: String) -> String { return "I'm a String with the value: " + s1 } func overloadingFun(num: Int) -> String { return "I'm an Int with the value: " + String(num) } /* Example Function Call overloadingFun(s1: "softball") // "I'm a String with the value: softball" overloadingFun(num: 12) // "I'm an Int with the value: 12" overloadingFun(num: 591) // "I'm an Int with the value: 591" overloadingFun(s1: "") // "I'm a String with the value: " */ overloadingFun(s1: "softball") overloadingFun(num: 12) overloadingFun(num: 591) overloadingFun(s1: "") //: ### Exercise 2 //: Write a function `medianAndAverage` that takes three `Int` parameters and returns a tuple with the type `(Int, Double)` where the first value is the median of the input values and the second value is the average of the input values. func medianAndAverage(num1: Int, num2: Int, num3: Int) -> (Int, Double) { var median: Int if num1 < num2 { // partial order = num1, num2 if num2 < num3 { median = num2 // known order = num1, num2, num3 } else { if num1 < num3 { median = num3 // known order = num1, num3, num2 } else { median = num1 // known order = num3, num1, num2 } } } else { // partial order = num2, num1 if num3 < num2 { median = num2 // known order = num3, num2, num1 } else { if num3 > num1 { median = num1 // known order = num2, num1, num3 } else { median = num3 // known order = num2, num3, num1 } } } return (median, Double(num1 + num2 + num3)/3.0) } /* Example Function Call medianAndAverage(num1: 1, num2: 5, num3: 6) // (5, 4) medianAndAverage(num1: 2, num2: 1, num3: 6) // (2, 3) medianAndAverage(num1: 3, num2: 15, num3: 9) // (9, 9) medianAndAverage(num1: -10, num2: 11, num3: 0) // (0, 0.333) medianAndAverage(num1: 1, num2: 2, num3: 5) // (2, 2.666) medianAndAverage(num1: 2, num2: 3, num3: 1) // (2, 2) medianAndAverage(num1: 2, num2: 2, num3: 1) // (2, 1.666) */ medianAndAverage(num1: 1, num2: 5, num3: 6) medianAndAverage(num1: 2, num2: 1, num3: 6) medianAndAverage(num1: 3, num2: 15, num3: 9) medianAndAverage(num1: -10, num2: 11, num3: 0) medianAndAverage(num1: 1, num2: 2, num3: 5) medianAndAverage(num1: 2, num2: 3, num3: 1) medianAndAverage(num1: 2, num2: 2, num3: 1) /*: ### Exercise 3 Write a function called `updateStudentRecordInOut` that performs the same task as `updateStudentRecord` except it operates upon an in-out `StudentRecord` parameter. Hint: Should this function return a value? See the example function calls for help. */ struct StudentRecord { let id: Int let name: String var pointsEarned: Int var pointsPossible: Int } func updateStudentRecordInOut(record: inout StudentRecord, pointsEarned: Int, pointsPossible: Int) { record.pointsEarned += pointsEarned record.pointsPossible += pointsPossible } var record2 = StudentRecord(id: 2, name: "Jarrod", pointsEarned: 27, pointsPossible: 30) /* Example Function Call updateStudentRecordInOut(record: &record2, pointsEarned: 4, pointsPossible: 8) record2.pointsEarned // 31 record2.pointsPossible // 38 updateStudentRecordInOut(record: &record2, pointsEarned: 8, pointsPossible: 9) record2.pointsEarned // 39 record2.pointsPossible // 47 */ updateStudentRecordInOut(record: &record2, pointsEarned: 4, pointsPossible: 8) record2.pointsEarned record2.pointsPossible updateStudentRecordInOut(record: &record2, pointsEarned: 8, pointsPossible: 9) record2.pointsEarned record2.pointsPossible /*: ### Exercise 4 (Bonus Problem!) Rewrite the nested function `innerFunction` such that the example function calls return the correct values. Hint: The `outerFunction` implements [Exclusive OR](https://en.wikipedia.org/wiki/Exclusive_or) (XOR) which is a logical operator that returns true when there is an odd number of inputs that are true. */ func outerFunction(input1: Bool, input2: Bool) -> Bool { func innerFunction(a: Bool, b: Bool) -> Bool { return !a && b /* could have also used `return a && !b` */ } return innerFunction(a: input1, b: input2) || innerFunction(a: input2, b: input1) } /* Example Function Call outerFunction(input1: false, input2: false) // false outerFunction(input1: false, input2: true) // true outerFunction(input1: true, input2: false) // true outerFunction(input1: true, input2: true) // false outerFunction(input1: outerFunction(input1: true, input2: true), input2: false) // false outerFunction(input1: outerFunction(input1: false, input2: true), input2: false) // true */ outerFunction(input1: false, input2: false) outerFunction(input1: false, input2: true) outerFunction(input1: true, input2: false) outerFunction(input1: true, input2: true) outerFunction(input1: outerFunction(input1: true, input2: true), input2: false) outerFunction(input1: outerFunction(input1: false, input2: true), input2: false)
mit
6dcc7c4368d1bd305da8f87f9b758662
34.689873
236
0.68239
3.320966
false
false
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Mail/SPMail.swift
1
3178
// 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 Foundation import MessageUI struct SPMail { static var canSendEmail: Bool { return MFMailComposeViewController.canSendMail() } static func openApp(to email: String, subject: String? = nil, body: String? = nil) { let parametrs = "mailto:\(email)?subject=\(subject ?? "")&body=\(body ?? "")".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) if parametrs != nil { if let url: URL = URL(string: parametrs!) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } } } } static func dialog(to email: String, subject: String? = nil, body: String? = nil, on viewController: UIViewController) { let mailVC = MFMailComposeViewController() mailVC.mailComposeDelegate = SPMailSingltone.sharedInstance mailVC.setToRecipients([email]) if subject != nil { mailVC.setSubject(subject!) } if body != nil { mailVC.setMessageBody(body!, isHTML: false) } viewController.present(mailVC, animated: true, completion: nil) } fileprivate final class SPMailSingltone: NSObject, MFMailComposeViewControllerDelegate { static let sharedInstance = SPMailSingltone() func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } } private init() {} } fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
mit
a06923ed9a0df8e39f3b6d9877edae8d
41.932432
160
0.694995
5.058917
false
false
false
false
codeOfRobin/Components-Personal
Sources/EmptyStateNode.swift
1
1130
// // EmptyStateNode.swift // BuildingBlocks-iOS // // Created by Robin Malhotra on 17/10/17. // Copyright © 2017 BuildingBlocks. All rights reserved. // import AsyncDisplayKit public class EmptyStateNode: ASDisplayNode { let imageNode = ASImageNode() let textNode = ASTextNode() public init(text: String) { super.init() self.imageNode.style.width = ASDimensionMake(139) self.imageNode.style.height = ASDimensionMake(142) self.imageNode.image = FrameworkImage.empty let attrs: [NSAttributedStringKey: Any] = [ NSAttributedStringKey.foregroundColor: UIColor(red:0.51, green:0.55, blue:0.58, alpha:1.00), NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0) ] self.textNode.attributedText = NSAttributedString(string: text, attributes: attrs) self.automaticallyManagesSubnodes = true } override public func didLoad() { print(self.frame) } override public func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASStackLayoutSpec(direction: .vertical, spacing: 37.0, justifyContent: .center, alignItems: .center, children: [imageNode, textNode]) } }
mit
c98d1ee35f05c95a73abc8d77024cf6b
29.513514
142
0.74845
3.689542
false
false
false
false
n-miyo/SwiftMPNowPlayingInfoCenterSample-
SwiftMPNowPlayingInfoCenterSample/ViewController.swift
1
5180
// -*- mode:swift -*- import UIKit import MediaPlayer import AVFoundation class ViewController : UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var artworkImageView: UIImageView! let TIMERINTERVAL = 0.5 var mediaItem: MPMediaItem? var player: Player? var timer: NSTimer? var counter = 0 override func viewDidLoad() { super.viewDidLoad() resetPlayer() playButton.enabled = false; titleLabel.text = "(no music)" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().beginReceivingRemoteControlEvents() becomeFirstResponder() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) UIApplication.sharedApplication().endReceivingRemoteControlEvents() resignFirstResponder() } // MARK: UIResponder override func remoteControlReceivedWithEvent(event: UIEvent) { if event.type == .RemoteControl { switch event.subtype { case .RemoteControlPlay: startPlayer() case .RemoteControlPause: stopPlayer() case .RemoteControlStop: stopPlayer() case .RemoteControlTogglePlayPause: togglePlayer() default: println("UIResponder: not supported") } } } } // MARK: Custom Logic extension ViewController { @IBAction func pressPicker(sender: UIButton) { stopPlayer(); var picker = MPMediaPickerController(mediaTypes:.Music) picker.delegate = self picker.allowsPickingMultipleItems = false picker.showsCloudItems = false picker.prompt = "music picker" presentViewController(picker, animated:true, completion:nil); } @IBAction func pressPlay(sender: UIButton) { togglePlayer() } func togglePlayer() { assert(mediaItem != nil, "mediaItem must be exist.") assert(player != nil, "player must be exist.") if mediaItem == nil || player == nil { resetPlayer() return } var p = player! if (p.playing) { stopPlayer() } else { startPlayer() } } func resetPlayer() { stopPlayer() player = nil playButton.enabled = false artworkImageView.image = nil } func createPlayer() { if mediaItem == nil { return } player = Player.createPlayer(mediaItem!) } func startPlayer() { if let p = player { p.play() playButton.setTitle("Stop", forState:.Normal); startTimer() } } func stopPlayer() { if let p = player { p.stop() playButton.setTitle("Play", forState:.Normal) stopTimer() } } func updateCounter() { UIApplication.sharedApplication().applicationIconBadgeNumber = ++counter } // MARK: Private private func startTimer() { if let t = timer { t.invalidate() } timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target:self, selector:Selector("updateCounter"), userInfo:nil, repeats:true) } private func stopTimer() { if let t = timer { t.invalidate() } timer = nil } } // MARK: MPMediaPickerControllerDelegate extension ViewController : MPMediaPickerControllerDelegate { func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) { func completion() { dismissViewControllerAnimated(true, completion:nil) } playButton.enabled = false mediaItem = nil if (mediaItemCollection.items.count <= 0) { completion() return } var i: MPMediaItem = mediaItemCollection.items[0] as MPMediaItem var b = i.valueForProperty(MPMediaItemPropertyIsCloudItem) as NSNumber if (b.boolValue) { titleLabel.text = "(sorry, not on the device)" resetPlayer() completion() return } mediaItem = i createPlayer() titleLabel.text = i.valueForProperty(MPMediaItemPropertyTitle) as? String playButton.setTitle("Play", forState:.Normal) playButton.enabled = true var img: UIImage! = player?.artwork?.imageWithSize(artworkImageView.frame.size) artworkImageView.contentMode = .ScaleAspectFit artworkImageView.clipsToBounds = true artworkImageView.image = img println("title: \(titleLabel.text)") println( "URL: \(mediaItem?.valueForProperty(MPMediaItemPropertyAssetURL))") completion() } func mediaPickerDidCancel(mediaPicker: MPMediaPickerController!) { dismissViewControllerAnimated(true, completion:nil) } }
mit
661dd0d0c07016d3101293d458bf0651
25.979167
78
0.595367
5.407098
false
false
false
false
Kushki/kushki-ios
Example/kushki-ios/TokenRequestViewController.swift
1
6403
// // TokenRequestViewController.swift // kushki-ios_Example // // Created by Bryan Lema on 9/10/19. // Copyright © 2019 Kushki. All rights reserved. // import UIKit import Kushki import WebKit class TokenRequestViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var ResponseView: UITextView! @IBOutlet weak var RequestToken: UIButton! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var cardNumber: UITextField! @IBOutlet weak var expiryMonth: UITextField! @IBOutlet weak var expiryYear: UITextField! @IBOutlet weak var cvv: UITextField! @IBOutlet weak var totalAmount: UITextField! @IBOutlet weak var webView: WKWebView! var transaction: Transaction? = nil var message: String = "" var kushki = Kushki(publicMerchantId: "e41151f380a145059b6c8f4d45002130", currency: "USD", environment: KushkiEnvironment.testing_qa) override func viewDidLoad() { super.viewDidLoad() self.webView!.navigationDelegate = self } @IBAction func clicked(_ sender: Any) { let card = Card(name: nameField.text!,number: cardNumber.text!, cvv: cvv.text!,expiryMonth: expiryMonth.text!,expiryYear: expiryYear.text!) requestKushkiToken(card: card, totalAmount: totalAmount.text!, isTest:true ) return } private func requestKushkiToken(card: Card, totalAmount: String, isTest: Bool) { self.kushki.requestToken(card: card, totalAmount: Double(totalAmount) ?? 0.0, isTest: isTest) { transaction in self.transaction = transaction let message = transaction.isSuccessful() ? transaction.token : transaction.code + ": " + transaction.message let secureId = transaction.secureId != nil ? transaction.secureId! : "" let acsURL = transaction.security!.acsURL != nil ? transaction.security!.acsURL! : "" if(transaction.security!.acsURL != nil && transaction.secureId != nil && transaction.security!.specificationVersion!.starts(with: "1.")){ self.loadWeb(payload: transaction.security!.paReq!, acsUrl: transaction.security!.acsURL!) } DispatchQueue.main.async(execute: { let alert = UIAlertController(title: "Kushki Token request", message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Ok", style: .default,handler: {(alert: UIAlertAction!) in self.secureValidation()})) self.present(alert, animated: true) var msgTotal: String = "Token response: \n\n" + message if (secureId != "") { msgTotal.append("\nSecureId: " + secureId) } if (acsURL != "") { msgTotal.append("\nAcsUrl: " + acsURL) } self.ResponseView.text = msgTotal }) } } private func loadWeb(payload: String,acsUrl:String){ let termUrl = "https://m.youtube.com" //TERM_URL_VALUE_HERE var components = URLComponents(string: acsUrl)! components.queryItems = [URLQueryItem(name: "PaReq", value: payload), URLQueryItem(name: "TermUrl", value: termUrl), URLQueryItem(name: "MD", value: "123456")] components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") let url = components.url! var request = URLRequest(url: url) request.httpMethod = "POST" request.allHTTPHeaderFields = ["Content-Type":"x-www-form-urlencoded"] DispatchQueue.main.async { self.webView!.load(request) } } func secureValidation(){ if(self.transaction!.security!.acsURL != nil && self.transaction!.secureId != nil && self.transaction!.security!.specificationVersion!.starts(with: "2.")){ self.kushki.requestSecureValidation(secureServiceId: self.transaction!.secureId!, otpValue: ""){secureValidation in print(secureValidation) DispatchQueue.main.async { let alert = UIAlertController(title: "Kushki Request Validation", message: secureValidation.message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Ok", style: .default)) self.present(alert, animated: true) } } } } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { print("intercept") print(navigationAction.request) if let url = navigationAction.request.url?.absoluteString { if (url.contains("https://m.youtube.com")) { if(url == "https://m.youtube.com/") { if(self.transaction != nil){ self.kushki.requestSecureValidation(secureServiceId: self.transaction!.secureId!, otpValue: ""){secureValidation in print(secureValidation) } self.kushki.requestSecureValidation(secureServiceId: self.transaction!.secureId!, otpValue: ""){secureValidation in print(secureValidation) DispatchQueue.main.async { let alert = UIAlertController(title: "Kushki Request Validation", message: secureValidation.message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Ok", style: .default)) self.present(alert, animated: true) } } } } } } decisionHandler(.allow) } }
mit
974d5b43d2023b24b0b25d13e3044e2d
47.5
171
0.565761
5.146302
false
false
false
false
material-motion/material-motion-swift
tests/unit/operator/lowerBoundTests.swift
1
1111
/* Copyright 2017-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 XCTest import MaterialMotion class lowerBoundTests: XCTestCase { func testValueNeverGoesBelowBound() { let property = createProperty() var values: [CGFloat] = [] let subscription = property.lowerBound(-1).subscribeToValue { value in values.append(value) } property.value = 10 property.value = 0 property.value = -10 property.value = -1 property.value = 0 XCTAssertEqual(values, [0, 10, 0, -1, -1, 0]) subscription.unsubscribe() } }
apache-2.0
c383a2da5ce3ee0b7473dca0274b1841
26.775
74
0.727273
4.306202
false
true
false
false
superman-coder/pakr
pakr/pakr/AWSClient.swift
1
10228
// // AWSClient.swift // pakr // // Created by Huynh Quang Thao on 4/22/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation import AWSS3 class AWSClient { var uploadRequests = Array<AWSS3TransferManagerUploadRequest?>() var downloadRequests = Array<AWSS3TransferManagerDownloadRequest?>() var uploadFileURLs = Array<NSURL?>() var downloadFileURLs = Array<NSURL?>() init() { FileUtils.createTemporaryDirectoryWithName("upload") FileUtils.createTemporaryDirectoryWithName("download") } // MARK: prepare for upload image. func prepareUploadImage(user: String!, image: UIImage) -> (AWSS3TransferManagerUploadRequest, NSURL){ // get data and compress from image let imageData = UIImageJPEGRepresentation(image, 0.9); // get file. and write to file. we just can send to amazon when having file url // let fileName = NSProcessInfo.processInfo().globallyUniqueString.stringByAppendingString(".jpeg") let fileName = imageData?.MD5().stringByAppendingString(".jpeg") let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("upload").URLByAppendingPathComponent(fileName!) let filePath = fileURL.path! // start to write image into disk imageData!.writeToFile(filePath, atomically: true) // create upload request for AWS let uploadRequest = AWSS3TransferManagerUploadRequest() // make it public. so anyone can use this links uploadRequest.ACL = AWSS3ObjectCannedACL.PublicRead uploadRequest.body = fileURL uploadRequest.contentType = "image/jpeg" uploadRequest.key = user + "/" + fileName! uploadRequest.bucket = Constants.AWS.S3BucketName return (uploadRequest, fileURL) } // MARK: upload image to Amazon S3 service func uploadImage(user: String!, image: UIImage, success: (String -> Void)?, error: (Void -> Void)?, progress: (Int -> Void)?) { let (uploadRequest, _) = prepareUploadImage(user, image: image) // upload this request upload(uploadRequest, success: success, error: error, progress: progress) } // MARK: add image request to queue for later download func prepareImageRequest(user: String!, image: UIImage) { let (uploadRequest, fileURL) = prepareUploadImage(user, image: image) uploadRequests.append(uploadRequest) uploadFileURLs.append(fileURL) } // MARK: upload a single request to Amazon S3 service func upload(uploadRequest: AWSS3TransferManagerUploadRequest, success: (String -> Void)?, error: (Void -> Void)?, progress: (Int -> Void)?) { let transferManager = AWSS3TransferManager.defaultS3TransferManager() // NSNotificationCenter.defaultCenter().postNotificationName(EventSignal.UploadStartEvent, object: // set upload request progress callback uploadRequest.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in if totalBytesExpectedToSend > 0 { if (totalBytesSent == totalBytesExpectedToSend) { print("Upload finish") } else { let percent = Int(Double(totalBytesSent) / Double(totalBytesExpectedToSend) * 100) let userInfo : [String:Int] = ["percent": percent] NSNotificationCenter.defaultCenter().postNotificationName(EventSignal.UploadProgressEvent, object: nil, userInfo: userInfo) progress?(percent) } } }) } // callback for upload result transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in if let error = task.error { if error.domain == AWSS3TransferManagerErrorDomain as String { if let errorCode = AWSS3TransferManagerErrorType(rawValue: error.code) { switch (errorCode) { case .Cancelled, .Paused: dispatch_async(dispatch_get_main_queue(), { () -> Void in print("Upload is canceled or paused") }) break; default: print("upload() failed: [\(error)]") break; } } else { print("upload() failed: [\(error)]") } } else { print("upload() failed: [\(error)]") } } if let exception = task.exception { print("upload() failed: [\(exception)]") } if task.result != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in let url = Constants.AWS.AWS_DOMAIN + uploadRequest.key! let userInfo : [String:String] = ["server_url": url] NSNotificationCenter.defaultCenter().postNotificationName(EventSignal.UploadDoneEvent, object: nil, userInfo: userInfo) success?(url) }) } else { print("shit") } return nil } } // MARK: Download single request func download(downloadRequest: AWSS3TransferManagerDownloadRequest, success: Void -> Void, error: Void -> Void) { switch (downloadRequest.state) { case .NotStarted, .Paused: // get default transfer manager let transferManager = AWSS3TransferManager.defaultS3TransferManager() transferManager.download(downloadRequest).continueWithBlock({ (task) -> AnyObject! in // handle exception if let error = task.error { if error.domain == AWSS3TransferManagerErrorDomain as String && AWSS3TransferManagerErrorType(rawValue: error.code) == AWSS3TransferManagerErrorType.Paused { print("Download paused.") } else { print("download failed: [\(error)]") } } else if let exception = task.exception { print("download failed: [\(exception)]") } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in success() }) } return nil }) break default: break } } // MARK: Download all files func downloadAll(success: Void -> Void, error: Void -> Void) { for (_, value) in self.downloadRequests.enumerate() { if let downloadRequest = value { if downloadRequest.state == .NotStarted || downloadRequest.state == .Paused { self.download(downloadRequest, success: success, error: error) } } } } // MARK: Upload all files func uploadAll() { for (index, value) in self.uploadRequests.enumerate() { if let uploadRequest = value { if uploadRequest.state == .NotStarted || uploadRequest.state == .Paused { self.upload(uploadRequest, success: { (fileUrl) in self.uploadFileURLs[index] = nil self.uploadRequests[index] = nil }, error: { (Void) in // currently do nothing here }, progress: { (progress) in // currently do nothing here }) } } } } func cancelAllUploads() { for (_, uploadRequest) in self.uploadRequests.enumerate() { if let uploadRequest = uploadRequest { uploadRequest.cancel().continueWithBlock({ (task) -> AnyObject! in if let error = task.error { print("cancel() failed: [\(error)]") } if let exception = task.exception { print("cancel() failed: [\(exception)]") } return nil }) } } } // MARK: Cancel all downloads in queue func cancelAllDownloads() { for (_, value) in self.downloadRequests.enumerate() { if let downloadRequest = value { if downloadRequest.state == .Running || downloadRequest.state == .Paused { downloadRequest.cancel().continueWithBlock({ (task) -> AnyObject! in if let error = task.error { print("cancel() failed: [\(error)]") } else if let exception = task.exception { print("cancel() failed: [\(exception)]") } return nil }) } } } } // MARK: get download index in queue func indexOfDownloadRequest(downloadRequest: AWSS3TransferManagerDownloadRequest?) -> Int? { for (index, object) in downloadRequests.enumerate() { if object == downloadRequest { return index } } return nil } // MARK: get upload index in queue func indexOfUploadRequest(uploadRequest: AWSS3TransferManagerUploadRequest?) -> Int? { for (index, object) in uploadRequests.enumerate() { if object == uploadRequest { return index } } return nil } }
apache-2.0
d7ddf710061edf0fb852825c3af475e1
39.587302
147
0.52645
5.739057
false
false
false
false
mohamede1945/quran-ios
Quran/SQLiteQariTimingRetriever.swift
2
2286
// // SQLiteQariTimingRetriever.swift // Quran // // Created by Mohamed Afifi on 5/20/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation import PromiseKit struct SQLiteQariTimingRetriever: QariTimingRetriever { let persistenceCreator: AnyCreator<URL, QariAyahTimingPersistence> func retrieveTiming(for qari: Qari, startAyah: AyahNumber) -> Promise<[AyahNumber: AyahTiming]> { guard case .gapless(let databaseName) = qari.audioType else { fatalError("Gapped qaris are not supported.") } return DispatchQueue.default.promise2 { let fileURL = qari.localFolder().appendingPathComponent(databaseName).appendingPathExtension(Files.databaseLocalFileExtension) let persistence = self.persistenceCreator.create(fileURL) let timings = try persistence.getTimingForSura(startAyah: startAyah) return timings } } func retrieveTiming(for qari: Qari, suras: [Int]) -> Promise<[Int: [AyahTiming]]> { guard case .gapless(let databaseName) = qari.audioType else { fatalError("Gapped qaris are not supported.") } return DispatchQueue.default.promise2 { let fileURL = qari.localFolder().appendingPathComponent(databaseName).appendingPathExtension(Files.databaseLocalFileExtension) let persistence = self.persistenceCreator.create(fileURL) var result: [Int: [AyahTiming]] = [:] for sura in suras { let timings = try persistence.getOrderedTimingForSura(startAyah: AyahNumber(sura: sura, ayah: 1)) result[sura] = timings } return result } } }
gpl-3.0
ceb4065cee5070bedf32cc2f70f61122
39.105263
142
0.681102
4.694045
false
false
false
false
arvedviehweger/swift
stdlib/public/core/Collection.swift
1
76861
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements, with forward /// index traversal. /// /// In most cases, it's best to ignore this protocol and use the `Collection` /// protocol instead, because it has a more complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead") public typealias IndexableBase = _IndexableBase public protocol _IndexableBase { // FIXME(ABI)#24 (Recursive Protocol Constraints): there is no reason for this protocol // to exist apart from missing compiler features that we emulate with it. // rdar://problem/20531108 // // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Iterator` type from a minimal collection, but it is also used in // exposed places like as a constraint on `IndexingIterator`. /// A type that represents a position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript /// argument. /// /// - SeeAlso: endIndex associatedtype Index : Comparable /// The position of the first element in a nonempty collection. /// /// If the collection is empty, `startIndex` is equal to `endIndex`. var startIndex: Index { get } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// When you need a range that includes the last element of a collection, use /// the half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let index = numbers.index(of: 30) { /// print(numbers[index ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the collection is empty, `endIndex` is equal to `startIndex`. var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a Collection.Iterator.Element that can // be used as IndexingIterator<T>'s Element. Here we arrange for // the Collection itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this Element to be the same // as Collection.Iterator.Element (see below), but we have no way of // expressing it today. associatedtype _Element /// Accesses the element at the specified position. /// /// The following example accesses an element of an array through its /// subscript to print its value: /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// print(streets[1]) /// // Prints "Bryant" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) subscript(position: Index) -> _Element { get } // WORKAROUND: rdar://25214066 // FIXME(ABI)#178 (Type checker) /// A sequence that represents a contiguous subrange of the collection's /// elements. associatedtype SubSequence /// Accesses the subsequence bounded by the given range. /// /// - Parameter bounds: A range of the collection's indices. The upper and /// lower bounds of the range must be valid indices of the collection. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition(bounds.contains(index)) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition( /// bounds.contains(range.lowerBound) || /// range.lowerBound == bounds.upperBound) /// precondition( /// bounds.contains(range.upperBound) || /// range.upperBound == bounds.upperBound) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// /// - SeeAlso: `index(after:)` func formIndex(after i: inout Index) } /// A type that provides subscript access to its elements, with forward index /// traversal. /// /// In most cases, it's best to ignore this protocol and use the `Collection` /// protocol instead, because it has a more complete interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead") public typealias Indexable = _Indexable public protocol _Indexable : _IndexableBase { /// A type that represents the number of steps between two indices, where /// one value is reachable from the other. /// /// In Swift, *reachability* refers to the ability to produce one value from /// the other through zero or more applications of `index(after:)`. associatedtype IndexDistance : SignedInteger = Int /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index(_ i: Index, offsetBy n: IndexDistance) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? /// Offsets the given index by the specified distance. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func formIndex(_ i: inout Index, offsetBy n: IndexDistance) /// Offsets the given index by the specified distance, or so that it equals /// the given limiting index. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: `true` if `i` has been offset by exactly `n` steps without /// going beyond `limit`; otherwise, `false`. When the return value is /// `false`, the value of `i` is equal to `limit`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func formIndex( _ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Bool /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. func distance(from start: Index, to end: Index) -> IndexDistance } /// A type that iterates over a collection using its indices. /// /// The `IndexingIterator` type is the default iterator for any collection that /// doesn't declare its own. It acts as an iterator by using a collection's /// indices to step over each value in the collection. Most collections in the /// standard library use `IndexingIterator` as their iterator. /// /// By default, any custom collection type you create will inherit a /// `makeIterator()` method that returns an `IndexingIterator` instance, /// making it unnecessary to declare your own. When creating a custom /// collection type, add the minimal requirements of the `Collection` /// protocol: starting and ending indices and a subscript for accessing /// elements. With those elements defined, the inherited `makeIterator()` /// method satisfies the requirements of the `Sequence` protocol. /// /// Here's an example of a type that declares the minimal requirements for a /// collection. The `CollectionOfTwo` structure is a fixed-size collection /// that always holds two elements of a specific type. /// /// struct CollectionOfTwo<Element>: Collection { /// let elements: (Element, Element) /// /// init(_ first: Element, _ second: Element) { /// self.elements = (first, second) /// } /// /// var startIndex: Int { return 0 } /// var endIndex: Int { return 2 } /// /// subscript(index: Int) -> Element { /// switch index { /// case 0: return elements.0 /// case 1: return elements.1 /// default: fatalError("Index out of bounds.") /// } /// } /// /// func index(after i: Int) -> Int { /// precondition(i < endIndex, "Can't advance beyond endIndex") /// return i + 1 /// } /// } /// /// The `CollectionOfTwo` type uses the default iterator type, /// `IndexingIterator`, because it doesn't define its own `makeIterator()` /// method or `Iterator` associated type. This example shows how a /// `CollectionOfTwo` instance can be created holding the values of a point, /// and then iterated over using a `for`-`in` loop. /// /// let point = CollectionOfTwo(15.0, 20.0) /// for element in point { /// print(element) /// } /// // Prints "15.0" /// // Prints "20.0" @_fixed_layout public struct IndexingIterator< Elements : _IndexableBase // FIXME(ABI)#97 (Recursive Protocol Constraints): // Should be written as: // Elements : Collection > : IteratorProtocol, Sequence { @_inlineable /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements) { self._elements = _elements self._position = _elements.startIndex } @_inlineable /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements, _position: Elements.Index) { self._elements = _elements self._position = _position } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns all the elements of the underlying /// sequence in order. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// This example shows how an iterator can be used explicitly to emulate a /// `for`-`in` loop. First, retrieve a sequence's iterator, and then call /// the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence if a next element /// exists; otherwise, `nil`. @_inlineable public mutating func next() -> Elements._Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _elements.formIndex(after: &_position) return element } @_versioned internal let _elements: Elements @_versioned internal var _position: Elements.Index } /// A sequence whose elements can be traversed multiple times, /// nondestructively, and accessed by indexed subscript. /// /// Collections are used extensively throughout the standard library. When you /// use arrays, dictionaries, views of a string's contents and other types, /// you benefit from the operations that the `Collection` protocol declares /// and implements. /// /// In addition to the methods that collections inherit from the `Sequence` /// protocol, you gain access to methods that depend on accessing an element /// at a specific position when using a collection. /// /// For example, if you want to print only the first word in a string, search /// for the index of the first space and then create a subsequence up to that /// position. /// /// let text = "Buffalo buffalo buffalo buffalo." /// if let firstSpace = text.characters.index(of: " ") { /// print(String(text.characters.prefix(upTo: firstSpace))) /// } /// // Prints "Buffalo" /// /// The `firstSpace` constant is an index into the `text.characters` /// collection. `firstSpace` is the position of the first space in the /// collection. You can store indices in variables, and pass them to /// collection algorithms or use them later to access the corresponding /// element. In the example above, `firstSpace` is used to extract the prefix /// that contains elements up to that index. /// /// You can pass only valid indices to collection operations. You can find a /// complete set of a collection's valid indices by starting with the /// collection's `startIndex` property and finding every successor up to, and /// including, the `endIndex` property. All other values of the `Index` type, /// such as the `startIndex` property of a different collection, are invalid /// indices for this collection. /// /// Saved indices may become invalid as a result of mutating operations; for /// more information about index invalidation in mutable collections, see the /// reference for the `MutableCollection` and `RangeReplaceableCollection` /// protocols, as well as for the specific type you're using. /// /// Accessing Individual Elements /// ============================= /// /// You can access an element of a collection through its subscript with any /// valid index except the collection's `endIndex` property, a "past the end" /// index that does not correspond with any element of the collection. /// /// Here's an example of accessing the first character in a string through its /// subscript: /// /// let firstChar = text.characters[text.characters.startIndex] /// print(firstChar) /// // Prints "B" /// /// The `Collection` protocol declares and provides default implementations for /// many operations that depend on elements being accessible by their /// subscript. For example, you can also access the first character of `text` /// using the `first` property, which has the value of the first element of /// the collection, or `nil` if the collection is empty. /// /// print(text.characters.first) /// // Prints "Optional("B")" /// /// Accessing Slices of a Collection /// ================================ /// /// You can access a slice of a collection through its ranged subscript or by /// calling methods like `prefix(_:)` or `suffix(from:)`. A slice of a /// collection can contain zero or more of the original collection's elements /// and shares the original collection's semantics. /// /// The following example, creates a `firstWord` constant by using the /// `prefix(_:)` method to get a slice of the `text` string's `characters` /// view. /// /// let firstWord = text.characters.prefix(7) /// print(String(firstWord)) /// // Prints "Buffalo" /// /// You can retrieve the same slice using other methods, such as finding the /// terminating index, and then using the `prefix(upTo:)` method, which takes /// an index as its parameter, or by using the view's ranged subscript. /// /// if let firstSpace = text.characters.index(of: " ") { /// print(text.characters.prefix(upTo: firstSpace)) /// // Prints "Buffalo" /// /// let start = text.characters.startIndex /// print(text.characters[start..<firstSpace]) /// // Prints "Buffalo" /// } /// /// The retrieved slice of `text.characters` is equivalent in each of these /// cases. /// /// Slices Share Indices /// -------------------- /// /// A collection and its slices share the same indices. An element of a /// collection is located under the same index in a slice as in the base /// collection, as long as neither the collection nor the slice has been /// mutated since the slice was created. /// /// For example, suppose you have an array holding the number of absences from /// each class during a session. /// /// var absences = [0, 2, 0, 4, 0, 3, 1, 0] /// /// You're tasked with finding the day with the most absences in the second /// half of the session. To find the index of the day in question, follow /// these steps: /// /// 1) Create a slice of the `absences` array that holds the second half of the /// days. /// 2) Use the `max(by:)` method to determine the index of the day with the /// most absences. /// 3) Print the result using the index found in step 2 on the original /// `absences` array. /// /// Here's an implementation of those steps: /// /// let secondHalf = absences.suffix(absences.count / 2) /// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) { /// print("Highest second-half absences: \(absences[i])") /// } /// // Prints "Highest second-half absences: 3" /// /// Slices Inherit Collection Semantics /// ----------------------------------- /// /// A slice inherits the value or reference semantics of its base collection. /// That is, when working with a slice of a mutable /// collection that has value semantics, such as an array, mutating the /// original collection triggers a copy of that collection, and does not /// affect the contents of the slice. /// /// For example, if you update the last element of the `absences` array from /// `0` to `2`, the `secondHalf` slice is unchanged. /// /// absences[7] = 2 /// print(absences) /// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]" /// print(secondHalf) /// // Prints "[0, 3, 1, 0]" /// /// Traversing a Collection /// ======================= /// /// Although a sequence can be consumed as it is traversed, a collection is /// guaranteed to be multipass: Any element may be repeatedly accessed by /// saving its index. Moreover, a collection's indices form a finite range of /// the positions of the collection's elements. This guarantees the safety of /// operations that depend on a sequence being finite, such as checking to see /// whether a collection contains an element. /// /// Iterating over the elements of a collection by their positions yields the /// same elements in the same order as iterating over that collection using /// its iterator. This example demonstrates that the `characters` view of a /// string returns the same characters in the same order whether the view's /// indices or the view itself is being iterated. /// /// let word = "Swift" /// for character in word.characters { /// print(character) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// for i in word.characters.indices { /// print(word.characters[i]) /// } /// // Prints "S" /// // Prints "w" /// // Prints "i" /// // Prints "f" /// // Prints "t" /// /// Conforming to the Collection Protocol /// ===================================== /// /// If you create a custom sequence that can provide repeated access to its /// elements, make sure that its type conforms to the `Collection` protocol in /// order to give a more useful and more efficient interface for sequence and /// collection operations. To add `Collection` conformance to your type, you /// must declare at least the four following requirements: /// /// - the `startIndex` and `endIndex` properties, /// - a subscript that provides at least read-only access to your type's /// elements, and /// - the `index(after:)` method for advancing an index into your collection. /// /// Expected Performance /// ==================== /// /// Types that conform to `Collection` are expected to provide the `startIndex` /// and `endIndex` properties and subscript access to elements as O(1) /// operations. Types that are not able to guarantee that expected performance /// must document the departure, because many collection operations depend on /// O(1) subscripting performance for their own performance guarantees. /// /// The performance of some collection operations depends on the type of index /// that the collection provides. For example, a random-access collection, /// which can measure the distance between two indices in O(1) time, will be /// able to calculate its `count` property in O(1) time. Conversely, because a /// forward or bidirectional collection must traverse the entire collection to /// count the number of contained elements, accessing its `count` property is /// an O(*n*) operation. public protocol Collection : _Indexable, Sequence { /// A type that represents the number of steps between a pair of /// indices. associatedtype IndexDistance = Int /// A type that provides the collection's iteration interface and /// encapsulates its iteration state. /// /// By default, a collection conforms to the `Sequence` protocol by /// supplying `IndexingIterator` as its associated `Iterator` /// type. associatedtype Iterator = IndexingIterator<Self> where Self.Iterator.Element == _Element // FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from // a custom `makeIterator()` function. Otherwise we get an // `IndexingIterator`. <rdar://problem/21539115> /// Returns an iterator over the elements of the collection. func makeIterator() -> Iterator /// A sequence that represents a contiguous subrange of the collection's /// elements. /// /// This associated type appears as a requirement in the `Sequence` /// protocol, but it is restated here with stricter constraints. In a /// collection, the subsequence should also conform to `Collection`. associatedtype SubSequence : _IndexableBase, Sequence = Slice<Self> where Self.SubSequence.Index == Index, Self.Iterator.Element == Self.SubSequence.Iterator.Element, SubSequence.SubSequence == SubSequence // FIXME(ABI)#98 (Recursive Protocol Constraints): // FIXME(ABI)#99 (Associated Types with where clauses): // associatedtype SubSequence : Collection // where // SubSequence.Indices == Indices, // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Accesses the element at the specified position. /// /// The following example accesses an element of an array through its /// subscript to print its value: /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// print(streets[1]) /// // Prints "Bryant" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// /// - Complexity: O(1) subscript(position: Index) -> Iterator.Element { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices : _Indexable, Sequence = DefaultIndices<Self> where Indices.Iterator.Element == Index, Indices.Index == Index, Indices.SubSequence == Indices // FIXME(ABI)#100 (Recursive Protocol Constraints): // associatedtype Indices : Collection // where // = DefaultIndices<Self> /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be nonuniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can result in an unexpected copy of the collection. To avoid /// the unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } /// Returns a subsequence from the start of the collection up to, but not /// including, the specified position. /// /// The resulting subsequence *does not include* the element at the position /// `end`. The following example searches for the index of the number `40` /// in an array of integers, and then prints the prefix of the array up to, /// but not including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(upTo: i)) /// } /// // Prints "[10, 20, 30]" /// /// Passing the collection's starting index as the `end` parameter results in /// an empty subsequence. /// /// print(numbers.prefix(upTo: numbers.startIndex)) /// // Prints "[]" /// /// - Parameter end: The "past the end" index of the resulting subsequence. /// `end` must be a valid index of the collection. /// - Returns: A subsequence up to, but not including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(through:)` func prefix(upTo end: Index) -> SubSequence /// Returns a subsequence from the specified position to the end of the /// collection. /// /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the suffix of the array starting at /// that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.suffix(from: i)) /// } /// // Prints "[40, 50, 60]" /// /// Passing the collection's `endIndex` as the `start` parameter results in /// an empty subsequence. /// /// print(numbers.suffix(from: numbers.endIndex)) /// // Prints "[]" /// /// - Parameter start: The index at which to start the resulting subsequence. /// `start` must be a valid index of the collection. /// - Returns: A subsequence starting at the `start` position. /// /// - Complexity: O(1) func suffix(from start: Index) -> SubSequence /// Returns a subsequence from the start of the collection through the /// specified position. /// /// The resulting subsequence *includes* the element at the position `end`. /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the prefix of the array up to, and /// including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(through: i)) /// } /// // Prints "[10, 20, 30, 40]" /// /// - Parameter end: The index of the last element to include in the /// resulting subsequence. `end` must be a valid index of the collection /// that is not equal to the `endIndex` property. /// - Returns: A subsequence up to, and including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(upTo:)` func prefix(through position: Index) -> SubSequence /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.characters.isEmpty { /// print("I've been through the desert on a horse with no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!") /// /// - Complexity: O(1) var isEmpty: Bool { get } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. var count: IndexDistance { get } // The following requirement enables dispatching for index(of:) when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found /// or `Optional(nil)` if an element was determined to be missing; /// otherwise, `nil`. /// /// - Complexity: O(*n*) func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? /// The first element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let firstNumber = numbers.first { /// print(firstNumber) /// } /// // Prints "10" var first: Iterator.Element? { get } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index(_ i: Index, offsetBy n: IndexDistance) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. func distance(from start: Index, to end: Index) -> IndexDistance } /// Default implementation for forward collections. extension _Indexable { /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inline(__always) public func formIndex(after i: inout Index) { i = index(after: i) } @_inlineable public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "out of bounds: index < startIndex") _precondition( index < bounds.upperBound, "out of bounds: index >= endIndex") } @_inlineable public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= index, "out of bounds: index < startIndex") _precondition( index <= bounds.upperBound, "out of bounds: index > endIndex") } @_inlineable public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) { // FIXME: swift-3-indexing-model: tests. _precondition( bounds.lowerBound <= range.lowerBound, "out of bounds: range begins before startIndex") _precondition( range.lowerBound <= bounds.upperBound, "out of bounds: range ends after endIndex") _precondition( bounds.lowerBound <= range.upperBound, "out of bounds: range ends before bounds.lowerBound") _precondition( range.upperBound <= bounds.upperBound, "out of bounds: range begins after bounds.upperBound") } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { return self._advanceForward(i, by: n) } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { return self._advanceForward(i, by: n, limitedBy: limit) } /// Offsets the given index by the specified distance. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) { i = index(i, offsetBy: n) } /// Offsets the given index by the specified distance, or so that it equals /// the given limiting index. /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. `n` must not be negative unless the /// collection conforms to the `BidirectionalCollection` protocol. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: `true` if `i` has been offset by exactly `n` steps without /// going beyond `limit`; otherwise, `false`. When the return value is /// `false`, the value of `i` is equal to `limit`. /// /// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)` /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute /// value of `n`. @_inlineable public func formIndex( _ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the /// resulting distance. @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { _precondition(start <= end, "Only BidirectionalCollections can have end come before start") var start = start var count: IndexDistance = 0 while start != end { count = count + 1 formIndex(after: &start) } return count } /// Do not use this method directly; call advanced(by: n) instead. @_inlineable @_versioned @inline(__always) internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { formIndex(after: &i) } return i } /// Do not use this method directly; call advanced(by: n, limit) instead. @_inlineable @_versioned @inline(__always) internal func _advanceForward( _ i: Index, by n: IndexDistance, limitedBy limit: Index ) -> Index? { _precondition(n >= 0, "Only BidirectionalCollections can be advanced by a negative amount") var i = i for _ in stride(from: 0, to: n, by: 1) { if i == limit { return nil } formIndex(after: &i) } return i } } /// Supply the default `makeIterator()` method for `Collection` models /// that accept the default associated `Iterator`, /// `IndexingIterator<Self>`. extension Collection where Iterator == IndexingIterator<Self> { /// Returns an iterator over the elements of the collection. @inline(__always) public func makeIterator() -> IndexingIterator<Self> { return IndexingIterator(_elements: self) } } /// Supply the default "slicing" `subscript` for `Collection` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension Collection where SubSequence == Slice<Self> { /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) @_inlineable public subscript(bounds: Range<Index>) -> Slice<Self> { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return Slice(base: self, bounds: bounds) } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// - Returns: The first element of the collection if the collection is /// not empty; otherwise, `nil`. /// /// - Complexity: O(1) @_inlineable public mutating func popFirst() -> Iterator.Element? { // TODO: swift-3-indexing-model - review the following guard !isEmpty else { return nil } let element = first! self = self[index(after: startIndex)..<endIndex] return element } } /// Default implementations of core requirements extension Collection { /// A Boolean value indicating whether the collection is empty. /// /// When you need to check whether your collection is empty, use the /// `isEmpty` property instead of checking that the `count` property is /// equal to zero. For collections that don't conform to /// `RandomAccessCollection`, accessing the `count` property iterates /// through the elements of the collection. /// /// let horseName = "Silver" /// if horseName.characters.isEmpty { /// print("I've been through the desert on a horse with no name.") /// } else { /// print("Hi ho, \(horseName)!") /// } /// // Prints "Hi ho, Silver!") /// /// - Complexity: O(1) @_inlineable public var isEmpty: Bool { return startIndex == endIndex } /// The first element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let firstNumber = numbers.first { /// print(firstNumber) /// } /// // Prints "10" @_inlineable public var first: Iterator.Element? { // NB: Accessing `startIndex` may not be O(1) for some lazy collections, // so instead of testing `isEmpty` and then returning the first element, // we'll just rely on the fact that the iterator always yields the // first element first. var i = makeIterator() return i.next() } // TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?) /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) // public var first: Iterator.Element? { // return isEmpty ? nil : self[startIndex] // } /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable public var underestimatedCount: Int { // TODO: swift-3-indexing-model - review the following return numericCast(count) } /// The number of elements in the collection. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable public var count: IndexDistance { return distance(from: startIndex, to: endIndex) } // TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)? /// Customization point for `Collection.index(of:)`. /// /// Define this method if the collection can find an element in less than /// O(*n*) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(`count`). @_inlineable public // dispatching func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for Collection //===----------------------------------------------------------------------===// extension Collection { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercaseString } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @_inlineable public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { // TODO: swift-3-indexing-model - review the following let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i])) formIndex(after: &i) } _expectEnd(of: self, is: i) return Array(result) } /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the collection. @_inlineable public func dropFirst(_ n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = index(startIndex, offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// collection. `n` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off the specified number of elements /// at the end. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func dropLast(_ n: Int) -> SubSequence { _precondition( n >= 0, "Can't drop a negative number of elements from a collection") let amount = Swift.max(0, numericCast(count) - n) let end = index(startIndex, offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be skipped or `false` if it should be included. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { var start = startIndex while try start != endIndex && predicate(self[start]) { formIndex(after: &start) } return self[start..<endIndex] } /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this collection /// with at most `maxLength` elements. @_inlineable public func prefix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = index(startIndex, offsetBy: numericCast(maxLength), limitedBy: endIndex) ?? endIndex return self[startIndex..<end] } /// Returns a subsequence containing the initial elements until `predicate` /// returns `false` and skipping the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns `true` if the element should /// be included or `false` if it should be excluded. Once the predicate /// returns `false` it will not be called again. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence { var end = startIndex while try end != endIndex && predicate(self[end]) { formIndex(after: &end) } return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains all the elements in the collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = Swift.max(0, numericCast(count) - maxLength) let start = index(startIndex, offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex return self[start..<endIndex] } /// Returns a subsequence from the start of the collection up to, but not /// including, the specified position. /// /// The resulting subsequence *does not include* the element at the position /// `end`. The following example searches for the index of the number `40` /// in an array of integers, and then prints the prefix of the array up to, /// but not including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(upTo: i)) /// } /// // Prints "[10, 20, 30]" /// /// Passing the collection's starting index as the `end` parameter results in /// an empty subsequence. /// /// print(numbers.prefix(upTo: numbers.startIndex)) /// // Prints "[]" /// /// - Parameter end: The "past the end" index of the resulting subsequence. /// `end` must be a valid index of the collection. /// - Returns: A subsequence up to, but not including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(through:)` @_inlineable public func prefix(upTo end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns a subsequence from the specified position to the end of the /// collection. /// /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the suffix of the array starting at /// that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.suffix(from: i)) /// } /// // Prints "[40, 50, 60]" /// /// Passing the collection's `endIndex` as the `start` parameter results in /// an empty subsequence. /// /// print(numbers.suffix(from: numbers.endIndex)) /// // Prints "[]" /// /// - Parameter start: The index at which to start the resulting subsequence. /// `start` must be a valid index of the collection. /// - Returns: A subsequence starting at the `start` position. /// /// - Complexity: O(1) @_inlineable public func suffix(from start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns a subsequence from the start of the collection through the /// specified position. /// /// The resulting subsequence *includes* the element at the position `end`. /// The following example searches for the index of the number `40` in an /// array of integers, and then prints the prefix of the array up to, and /// including, that index: /// /// let numbers = [10, 20, 30, 40, 50, 60] /// if let i = numbers.index(of: 40) { /// print(numbers.prefix(through: i)) /// } /// // Prints "[10, 20, 30, 40]" /// /// - Parameter end: The index of the last element to include in the /// resulting subsequence. `end` must be a valid index of the collection /// that is not equal to the `endIndex` property. /// - Returns: A subsequence up to, and including, the `end` position. /// /// - Complexity: O(1) /// - SeeAlso: `prefix(upTo:)` @_inlineable public func prefix(through position: Index) -> SubSequence { return prefix(upTo: index(after: position)) } /// Returns the longest possible subsequences of the collection, in order, /// that don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split( /// maxSplits: 1, whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the collection satisfying the `isSeparator` /// predicate. The default value is `true`. /// - isSeparator: A closure that takes an element as an argument and /// returns a Boolean value indicating whether the collection should be /// split at that element. /// - Returns: An array of subsequences, split from this collection's /// elements. @_inlineable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { // TODO: swift-3-indexing-model - review the following _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end: Index) -> Bool { if subSequenceStart == end && omittingEmptySubsequences { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplits == 0 || isEmpty { _ = appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) formIndex(after: &subSequenceEnd) subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplits { break } continue } formIndex(after: &subSequenceEnd) } if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension Collection where Iterator.Element : Equatable { /// Returns the longest possible subsequences of the collection, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the collection are not returned as part /// of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.characters.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the collection, or /// one less than the number of subsequences to return. If /// `maxSplits + 1` subsequences are returned, the last one is a suffix /// of the original collection containing the remaining elements. /// `maxSplits` must be greater than or equal to zero. The default value /// is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the collection and for each instance of `separator` at /// the start or end of the collection. If `true`, only nonempty /// subsequences are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this collection's /// elements. @_inlineable public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [SubSequence] { // TODO: swift-3-indexing-model - review the following return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Collection where SubSequence == Self { /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// /// - Returns: The first element of the collection. /// /// - Complexity: O(1) /// - SeeAlso: `popFirst()` @_inlineable @discardableResult public mutating func removeFirst() -> Iterator.Element { // TODO: swift-3-indexing-model - review the following _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[index(after: startIndex)..<endIndex] return element } /// Removes the specified number of elements from the beginning of the /// collection. /// /// - Parameter n: The number of elements to remove. `n` must be greater than /// or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*). @_inlineable public mutating func removeFirst(_ n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex] } } extension Collection { @_inlineable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return try preprocess() } } @available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.") public enum Bit {} @available(*, unavailable, renamed: "IndexingIterator") public struct IndexingGenerator<Elements : _IndexableBase> {} @available(*, unavailable, renamed: "Collection") public typealias CollectionType = Collection extension Collection { @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead") public func split( _ maxSplit: Int = Int.max, allowEmptySlices: Bool = false, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Collection where Iterator.Element : Equatable { @available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { Builtin.unreachable() } } @available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3") public struct PermutationGenerator<C : Collection, Indices : Sequence> {}
apache-2.0
79f905bc2fade7f086f5397e6247aba3
38.927792
118
0.644996
4.207642
false
false
false
false
jjatie/Charts
Source/Charts/Formatters/DefaultFillFormatter.swift
1
1423
// // DefaultFillFormatter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import CoreGraphics import Foundation /// Default formatter that calculates the position of the filled line. open class DefaultFillFormatter: FillFormatter { public typealias Block = ( _ dataSet: LineChartDataSet, _ dataProvider: LineChartDataProvider ) -> CGFloat open var block: Block? public init() {} public init(block: @escaping Block) { self.block = block } public static func with(block: @escaping Block) -> DefaultFillFormatter? { return DefaultFillFormatter(block: block) } open func getFillLinePosition( dataSet: LineChartDataSet, dataProvider: LineChartDataProvider ) -> CGFloat { guard block == nil else { return block!(dataSet, dataProvider) } var fillMin: CGFloat = 0.0 if dataSet.yRange.max > 0.0, dataSet.yRange.max < 0.0 { fillMin = 0.0 } else if let data = dataProvider.data { let max = data.yRange.max > 0.0 ? 0.0 : dataProvider.chartYMax let min = data.yRange.min < 0.0 ? 0.0 : dataProvider.chartYMin fillMin = CGFloat(dataSet.yRange.min >= 0.0 ? min : max) } return fillMin } }
apache-2.0
90ec2cc64de1d6497f9c3984ba680e74
26.365385
78
0.638089
4.391975
false
false
false
false
braindrizzlestudio/BDGradientNode
BDGradientNodeDemo/GradientViewController.swift
1
760
// // GradientViewController.swift // BDGradientNodeDemo // // Created by Braindrizzle Studio. // http://braindrizzlestudio.com // Copyright (c) 2015 Braindrizzle Studio. All rights reserved. // // This application is a demo of BDGradientNode. // import UIKit import SpriteKit class GradientViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() let skView = self.view as! SKView skView.ignoresSiblingOrder = true let scene = GradientScene() scene.size = self.view.bounds.size scene.scaleMode = .AspectFill skView.presentScene(scene) } override func prefersStatusBarHidden() -> Bool { return true } }
mit
84a78ebe60c2b5df28d5e7f0c485354f
20.111111
64
0.643421
4.52381
false
false
false
false
danthorpe/Money
Sources/Bitcoin.swift
3
3189
// // Money, https://github.com/danthorpe/Money // Created by Dan Thorpe, @danthorpe // // The MIT License (MIT) // // Copyright (c) 2015 Daniel Thorpe // // 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 // MARK: - Bitcoin Currency /** # Bitcoin Currency Type BitcoinCurrencyType is a refinement of CryptoCurrencyType, which allows type restriction when working with Bitcoin. */ public protocol BitcoinCurrencyType: CryptoCurrencyType { } public extension BitcoinCurrencyType { /// The smallest unit of Bitcoin is the Satoshi /// - see: https://en.bitcoin.it/wiki/Satoshi_(unit) static var scale: Int { return 8 } /// - returns: the currency symbol static var symbol: String? { return "Ƀ" } } public extension Currency { /** # Currency.XBT This is the ISO 4217 currency code, however at the moment it is unofficial. unicode \u{20bf} was accepted as the Bitcoin currency symbol in November. However, it's not yet available on Apple platforms. Ƀ is a popular alternative which is available. */ struct XBT: BitcoinCurrencyType { /// - returns: the proposed ISO 4217 currency code public static let code = "XBT" /// - returns: a configured NSNumberFormatter // public static let formatter: NSNumberFormatter = { // let fmtr = NSNumberFormatter() // fmtr.numberStyle = .CurrencyStyle // fmtr.maximumFractionDigits = scale // fmtr.currencySymbol = "Ƀ" // return fmtr // }() } /** # Currency.BTC This is the common code used for Bitcoin, although it can never become the ISO standard as BT is the country code for Bhutan. */ struct BTC: BitcoinCurrencyType { public static let code = "BTC" // public static let scale = Currency.XBT.scale // public static let formatter = Currency.XBT.formatter } } /// The proposed ISO 4217 Bitcoin MoneyType public typealias XBT = _Money<Currency.XBT> /// The most commonly used Bitcoin MoneyType public typealias BTC = _Money<Currency.BTC>
mit
979122de87ac9879c542e16cb22dd337
30.86
81
0.689579
4.443515
false
false
false
false
omnypay/omnypay-sdk-ios
ExampleApp/OmnyPayAPIDemo/OmnyPayAPIDemo/ViewController.swift
1
4220
/** Copyright 2017 OmnyPay 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 UIKit import OmnyPayAPI import KVNProgress /** * This class initializes example app with all the prerequisites for e.g. Merchant Id and User account * required for the app. * Please set merchant id, username and password in Constants.swift file */ class ViewController: UIViewController { var merchantShopperId: String? var merchantAuthToken: String? @IBOutlet weak var btnProceed: UIButton! override func viewDidLoad() { super.viewDidLoad() btnProceed.isHidden = true title = Constants.appTitle } @IBAction func initializeApp(_ sender: UIButton) { KVNProgress.show(withStatus: "Initializing SDK") /** * The initializeSDK method initializes merchantId. If merchantId exists in OmnyPay system, * then user is created and authenticated. If not, error is returned back. Replace * merchantId with the your merchant_id. */ omnypayApi.initialize(withMerchantId: Constants.merchantId, merchantApiKey: Constants.merchantApiKey, merchantApiSecret: Constants.merchantApiSecret, configuration: [ "host": ApiWrapper.getBaseApiUrl(), "correlation-id": Constants.correlationId ]){ (status, error) in if status { // create merchant shopper ApiWrapper.createMerchantShopper() { merchantShopper in if merchantShopper["error"] != nil || (merchantShopper["status"] ?? "") as! String == "error" { print("shopper could not be created") KVNProgress.showError(withStatus: "Shopper could not be created") } else { /** * Use your identity service to authenticate the shopper. This method shows how to use OmnyPay's * identity service for shopper authentication. * * After authentication pass on the auth-token and shopper id to OmnyPay service. */ ApiWrapper.authenticateShopperForMerchant() { shopperAuth in if shopperAuth["error"] != nil { print("shopper not authenticated with merchant") KVNProgress.showError(withStatus: "Invalid shopper") } else { self.merchantShopperId = shopperAuth["merchant-shopper-id"] as? String self.merchantAuthToken = shopperAuth["merchant-auth-token"] as? String DispatchQueue.main.async { KVNProgress.dismiss() self.btnProceed.isHidden = false } } } } } } else { print("Merchant initialization failed") KVNProgress.showError(withStatus: "Initialization failed") } } } @IBAction func proceedToFetchCards(_ sender: UIButton) { KVNProgress.show(withStatus: "Authenticating shopper") /** * This method shows how a user is authenticated with current session by passing your * user/shopper id and auth token. authenticateShopper is the method defined is OmnyPayAPI * which is responsible for authenticating a shopper with OmnyPay service. */ omnypayApi.authenticateShopper(withShopperId: self.merchantShopperId!, authToken: self.merchantAuthToken!){ (session, error) in if error == nil { KVNProgress.dismiss() self.performSegue(withIdentifier: "fetchCards", sender: self) } else { KVNProgress.showError(withStatus: "Shopper could not be authenticated") print("Shopper authentication failed: ", error as Any) } } } }
apache-2.0
f59ac3fe3a883a61fc8c118cce1f38f0
37.018018
131
0.647867
4.958872
false
false
false
false
Acidburn0zzz/firefox-ios
Storage/SQL/SQLiteHistoryRecommendations.swift
9
2646
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger fileprivate let log = Logger.syncLogger extension SQLiteHistory: HistoryRecommendations { static let MaxHistoryRowCount: UInt = 200000 static let PruneHistoryRowCount: UInt = 10000 public func cleanupHistoryIfNeeded() { DispatchQueue.global(qos: .background).async { self.checkIfCleanupIsNeeded(maxHistoryRows: SQLiteHistory.MaxHistoryRowCount) >>== { doCleanup in if doCleanup { _ = self.db.run(self.cleanupOldHistory(numberOfRowsToPrune: SQLiteHistory.PruneHistoryRowCount)) } } } } // Checks if there are more than the specified number of rows in the // `history` table. This is used as an indicator that `cleanupOldHistory()` // needs to run. func checkIfCleanupIsNeeded(maxHistoryRows: UInt) -> Deferred<Maybe<Bool>> { let sql = "SELECT COUNT(rowid) > \(maxHistoryRows) AS cleanup FROM \(TableHistory)" return self.db.runQueryConcurrently(sql, args: nil, factory: IntFactory) >>== { cursor in guard let cleanup = cursor[0], cleanup > 0 else { return deferMaybe(false) } return deferMaybe(true) } } // Deletes the specified number of items from the `history` table and // their corresponding items in the `visits` table. This only gets run // when the `checkIfCleanupIsNeeded()` method returns `true`. It is possible // that a single clean-up operation may not remove enough rows to drop below // the threshold used in `checkIfCleanupIsNeeded()` and therefore, this may // end up running several times until that threshold is crossed. func cleanupOldHistory(numberOfRowsToPrune: UInt) -> [(String, Args?)] { log.debug("Cleaning up \(numberOfRowsToPrune) rows of history.") let sql = """ DELETE FROM \(TableHistory) WHERE id IN ( SELECT siteID FROM \(TableVisits) GROUP BY siteID ORDER BY max(date) ASC LIMIT \(numberOfRowsToPrune) ) """ return [(sql, nil)] } public func repopulate(invalidateTopSites shouldInvalidateTopSites: Bool) -> Success { if shouldInvalidateTopSites { return db.run(refreshTopSitesQuery()) } else { return succeed() } } }
mpl-2.0
67fa1c6f012eeb7951c32f4e706b6e73
37.911765
116
0.636432
4.767568
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPDataBusinessHourModel.swift
1
6102
// // KPDataBusinessHourModel.swift // kapi-kaffeine // // Created by MengHsiu Chang on 19/06/2017. // Copyright © 2017 kapi-kaffeine. All rights reserved. // import Foundation enum KPDay: String { case Monday = "mon" case Tuesday = "tue" case Wednesday = "wed" case Thursday = "thu" case Friday = "fri" case Saturday = "sat" case Sunday = "sun" } class KPDataBusinessHourModel: NSObject { var businessTime: [KPDay: [(startHour: String, endHour: String, startTimeInterval: TimeInterval, endTimeInterval: TimeInterval)]] = [KPDay.Monday: [], KPDay.Tuesday: [], KPDay.Wednesday: [], KPDay.Thursday: [], KPDay.Friday: [], KPDay.Saturday: [], KPDay.Sunday: []] var originalData: [String: String] lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "HH:mm" return formatter }() init(value: [String: String]) { originalData = value super.init() for (key, time) in value { let components = key.components(separatedBy: "_") let day = KPDay(rawValue: components.first!)! let timeIndex = Int(components[1])! while businessTime[day]!.count < timeIndex { businessTime[day]!.append(("", "", 0, 0)) } if components[2] == "open" { businessTime[day]?[timeIndex-1].startHour = time businessTime[day]?[timeIndex-1].startTimeInterval = (timeFormatter.date(from: time)?.timeIntervalSince1970) ?? Double.greatestFiniteMagnitude } else if components[2] == "close" { businessTime[day]?[timeIndex-1].endHour = time businessTime[day]?[timeIndex-1].endTimeInterval = (timeFormatter.date(from: time)?.timeIntervalSince1970) ?? 0 } } } var shopStatus: (isOpening: Bool, status: String) { get { let todayDate = Date() if let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) { let currentHour = calendar.component(.hour, from: todayDate) let currentMinute = calendar.component(.minute, from: todayDate) let currentTime = timeFormatter.date(from: String(format: "%2d:%2d", currentHour, currentMinute)) for time in businessTime[KPDataBusinessHourModel.getDayOfWeek()]! { if currentTime!.timeIntervalSince1970 > time.startTimeInterval && currentTime!.timeIntervalSince1970 < time.endTimeInterval { return (true, "營業中: \(time.startHour)~\(time.endHour)") } } return (false, "休息中") } else { // Calendar create failed // ??????? return (false, "") } } } var isOpening: Bool { get { return self.shopStatus.isOpening } } public class func getDayOfWeek() -> KPDay { let todayDate = NSDate() let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian) let myComponents = myCalendar?.component(.weekday, from: todayDate as Date) if myComponents == 1 { return KPDay.Sunday } else if myComponents == 2 { return KPDay.Monday } else if myComponents == 3 { return KPDay.Tuesday } else if myComponents == 4 { return KPDay.Wednesday } else if myComponents == 5 { return KPDay.Thursday } else if myComponents == 6 { return KPDay.Friday } else if myComponents == 7 { return KPDay.Saturday } else { fatalError() } } override var description: String { var result = "" for (key, value) in businessTime { result += "\(key.rawValue): " for (start, end, _, _) in value { result += "\(start)~\(end)\t" } result += "\n" } return result } func getTimeString(withDay day: String) -> String { let timeArray = businessTime[KPDataBusinessHourModel.getShortHands(withDay: day)] var result = "" for (start, end, _, _) in timeArray! { result += "\(start)~\(end)\t" } return result == "" ? "休息" : result } static func getShortHands(withDay day: String) -> KPDay { if day == "星期一" { return KPDay.Monday } else if day == "星期二" { return KPDay.Tuesday } else if day == "星期三" { return KPDay.Wednesday } else if day == "星期四" { return KPDay.Thursday } else if day == "星期五" { return KPDay.Friday } else if day == "星期六" { return KPDay.Saturday } else if day == "星期日" { return KPDay.Sunday } else { fatalError() } } func getOutputData() -> [String: String] { var output:[String:String] = [:] for (key, value) in businessTime { for (index, time) in value.enumerated() { output["\(key.rawValue)_\(index)_open"] = time.startHour output["\(key.rawValue)_\(index)_close"] = time.endHour } } return output } }
mit
4ad57981e5b4d3ed1e8b01c413a9bd3d
34.133721
157
0.486348
4.873387
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Main/Controller/NavigationController.swift
1
2421
// // NavigationController.swift // HelloSVU_Swift // // Created by Insect on 2017/5/23. // Copyright © 2017年 Insect. All rights reserved. // import UIKit import FDFullscreenPopGesture class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() fd_fullscreenPopGestureRecognizer.isEnabled = true // 导航栏背景和文字设置 let naviBar: UINavigationBar = UINavigationBar.appearance() naviBar.setBackgroundImage(#imageLiteral(resourceName: "navigationbarBackgroundWhite"), for: .default) naviBar.titleTextAttributes = {[ NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: PFM18Font ]}() } // MARK: - 全屏滑动返回 private func pop() { // 1.获取系统的Pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } // 2.获取手势添加到的View中 guard let gesView = systemGes.view else { return } let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObjc = targets?.first else { return } // 3.2.取出target guard let target = targetObjc.value(forKey: "target") else { return } // 3.3.取出Action let action = Selector(("handleNavigationTransition:")) // 4.创建自己的Pan手势 let panGes = UIPanGestureRecognizer() gesView.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if childViewControllers.count >= 1 { viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(normalImg: "navigationButtonReturn", highlightedImg: "navigationButtonReturnClick", title: "返回", size: nil, target: self, action: #selector(self.backBtnDidClick)) // 隐藏要push的控制器的tabbar viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } } // MARK: - 返回点击事件 extension NavigationController { @objc private func backBtnDidClick() { popViewController(animated: true) } }
apache-2.0
e698c8716eabcd5766c6c570ae810481
31.394366
240
0.642609
5.077263
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/UIComponents/UIComponentsKit/Views/SearchableItemPicker.swift
1
4761
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Foundation import SwiftUI import ToolKit public struct SearchableItem<Identifier: Hashable>: Identifiable, CustomStringConvertible { public let id: Identifier public let title: String public var description: String { title } public init(id: Identifier, title: String) { self.id = id self.title = title } } extension SearchableItem: Equatable { public static func == (lhs: SearchableItem, rhs: SearchableItem) -> Bool { lhs.id == rhs.id } } public struct SearchableItemPicker<Identifier: Hashable>: View { public struct SearchableSection: Identifiable { public let id: AnyHashable public let title: String? public let items: [SearchableItem<Identifier>] public init( title: String?, items: [SearchableItem<Identifier>], id: AnyHashable = UUID() ) { self.id = id self.title = title self.items = items } } private let sections: [SearchableSection] private let cancelButtonTitle: String private let searchPlaceholder: String private let searchTolerance: Double @Binding private var selectedItem: SearchableItem<Identifier>? @State private var searching: Bool = false @State private var searchQuery: String = "" public init( sections: [SearchableSection], selectedItem: Binding<SearchableItem<Identifier>?>, cancelButtonTitle: String = "", searchPlaceholder: String = "", searchTolerance: Double = 0.3 ) { self.sections = sections _selectedItem = selectedItem self.cancelButtonTitle = cancelButtonTitle self.searchPlaceholder = searchPlaceholder self.searchTolerance = searchTolerance } public var body: some View { VStack(spacing: Spacing.padding3) { searchBar .padding(.horizontal, Spacing.padding3) ScrollView { LazyVStack(alignment: .leading, spacing: .zero) { ForEach(sections) { section in if let title = section.title { Section(header: SectionHeader(title: title)) { ForEach(filtered(section.items)) { item in cell(for: item) PrimaryDivider() } } .textCase(nil) // prevents header from being uppercased .listRowInsets(EdgeInsets()) } else { Section { ForEach(filtered(section.items)) { item in cell(for: item) PrimaryDivider() } } .textCase(nil) // prevents header from being uppercased .listRowInsets(EdgeInsets()) } } } } } } var searchBar: some View { SearchBar( text: $searchQuery, isFirstResponder: $searching, cancelButtonText: cancelButtonTitle, placeholder: searchPlaceholder, onReturnTapped: { // make search bar resign first responder searching = false } ) } @ViewBuilder private func cell(for item: SearchableItem<Identifier>) -> some View { PrimaryRow( title: item.title, subtitle: String(describing: item.id), trailing: { if item == selectedItem { Icon.checkCircle .frame(width: 16, height: 16) .accentColor(.semantic.success) } else { EmptyView() } }, action: { searching = false // Fixes a bug on item selection while searching selectedItem = item } ) } private func filtered(_ items: [SearchableItem<Identifier>]) -> [SearchableItem<Identifier>] { guard !searchQuery.isEmpty else { return items } return items.filter { let searchDistance = $0.title.distance( between: searchQuery, using: FuzzyAlgorithm(caseInsensitive: true) ) return searchDistance <= searchTolerance } } }
lgpl-3.0
2dfc25fbbabf4dfeb253d15e84395e0c
30.523179
98
0.518067
5.797808
false
false
false
false
LeeFengHY/SwiftFullScreenPop
SwiftFullScreenPop/TableViewController.swift
1
1023
// // TableViewController.swift // SwiftFullScreenPop // // Created by QFWangLP on 2017/6/21. // Copyright © 2017年 leefenghy. All rights reserved. // import UIKit class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let one = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")! let two = tableView.dequeueReusableCell(withIdentifier: "cell")! if indexPath.row == 0 { one.textLabel?.text = "show navgationBar" return one }else { two.textLabel?.text = "hidden navgationBar" return two } } }
mit
6e5fb3c2534443632a52b80020eeff59
26.567568
109
0.65098
4.834123
false
false
false
false
Jnosh/swift
stdlib/public/core/CString.swift
2
8611
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, this /// initializer replaces them with the Unicode replacement character /// (`"\u{FFFD}"`). /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Café" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Caf�" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init(cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len) { _decodeCString( $0, as: UTF8.self, length: len, repairingInvalidCodeUnits: true)! } self = result } /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// This is identical to init(cString: UnsafePointer<CChar> but operates on an /// unsigned sequence of bytes. public init(cString: UnsafePointer<UInt8>) { self = String.decodeCString( cString, as: UTF8.self, repairingInvalidCodeUnits: true)!.result } /// Creates a new string by copying and validating the null-terminated UTF-8 /// data referenced by the given pointer. /// /// This initializer does not try to repair ill-formed UTF-8 code unit /// sequences. If any are found, the result of the initializer is `nil`. /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "Optional(Café)" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "nil" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init?(validatingUTF8 cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) guard let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len, { _decodeCString($0, as: UTF8.self, length: len, repairingInvalidCodeUnits: false) }) else { return nil } self = result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// When you pass `true` as `isRepairing`, this method replaces ill-formed /// sequences with the Unicode replacement character (`"\u{FFFD}"`); /// otherwise, an ill-formed sequence causes this method to stop decoding /// and return `nil`. /// /// The following example calls this method with pointers to the contents of /// two different `CChar` arrays---the first with well-formed UTF-8 code /// unit sequences and the second with an ill-formed sequence at the end. /// /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Café, false))" /// /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((Caf�, true))" /// /// - Parameters: /// - cString: A pointer to a null-terminated code sequence encoded in /// `encoding`. /// - encoding: The Unicode encoding of the data referenced by `cString`. /// - isRepairing: Pass `true` to create a new string, even when the data /// referenced by `cString` contains ill-formed sequences. Ill-formed /// sequences are replaced with the Unicode replacement character /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new /// string if an ill-formed sequence is detected. /// - Returns: A tuple with the new string and a Boolean value that indicates /// whether any repairs were made. If `isRepairing` is `false` and an /// ill-formed sequence is detected, this method returns `nil`. /// /// - SeeAlso: `UnicodeCodec` public static func decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { guard let cString = cString else { return nil } var end = cString while end.pointee != 0 { end += 1 } let len = end - cString return _decodeCString( cString, as: encoding, length: len, repairingInvalidCodeUnits: isRepairing) } } /// From a non-`nil` `UnsafePointer` to a null-terminated string /// with possibly-transient lifetime, create a null-terminated array of 'C' char. /// Returns `nil` if passed a null pointer. public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_swift_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// This internal helper takes the string length as an argument. func _decodeCString<Encoding : _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>, as encoding: Encoding.Type, length: Int, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? { let buffer = UnsafeBufferPointer<Encoding.CodeUnit>( start: cString, count: length) let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits( buffer, encoding: encoding, repairIllFormedSequences: isRepairing) return stringBuffer.map { (result: String(_storage: $0), repairsMade: hadError) } } extension String { @available(*, unavailable, message: "Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.") public static func fromCString(_ cs: UnsafePointer<CChar>) -> String? { Builtin.unreachable() } @available(*, unavailable, message: "Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.") public static func fromCStringRepairingIllFormedUTF8( _ cs: UnsafePointer<CChar> ) -> (String?, hadError: Bool) { Builtin.unreachable() } }
apache-2.0
88bb8593e38c3f4394a0dd053fc8b3df
39.205607
233
0.62808
4.304152
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/ViewControllers/BaseViewController.swift
1
3139
// // BaseViewController.swift // Dribbble // // Created by Suyeol Jeon on 10/02/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import RxSwift class BaseViewController: UIViewController { // MARK: Properties lazy private(set) var className: String = { return type(of: self).description().components(separatedBy: ".").last ?? "" }() var automaticallyAdjustsLeftBarButtonItem = true /// There is a bug when trying to go back to previous view controller in a navigation controller /// on iOS 11, a scroll view in the previous screen scrolls weirdly. In order to get this fixed, /// we have to set the scrollView's `contentInsetAdjustmentBehavior` property to `.never` on /// `viewWillAppear()` and set back to the original value on `viewDidAppear()`. private var scrollViewOriginalContentInsetAdjustmentBehaviorRawValue: Int? // MARK: Initializing init() { super.init(nibName: nil, bundle: nil) } required convenience init?(coder aDecoder: NSCoder) { self.init() } deinit { log.verbose("DEINIT: \(self.className)") } // MARK: Rx var disposeBag = DisposeBag() // MARK: View Lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.automaticallyAdjustsLeftBarButtonItem { self.adjustLeftBarButtonItem() } // fix iOS 11 scroll view bug if #available(iOS 11, *) { if let scrollView = self.view.subviews.first as? UIScrollView { self.scrollViewOriginalContentInsetAdjustmentBehaviorRawValue = scrollView.contentInsetAdjustmentBehavior.rawValue scrollView.contentInsetAdjustmentBehavior = .never } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // fix iOS 11 scroll view bug if #available(iOS 11, *) { if let scrollView = self.view.subviews.first as? UIScrollView, let rawValue = self.scrollViewOriginalContentInsetAdjustmentBehaviorRawValue, let behavior = UIScrollView.ContentInsetAdjustmentBehavior(rawValue: rawValue) { scrollView.contentInsetAdjustmentBehavior = behavior } } } // MARK: Layout Constraints private(set) var didSetupConstraints = false override func viewDidLoad() { self.view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if !self.didSetupConstraints { self.setupConstraints() self.didSetupConstraints = true } super.updateViewConstraints() } func setupConstraints() { // Override point } // MARK: Adjusting Navigation Item func adjustLeftBarButtonItem() { if self.navigationController?.viewControllers.count ?? 0 > 1 { // pushed self.navigationItem.leftBarButtonItem = nil } else if self.presentingViewController != nil { // presented self.navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonDidTap) ) } } @objc func cancelButtonDidTap() { self.dismiss(animated: true, completion: nil) } }
mit
d4e64359a291218d0dc1d81adaea828c
25.15
98
0.698853
4.918495
false
false
false
false