repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
antonio081014/LeetCode-CodeBase
Swift/length-of-last-word.swift
2
461
/** * Problem Link: https://leetcode.com/problems/length-of-last-word/ * * * */ class Solution { func lengthOfLastWord(_ s: String) -> Int { var len = 0 let rev = String(s.trimmingCharacters(in: .whitespacesAndNewlines).characters.reversed()) for c in rev.characters { if String(c) == " " { return len } else { len += 1 } } return len } }
mit
2c2e53ac4a9e96effbeb715dfc5ab65b
20.952381
97
0.494577
4.079646
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/CreateBinaryTree.swift
1
4329
// // CreateBinaryTree.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/10. // Copyright © 2017年 okerivy. All rights reserved. // import Foundation typealias TreeNode = CreateBinaryTree.TreeNode public class CreateBinaryTree { /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class TreeNode { var value: Int var left: TreeNode? var right: TreeNode? // 后来添加 var next: TreeNode? init(value: Int, left: TreeNode?, right: TreeNode?) { self.value = value self.left = left self.right = right self.next = nil } } // MARK: - 按数字来构建二叉树 func convertNumberToTree(_ num: Int?) -> TreeNode? { guard let num = num else { return nil } return TreeNode.init(value: num, left: nil, right: nil) } // MARK: - 按数组来构建二叉树 func convertArrayToTree(_ array: [Int]) -> TreeNode? { let count = array.count if count <= 0 { return nil } let root: TreeNode = TreeNode.init(value: array[0], left: nil, right: nil) var fifoQueue: [TreeNode] = [root] var i = 1 while i < count { let node: TreeNode = fifoQueue.removeFirst() if array[i] == Int.min { node.left = nil } else { node.left = TreeNode.init(value: array[i], left: nil, right: nil) if let left = node.left { fifoQueue.append(left) } } if i+1 >= count { break } if array[i+1] == Int.min { node.right = nil } else { node.right = TreeNode.init(value: array[i+1], left: nil, right: nil) if let right = node.right { fifoQueue.append(right) } } i += 2 } return root } // MARK: - 按数组来构建二叉查找树 Binary Search Tree func convertArrayToBSTree(_ array: [Int]) -> TreeNode? { let count = array.count if count <= 0 { return nil } let root: TreeNode = TreeNode.init(value: array[0], left: nil, right: nil) for number in array { addNode(node: root, value: number) } return root } // 给 tree 添加左右结点 private func addNode(node:TreeNode, value : Int) { if (value < node.value) { if let leftNode = node.left { // 递归添加 addNode(node: leftNode, value: value) } else { node.left = TreeNode.init(value: value, left: nil, right: nil) } } else if (value > node.value) { if let rightNode = node.right { // 递归添加 addNode(node: rightNode, value: value) } else { node.right = TreeNode.init(value: value, left: nil, right: nil) } } } // MARK: - 判断一颗二叉树是否为二叉查找树 func isValidBST(root: TreeNode?) -> Bool { return _helperValidBST(node: root, nil, nil) } private func _helperValidBST(node: TreeNode?, _ min: Int?, _ max: Int?) -> Bool { // 如果结点为nil 返回true guard let node = node else { return true } // 所有右子节点都必须大于根节点 if min != nil && node.value <= min! { return false } //所有左子节点都必须小于根节点 if max != nil && node.value >= max! { return false } return _helperValidBST(node: node.left, min, node.value) && _helperValidBST(node: node.right, node.value, max) } }
mit
542e651affc9eb96f55b02780938babc
26.171053
118
0.471429
4.201424
false
false
false
false
pandaApe/HLTabPagerViewController
Example/HLTabPagerViewController/BaseViewController.swift
1
2196
// // BaseViewController.swift // Demo // // Created by PandaApe on 2017/5/31. // Copyright © 2017年 PandaApe. All rights reserved. // import UIKit import HLTabPagerViewController class BaseViewController: HLTabPagerViewController { var dataArray = [(title:String, bgColor:UIColor)]() override func viewDidLoad() { super.viewDidLoad() for index in 0 ... 10 { dataArray.append((title: "Tab-\(index)", bgColor: generateRandomColor())) } self.dataSource = self self.delegate = self self.reloadData() } } extension BaseViewController: HLTabPagerDataSource, HLTabPagerDelegate { func numberOfViewControllers() -> Int{ return dataArray.count } func viewController(forIndex index:Int) -> UIViewController{ let contentVC = T1ViewController() contentVC.view.backgroundColor = dataArray[index].bgColor return contentVC } func tabHeight() -> CGFloat { return 45 } func tabColor() -> UIColor { return UIColor.gray } // func tabBackgroundColor() -> UIColor { // return UIColor.white // } func bottomLineHeight() -> CGFloat { return 2 } func tabPager(_ tabPager: HLTabPagerViewController, willTransitionToTab atIndex: Int) { print("willTransitionToTab ->\(atIndex)") } func tabPager(_ tabPager: HLTabPagerViewController, didTransitionToTab atIndex: Int) { print("didTransitionToTab ->\(atIndex)") } } func generateRandomColor() -> UIColor { let hue : CGFloat = CGFloat(arc4random() % 256) / 256 // use 256 to get full range from 0.0 to 1.0 let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from white let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5 // from 0.5 to 1.0 to stay away from black return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) }
mit
f8db8e463f936800e6a49f17cfb41816
22.836957
113
0.587323
4.85177
false
false
false
false
gu704823/huobanyun
huobanyun/Spring/TransitionManager.swift
18
3764
// 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 class TransitionManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var isPresenting = true var duration = 0.3 public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! if isPresenting { toView.frame = container.bounds toView.transform = CGAffineTransform(translationX: 0, y: container.frame.size.height) container.addSubview(fromView) container.addSubview(toView) SpringAnimation.springEaseInOut(duration: duration) { fromView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) fromView.alpha = 0.5 toView.transform = CGAffineTransform.identity } } else { // 1. Rotating will change the bounds // 2. we have to properly reset toView // to the actual container's bounds, at // the same time take consideration of // previous transformation when presenting let transform = toView.transform toView.transform = CGAffineTransform.identity toView.frame = container.bounds toView.transform = transform container.addSubview(toView) container.addSubview(fromView) SpringAnimation.springEaseInOut(duration: duration) { fromView.transform = CGAffineTransform(translationX: 0, y: fromView.frame.size.height) toView.transform = CGAffineTransform.identity toView.alpha = 1 } } delay(delay: duration, closure: { transitionContext.completeTransition(true) }) } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } public func animationController(forPresentedController presented: UIViewController, presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
mit
310250677c6059f2de2058b2ade290cb
42.767442
204
0.690755
5.685801
false
false
false
false
marcelofabri/TraktModels
Pod/Classes/Show.swift
1
3643
// // Show.swift // movile-up-ios // // Created by Marcelo Fabri on 17/04/15. // Copyright (c) 2015 Movile. All rights reserved. // public enum ShowStatus: String { case Returning = "returning series" case InProduction = "in production" case Canceled = "canceled" case Ended = "ended" } extension ShowStatus: JSONDecodable { public static func decode(j: AnyObject) -> ShowStatus? { if let json = j as? String { return ShowStatus(rawValue: json) } return nil } } public struct Show { public let title: String public let year: Int public let identifiers: Identifiers public let overview: String? public let firstAired: NSDate? public let runtime: Int? public let network: String? public let country: String? public let trailerURL: NSURL? public let homepageURL: NSURL? public let status: ShowStatus? public let rating: Float? public let votes: Int? public let genres: [String]? public let airedEpisodes: Int? public let fanart: ImagesURLs? public let poster: ImagesURLs? public let logoImageURL: NSURL? public let clearArtImageURL: NSURL? public let bannerImageURL: NSURL? public let thumbImageURL: NSURL? } extension Show: JSONDecodable { private static func fullImageURL(j: AnyObject?) -> NSURL? { if let json = j as? NSDictionary { return flatMap(json["full"] as? String) { JSONParseUtils.parseURL($0) } } return nil } public static func decode(j: AnyObject) -> Show? { if let json = j as? NSDictionary, title = json["title"] as? String, year = json["year"] as? Int, ids = flatMap(json["ids"], { Identifiers.decode($0) }) { let overview = json["overview"] as? String let firstAired = JSONParseUtils.parseDate(json["first_aired"] as? String) let runtime = json["runtime"] as? Int let network = json["network"] as? String let country = json["country"] as? String let trailerURL = JSONParseUtils.parseURL(json["trailer"] as? String) let homepageURL = JSONParseUtils.parseURL(json["homepage"] as? String) let status = flatMap(json["status"]) { ShowStatus.decode($0) } let rating = json["rating"] as? Float let votes = json["votes"] as? Int let genres = json["genres"] as? [String] let airedEpisodes = json["aired_episodes"] as? Int let images = json["images"] as? NSDictionary let fanart = flatMap(images?["fanart"]) { ImagesURLs.decode($0) } let poster = flatMap(images?["poster"]) { ImagesURLs.decode($0) } let logoImageURL = fullImageURL(images?["logo"]) let clearArtImageURL = fullImageURL(images?["clearart"]) let bannerImageURL = fullImageURL(images?["banner"]) let thumbImageURL = fullImageURL(images?["thumb"]) return Show(title: title, year: year, identifiers: ids, overview: overview, firstAired: firstAired, runtime: runtime, network: network, country: country, trailerURL: trailerURL, homepageURL: homepageURL, status: status, rating: rating, votes: votes, genres: genres, airedEpisodes: airedEpisodes, fanart: fanart, poster: poster, logoImageURL: logoImageURL, clearArtImageURL: clearArtImageURL, bannerImageURL: bannerImageURL, thumbImageURL: thumbImageURL) } return nil } }
mit
fc16c31af8d19a3a226fdd6b0ac4bdb7
38.597826
469
0.612956
4.588161
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwift/convnet-swift/Magicnet.swift
1
13852
/* A MagicNet takes data: a list of convnetjs.Vol(), and labels which for now are assumed to be class indeces 0..K. MagicNet then: - creates data folds for cross-validation - samples candidate networks - evaluates candidate networks on all data folds - produces predictions by model-averaging the best networks */ import Foundation class MagicNet { var data: [Vol] var labels: [Int] var trainRatio: Double var numFolds: Int var numCandidates: Int var numEpochs: Int var ensembleSize: Int var batchSizeMin: Int var batchSizeMax: Int var l2DecayMin: Int var l2DecayMax: Int var learningRateMin: Int var learningRateMax: Int var momentumMin: Double var momentumMax: Double var neuronsMin: Int var neuronsMax: Int var folds: [Fold] var candidates: [Candidate] var evaluatedCandidates: [Candidate] var uniqueLabels: [Int] var iter: Int var foldix: Int var finishFoldCallback: (()->())? var finishBatchCallback: (()->())? struct Fold { var train_ix: [Int] var test_ix: [Int] } struct Candidate { var acc: [AnyObject] var accv: Double var layerDefs: [LayerOptTypeProtocol] var trainerDef: TrainerOpt var net: Net var trainer: Trainer } init(data:[Vol] = [], labels:[Int] = [], opt:[String: AnyObject]) { // required inputs self.data = data // store these pointers to data self.labels = labels // optional inputs trainRatio = opt["trainRatio"] as? Double ?? 0.7 numFolds = opt["numFolds"] as? Int ?? 10 numCandidates = opt["numCandidates"] as? Int ?? 50 // we evaluate several in parallel // how many epochs of data to train every network? for every fold? // higher values mean higher accuracy in final results, but more expensive numEpochs = opt["numEpochs"] as? Int ?? 50 // number of best models to average during prediction. Usually higher = better ensembleSize = opt["ensembleSize"] as? Int ?? 10 // candidate parameters batchSizeMin = opt["batchSizeMin"] as? Int ?? 10 batchSizeMax = opt["batchSizeMax"] as? Int ?? 300 l2DecayMin = opt["l2DecayMin"] as? Int ?? -4 l2DecayMax = opt["l2DecayMax"] as? Int ?? 2 learningRateMin = opt["learningRateMin"] as? Int ?? -4 learningRateMax = opt["learningRateMax"] as? Int ?? 0 momentumMin = opt["momentumMin"] as? Double ?? 0.9 momentumMax = opt["momentumMax"] as? Double ?? 0.9 neuronsMin = opt["neuronsMin"] as? Int ?? 5 neuronsMax = opt["neuronsMax"] as? Int ?? 30 // computed folds = [] // data fold indices, gets filled by sampleFolds() candidates = [] // candidate networks that are being currently evaluated evaluatedCandidates = [] // history of all candidates that were fully evaluated on all folds uniqueLabels = ArrayUtils.arrUnique(labels) iter = 0 // iteration counter, goes from 0 -> numEpochs * numTrainingData foldix = 0 // index of active fold // callbacks finishFoldCallback = nil finishBatchCallback = nil // initializations if data.count > 0 { sampleFolds() sampleCandidates() } } // sets folds to a sampling of numFolds folds func sampleFolds() -> () { let N = data.count let numTrain = Int(floor(trainRatio * Double(N))) folds = [] // flush folds, if any for _ in 0 ..< numFolds { var p = randomPermutation(N) let fold = Fold( train_ix: Array(p[0 ..< numTrain]), test_ix: Array(p[numTrain ..< N])) folds.append(fold) } } // returns a random candidate network func sampleCandidate() -> Candidate { let inputDepth = data[0].w.count let numClasses = uniqueLabels.count // sample network topology and hyperparameters var layerDefs: [LayerOptTypeProtocol] = [] let layerInput = InputLayerOpt( outSx: 1, outSy: 1, outDepth: inputDepth) layerDefs.append(layerInput) let nl = Int(weightedSample([0,1,2,3], probs: [0.2, 0.3, 0.3, 0.2])!) // prefer nets with 1,2 hidden layers for _ in 0 ..< nl { // WARNING: iterator was q let ni = RandUtils.randi(neuronsMin, neuronsMax) let actarr: [ActivationType] = [.Tanh, .Maxout, .ReLU] let act = actarr[RandUtils.randi(0,3)] if RandUtils.randf(0,1) < 0.5 { let dp = RandUtils.random_js() let layerFC = FullyConnectedLayerOpt( numNeurons: ni, activation: act, dropProb: dp) layerDefs.append(layerFC) } else { let layerFC = FullyConnectedLayerOpt( numNeurons: ni, activation: act) layerDefs.append(layerFC ) } } let layerSoftmax = SoftmaxLayerOpt(numClasses: numClasses) layerDefs.append(layerSoftmax) let net = Net(layerDefs) // sample training hyperparameters let bs = RandUtils.randi(batchSizeMin, batchSizeMax) // batch size let l2 = pow(10, RandUtils.randf(Double(l2DecayMin), Double(l2DecayMax))) // l2 weight decay let lr = pow(10, RandUtils.randf(Double(learningRateMin), Double(learningRateMax))) // learning rate let mom = RandUtils.randf(momentumMin, momentumMax) // momentum. Lets just use 0.9, works okay usually ;p let tp = RandUtils.randf(0,1) // trainer type var trainerDef = TrainerOpt() if tp < 0.33 { trainerDef.method = .adadelta trainerDef.batchSize = bs trainerDef.l2Decay = l2 } else if tp < 0.66 { trainerDef.method = .adagrad trainerDef.batchSize = bs trainerDef.l2Decay = l2 trainerDef.learningRate = lr } else { trainerDef.method = .sgd trainerDef.batchSize = bs trainerDef.l2Decay = l2 trainerDef.learningRate = lr trainerDef.momentum = mom } let trainer = Trainer(net: net, options: trainerDef) // var cand = {} // cand.acc = [] // cand.accv = 0 // this will maintained as sum(acc) for convenience // cand.layerDefs = layerDefs // cand.trainerDef = trainerDef // cand.net = net // cand.trainer = trainer return Candidate(acc:[], accv: 0, layerDefs: layerDefs, trainerDef: trainerDef, net: net, trainer: trainer) } // sets candidates with numCandidates candidate nets func sampleCandidates() -> () { candidates = [] // flush, if any for _ in 0 ..< numCandidates { let cand = sampleCandidate() candidates.append(cand) } } func step() -> () { // run an example through current candidate iter += 1 // step all candidates on a random data point let fold = folds[foldix] // active fold let dataix = fold.train_ix[RandUtils.randi(0, fold.train_ix.count)] for k in 0 ..< candidates.count { var x = data[dataix] let l = labels[dataix] _ = candidates[k].trainer.train(x: &x, y: l) } // process consequences: sample new folds, or candidates let lastiter = numEpochs * fold.train_ix.count if iter >= lastiter { // finished evaluation of this fold. Get final validation // accuracies, record them, and go on to next fold. var valAcc = evalValErrors() for k in 0 ..< candidates.count { var c = candidates[k] c.acc.append(valAcc[k] as AnyObject) c.accv += valAcc[k] } iter = 0 // reset step number foldix += 1 // increment fold if finishFoldCallback != nil { finishFoldCallback!() } if foldix >= folds.count { // we finished all folds as well! Record these candidates // and sample new ones to evaluate. for k in 0 ..< candidates.count { evaluatedCandidates.append(candidates[k]) } // sort evaluated candidates according to accuracy achieved evaluatedCandidates.sort(by: { (a, b) -> Bool in return (a.accv / Double(a.acc.count)) < (b.accv / Double(b.acc.count)) }) // WARNING: not sure > or < ? // and clip only to the top few ones (lets place limit at 3*ensembleSize) // otherwise there are concerns with keeping these all in memory // if MagicNet is being evaluated for a very long time if evaluatedCandidates.count > 3 * ensembleSize { let clip = Array(evaluatedCandidates[0 ..< 3*ensembleSize]) evaluatedCandidates = clip } if finishBatchCallback != nil { finishBatchCallback!() } sampleCandidates() // begin with new candidates foldix = 0 // reset this } else { // we will go on to another fold. reset all candidates nets for k in 0 ..< candidates.count { var c = candidates[k] let net = Net(c.layerDefs) let trainer = Trainer(net: net, options: c.trainerDef) c.net = net c.trainer = trainer } } } } func evalValErrors() -> [Double] { // evaluate candidates on validation data and return performance of current networks // as simple list var vals: [Double] = [] var fold = folds[foldix] // active fold for k in 0 ..< candidates.count { let net = candidates[k].net var v = 0.0 for q in 0 ..< fold.test_ix.count { var x = data[fold.test_ix[q]] let l = labels[fold.test_ix[q]] _ = net.forward(&x) let yhat = net.getPrediction() v += (yhat == l ? 1.0 : 0.0) // 0 1 loss } v /= Double(fold.test_ix.count) // normalize vals.append(v) } return vals } // returns prediction scores for given test data point, as Vol // uses an averaged prediction from the best ensembleSize models // x is a Vol. func predictSoft(_ data: Vol) -> Vol { var data = data // forward prop the best networks // and accumulate probabilities at last layer into a an output Vol var evalCandidates: [Candidate] = [] var nv = 0 if evaluatedCandidates.count == 0 { // not sure what to do here, first batch of nets hasnt evaluated yet // lets just predict with current candidates. nv = candidates.count evalCandidates = candidates } else { // forward prop the best networks from evaluatedCandidates nv = min(ensembleSize, evaluatedCandidates.count) evalCandidates = evaluatedCandidates } // forward nets of all candidates and average the predictions var xout: Vol! var n: Int! for j in 0 ..< nv { let net = evalCandidates[j].net let x = net.forward(&data) if j==0 { xout = x n = x.w.count } else { // add it on for d in 0 ..< n { xout.w[d] += x.w[d] } } } // produce average for d in 0 ..< n { xout.w[d] /= Double(nv) } return xout } func predict(_ data: Vol) -> Int { let xout = predictSoft(data) var predictedLabel: Int if xout.w.count != 0 { let stats = maxmin(xout.w)! predictedLabel = stats.maxi } else { predictedLabel = -1 // error out } return predictedLabel } // func toJSON() -> [String: AnyObject] { // // dump the top ensembleSize networks as a list // let nv = min(ensembleSize, evaluatedCandidates.count) // var json: [String: AnyObject] = [:] // var jNets: [[String: AnyObject]] = [] // for i in 0 ..< nv { // jNets.append(evaluatedCandidates[i].net.toJSON()) // } // json["nets"] = jNets // return json // } // // func fromJSON(json: [String: AnyObject]) -> () { // let jNets: [AnyObject] = json["nets"] // ensembleSize = jNets.count // evaluatedCandidates = [] // for i in 0 ..< ensembleSize { // // var net = Net() // net.fromJSON(jNets[i]) // var dummyCandidate = [:] // dummyCandidate.net = net // evaluatedCandidates.append(dummyCandidate) // } // } // callback functions // called when a fold is finished, while evaluating a batch func onFinishFold(_ f: (()->())?) -> () { finishFoldCallback = f; } // called when a batch of candidates has finished evaluating func onFinishBatch(_ f: (()->())?) -> () { finishBatchCallback = f; } }
mit
293fd6cc31dee92d4eddc4cb95965335
34.517949
115
0.537684
4.541639
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/CoreDataCollectionViewDataSource.swift
1
15251
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import CoreData import UIKit protocol CoreDataCollectionViewDataSourceDelegate: AnyObject { associatedtype Object: NSFetchRequestResult associatedtype Cell: UICollectionViewCell associatedtype HeaderView: UICollectionReusableView func configure(_ cell: Cell, for object: Object) func configureHeaderView(_ headerView: HeaderView, sectionInfo: NSFetchedResultsSectionInfo) func searchPredicate(forSearchText searchText: String) -> NSPredicate? func configureSearchHeaderView(_ searchHeaderView: HeaderView, numberOfSearchResults: Int) func collectionView(_ collectionView: UICollectionView, viewForAdditionalSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView? } extension CoreDataCollectionViewDataSourceDelegate { func configureHeaderView(_ view: HeaderView, sectionInfo: NSFetchedResultsSectionInfo) {} func searchPredicate(forSearchText searchText: String) -> NSPredicate? { return nil } func configureSearchHeaderView(_ view: HeaderView, numberOfSearchResults: Int) {} func collectionView(_ collectionView: UICollectionView, viewForAdditionalSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView? { return nil } } // unable to split up since UICollectionViewDataSource and NSFetchedResultsControllerDelegate contain @objc methods // swiftlint:disable:next line_length class CoreDataCollectionViewDataSource<Delegate: CoreDataCollectionViewDataSourceDelegate>: NSObject, UICollectionViewDataSource, NSFetchedResultsControllerDelegate { typealias Object = Delegate.Object typealias Cell = Delegate.Cell typealias HeaderView = Delegate.HeaderView private let emptyCellReuseIdentifier = "collectionview.cell.empty" private weak var collectionView: UICollectionView? private var fetchedResultsControllers: [NSFetchedResultsController<Object>] private var cellReuseIdentifier: String private var headerReuseIdentifier: String? private weak var delegate: Delegate? private var searchFetchRequest: NSFetchRequest<Object>? private var searchFetchResultsController: NSFetchedResultsController<Object>? private var contentChangeOperations: [BlockOperation] = [] required init(_ collectionView: UICollectionView?, fetchedResultsControllers: [NSFetchedResultsController<Object>], searchFetchRequest: NSFetchRequest<Object>? = nil, cellReuseIdentifier: String, headerReuseIdentifier: String? = nil, delegate: Delegate) { self.collectionView = collectionView self.fetchedResultsControllers = fetchedResultsControllers self.searchFetchRequest = searchFetchRequest self.cellReuseIdentifier = cellReuseIdentifier self.headerReuseIdentifier = headerReuseIdentifier self.delegate = delegate super.init() self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: self.emptyCellReuseIdentifier) do { for fetchedResultsController in self.fetchedResultsControllers { fetchedResultsController.delegate = self try fetchedResultsController.performFetch() } } catch { ErrorManager.shared.report(error) logger.error("Error fetching items", error: error) } self.collectionView?.dataSource = self self.collectionView?.reloadData() } var isSearching: Bool { return self.searchFetchResultsController != nil } var hasSearchResults: Bool { return !(self.searchFetchResultsController?.fetchedObjects?.isEmpty ?? true) } func object(at indexPath: IndexPath) -> Object { if let searchResultsController = self.searchFetchResultsController { return searchResultsController.object(at: indexPath) } let (controller, dataIndexPath) = self.controllerAndImplementationIndexPath(forVisual: indexPath) return controller.object(at: dataIndexPath) } // MARK: NSFetchedResultsControllerDelegate func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { guard self.searchFetchResultsController == nil else { return } let indexSet = IndexSet(integer: sectionIndex) let convertedIndexSet = self.indexSet(for: controller, with: indexSet) switch type { case .insert: self.contentChangeOperations.append(BlockOperation(block: { self.collectionView?.insertSections(convertedIndexSet) })) case .delete: self.contentChangeOperations.append(BlockOperation(block: { self.collectionView?.deleteSections(convertedIndexSet) })) case .move, .update: break @unknown default: break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { guard self.searchFetchResultsController == nil else { return } switch type { case .insert: let convertedNewIndexPath = self.convert(newIndexPath, in: controller, for: type) self.contentChangeOperations.append(BlockOperation { self.collectionView?.insertItems(at: [convertedNewIndexPath]) }) case .delete: let convertedIndexPath = self.convert(indexPath, in: controller, for: type) self.contentChangeOperations.append(BlockOperation { self.collectionView?.deleteItems(at: [convertedIndexPath]) }) case .update: let convertedIndexPath = self.convert(indexPath, in: controller, for: type) self.contentChangeOperations.append(BlockOperation { self.collectionView?.reloadItems(at: [convertedIndexPath]) }) case .move: let convertedIndexPath = self.convert(indexPath, in: controller, for: type) let convertedNewIndexPath = self.convert(newIndexPath, in: controller, for: type) self.contentChangeOperations.append(BlockOperation { self.collectionView?.deleteItems(at: [convertedIndexPath]) self.collectionView?.insertItems(at: [convertedNewIndexPath]) }) // swiftlint:disable:this closing_brace_whitespace @unknown default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { guard self.searchFetchResultsController == nil else { return } self.collectionView?.performBatchUpdates({ for operation in self.contentChangeOperations { operation.start() } }, completion: { _ in self.contentChangeOperations.removeAll(keepingCapacity: false) }) } private func convert(_ indexPath: IndexPath?, in controller: NSFetchedResultsController<NSFetchRequestResult>, for type: NSFetchedResultsChangeType) -> IndexPath { let requiredIndexPath = indexPath.require(hint: "required index path for \(type) not supplied") return self.indexPath(for: controller, with: requiredIndexPath) } deinit { for operation in self.contentChangeOperations { operation.cancel() } self.contentChangeOperations.removeAll(keepingCapacity: false) self.fetchedResultsControllers.removeAll(keepingCapacity: false) } // MARK: UICollectionViewDataSource private func numberOfFetchedItems(inSection section: Int) -> Int { var sectionsToGo = section for controller in self.fetchedResultsControllers { let sectionCount = controller.sections?.count ?? 0 if sectionsToGo >= sectionCount { sectionsToGo -= sectionCount } else { return controller.sections?[sectionsToGo].numberOfObjects ?? 0 } } fatalError("Incorrect section index") } func numberOfSections(in collectionView: UICollectionView) -> Int { if self.isSearching { return 1 } else { return self.fetchedResultsControllers.compactMap(\.sections?.count).reduce(0, +) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let searchResultsController = self.searchFetchResultsController { return max(searchResultsController.fetchedObjects?.count ?? 0, 1) } else { return self.numberOfFetchedItems(inSection: section) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if self.searchFetchResultsController?.fetchedObjects?.isEmpty ?? false { return collectionView.dequeueReusableCell(withReuseIdentifier: self.emptyCellReuseIdentifier, for: indexPath) } let someCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellReuseIdentifier, for: indexPath) as? Cell let cell = someCell.require(hint: "Unexpected cell type at \(indexPath), expected cell of type \(Cell.self)") let object = self.object(at: indexPath) self.delegate?.configure(cell, for: object) return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionHeader { guard let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerReuseIdentifier!, for: indexPath) as? HeaderView else { fatalError("Unexpected header view type, expected \(HeaderView.self)") } if let searchResultsController = self.searchFetchResultsController { if let numberOfSearchResults = searchResultsController.fetchedObjects?.count { self.delegate?.configureSearchHeaderView(view, numberOfSearchResults: numberOfSearchResults) } } else { let (controller, newIndexPath) = self.controllerAndImplementationIndexPath(forVisual: indexPath) if let sectionInfo = controller.sections?[newIndexPath.section] { self.delegate?.configureHeaderView(view, sectionInfo: sectionInfo) } } return view } return self.delegate?.collectionView(collectionView, viewForAdditionalSupplementaryElementOfKind: kind, at: indexPath) ?? UICollectionReusableView() } func search(withText searchText: String?) { guard let fetchRequest = self.searchFetchRequest?.copy() as? NSFetchRequest<Object> else { logger.warning("CollectionViewControllerDelegateImplementation is not configured for search. Missing search fetch request.") self.resetSearch() return } let searchPredicate = searchText.flatMap { self.delegate?.searchPredicate(forSearchText: $0) } let fetchPredicate = fetchRequest.predicate let predicates = [fetchPredicate, searchPredicate].compactMap { $0 } guard !predicates.isEmpty else { self.resetSearch() return } fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) self.searchFetchResultsController = CoreDataHelper.createResultsController(fetchRequest, sectionNameKeyPath: nil) do { try self.searchFetchResultsController?.performFetch() } catch { ErrorManager.shared.report(error) logger.error("Error fetching search item", error: error) } self.collectionView?.reloadData() } func resetSearch() { let shouldReloadData = self.isSearching self.searchFetchResultsController = nil if shouldReloadData { self.collectionView?.reloadData() } } } extension CoreDataCollectionViewDataSource { // Conversion of indices between data and views // correct "visual" indexPath for data controller and its indexPath (data->visual) private func indexPath(for controller: NSFetchedResultsController<NSFetchRequestResult>, with indexPath: IndexPath) -> IndexPath { var convertedIndexPath = indexPath for resultsController in self.fetchedResultsControllers { if resultsController == controller { return convertedIndexPath } else { convertedIndexPath.section += resultsController.sections?.count ?? 0 } } fatalError("Convertion of indexPath (\(indexPath) in controller (\(controller.debugDescription) to indexPath failed") } // correct "visual" indexSet for data controller and its indexSet (data->visual) private func indexSet(for controller: NSFetchedResultsController<NSFetchRequestResult>, with indexSet: IndexSet) -> IndexSet { var convertedIndexSet = IndexSet() var passedSections = 0 for contr in self.fetchedResultsControllers { if contr == controller { for index in indexSet { convertedIndexSet.insert(index + passedSections) } break } else { passedSections += contr.sections?.count ?? 0 } } return convertedIndexSet } // find data controller and its indexPath for a given "visual" indexPath (visual->data) private func controllerAndImplementationIndexPath(forVisual indexPath: IndexPath) -> (NSFetchedResultsController<Object>, IndexPath) { var passedSections = 0 for contr in self.fetchedResultsControllers { if passedSections + (contr.sections?.count ?? 0) > indexPath.section { let newIndexPath = IndexPath(item: indexPath.item, section: indexPath.section - passedSections) return (contr, newIndexPath) } else { passedSections += (contr.sections?.count ?? 0) } } fatalError("Convertion of indexPath (\(indexPath) to controller and indexPath failed") } }
gpl-3.0
cdf629bea4ed68b460a0ac3511b83bc6
40.553134
166
0.66177
6.35152
false
false
false
false
hooman/swift
test/attr/attr_objc_async.swift
3
3595
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -swift-version 5 -enable-source-import -I %S/Inputs -disable-availability-checking -warn-concurrency // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 5 -enable-source-import -I %S/Inputs | %FileCheck %s // RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 5 -enable-source-import -I %S/Inputs -disable-availability-checking -warn-concurrency > %t.ast // RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.ast // REQUIRES: objc_interop // REQUIRES: concurrency import Foundation // CHECK: class MyClass class MyClass { // CHECK: @objc func doBigJob() async -> Int // CHECK-DUMP: func_decl{{.*}}doBigJob{{.*}}foreign_async=@convention(block) (Int) -> (),completion_handler_param=0 @objc func doBigJob() async -> Int { return 0 } // CHECK: @objc func doBigJobOrFail(_: Int) async throws -> (AnyObject, Int) // CHECK-DUMP: func_decl{{.*}}doBigJobOrFail{{.*}}foreign_async=@convention(block) (Optional<AnyObject>, Int, Optional<Error>) -> (),completion_handler_param=1,error_param=2 @objc func doBigJobOrFail(_: Int) async throws -> (AnyObject, Int) { return (self, 0) } @objc func takeAnAsync(_ fn: () async -> Int) { } // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-1{{'async' function types cannot be represented in Objective-C}} @objc class func createAsynchronously() async -> Self? { nil } // expected-error@-1{{asynchronous method returning 'Self' cannot be '@objc'}} } // actor exporting Objective-C entry points. // CHECK: actor MyActor actor MyActor { // CHECK: @objc func doBigJob() async -> Int // CHECK-DUMP: func_decl{{.*}}doBigJob{{.*}}foreign_async=@convention(block) (Int) -> (),completion_handler_param=0 @objc func doBigJob() async -> Int { return 0 } // CHECK: @objc func doBigJobOrFail(_: Int) async throws -> (AnyObject, Int) // CHECK-DUMP: func_decl{{.*}}doBigJobOrFail{{.*}}foreign_async=@convention(block) (Optional<AnyObject>, Int, Optional<Error>) -> (),completion_handler_param=1,error_param=2 @objc func doBigJobOrFail(_: Int) async throws -> (AnyObject, Int) { return (self, 0) } // expected-warning@-1{{cannot call function returning non-sendable type '(AnyObject, Int)' across actors}} // Actor-isolated entities cannot be exposed to Objective-C. @objc func synchronousBad() { } // expected-error{{actor-isolated instance method 'synchronousBad()' cannot be @objc}} // expected-note@-1{{add 'async' to function 'synchronousBad()' to make it asynchronous}} {{30-30= async}} @objc var badProp: AnyObject { self } // expected-error{{actor-isolated property 'badProp' cannot be @objc}} @objc subscript(index: Int) -> AnyObject { self } // expected-error{{actor-isolated subscript 'subscript(_:)' cannot be @objc}} // CHECK: @objc nonisolated func synchronousGood() @objc nonisolated func synchronousGood() { } } actor class MyActor2 { } // expected-error@-1 {{keyword 'class' cannot be used as an identifier here}} // CHECK: @objc actor MyObjCActor @objc actor MyObjCActor: NSObject { } @objc actor class MyObjCActor2: NSObject {} // expected-error@-1 {{keyword 'class' cannot be used as an identifier here}}
apache-2.0
f2c9296503b5e593c6545386d0e9f9fd
62.070175
321
0.714882
3.780231
false
false
false
false
touchopia/Codementor-Swift-101
Week-4/SourceCode/layout/layout/ViewController.swift
1
1058
// // ViewController.swift // layout // // Created by Phil Wright on 7/28/15. // Copyright (c) 2015 Touchopia LLC. All rights reserved. // import UIKit // View + Controller class ViewController: UIViewController { @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var subtractButton: UIButton! @IBOutlet weak var addButton: UIButton! // variable that changes and is called count var counter : Counter = Counter() override func viewDidLoad() { super.viewDidLoad() println("ViewDidLoad") } func updateCountLabel() { self.counterLabel.text = "\(self.counter.count)" } @IBAction func subtract( sender: UIButton ) { self.counter.count -= 1 if self.counter.count < 1 { self.counter.count = 0 } self.updateCountLabel() } @IBAction func add( sender: UIButton ) { self.counter.count += 1 self.updateCountLabel() } }
mit
72fcf5a75411620aee882b41c681e94a
18.592593
58
0.568998
4.702222
false
false
false
false
thedistance/TheDistanceCore
TDCore/Extensions/UIViewController.swift
1
4004
// // UIViewController.swift // TheDistanceCore // // Created by Josh Campion on 30/10/2015. // Copyright © 2015 The Distance. All rights reserved. // import UIKit public extension UIViewController { /** Convenience method for accessing the topmost presented view controller. This is useful when trying in initiate an action, such as a present action, from a UIView subclass that is independent of the `UIViewController` it is residing in. - returns: The `.rootViewController` of the `UIApplication`'s `keyWindow`, or the highest presented view controller. This will return `nil` if and only if there is no root view controller. */ /* public class func topPresentedViewController() -> UIViewController? { var context = UIApplication.sharedApplication().keyWindow?.rootViewController while context?.presentedViewController != nil { context = context?.presentedViewController } return context } */ /** Convenience method for handling nested `UIViewController`s in a `UISplitViewController` or other situation where a navigation controller may be passed, not the specific `UIViewController` subclass that contains the 'content'. - returns: The root `UIViewController` if `self` is a `UINavigationController` or `self` if not. */ public func navigationRootViewController() -> UIViewController? { if let nav = self as? UINavigationController { return nav.viewControllers.first } else if let split = self as? UISplitViewController { return split.viewControllers.first?.navigationRootViewController() } else { return self } } /** Convenience method for handling nested `UIViewController`s in a `UISplitViewController` or other situation where a navigation controller may be passed, not the specific `UIViewController` subclass that contains the 'content'. - returns: The top most `UIViewController` in the stack if `self` is a `UINavigationController` or `self` if not. */ public func navigationTopViewController() -> UIViewController? { if let nav = self as? UINavigationController { return nav.viewControllers.last } else if let split = self as? UISplitViewController { return split.viewControllers.last?.navigationTopViewController() } else { return self } } /** Convenience method for presenting a `UIViewController` configuring the `popoverPresentationController` to use a given `UIView` or `UIBarButtonItem`. This is useful for action sheets and `UIActivityViewController`s. - parameter vc: The `UIViewController` to present. - parameter item: Either the `UIView` or `UIBarButtonItem` that the `ActionSheet` style `UIAlertController` will be presented from on Regular-Regular size class devices. - paramter inViewController: The `UIViewController` that will present the `UIAlertController`. If `nil`, `self` is used to present the `UIAlertController`. The default value is `nil`. - parameter animated: Passed to `presentViewController(_:animated:completion:)` - parameter completion: Passed to `presentViewController(_:animated:completion:)` -seealso: `openInSafari(_:)` */ public func presentViewController(_ vc:UIViewController, fromSourceItem item: UIPopoverSourceType, inViewController:UIViewController? = nil, animated:Bool = true, completion: (() -> ())? = nil) { switch item { case .view(let view): vc.popoverPresentationController?.sourceView = view vc.popoverPresentationController?.sourceRect = view.bounds case .barButton(let item): vc.popoverPresentationController?.barButtonItem = item } (inViewController ?? self).present(vc, animated: animated, completion: completion) } }
mit
2726184be12fac1a262f1f55acdef12c
43.977528
240
0.685486
5.50619
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Extensions/UIKit/UIView+CSPosition.swift
1
4173
// // Created by Rene Dohan on 2/14/20. // import UIKit import RenetikObjc public extension UIView { var position: CGPoint { get { frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } func position(_ point: CGPoint) -> Self { position = point; return self } var x: CGFloat { position.x } var y: CGFloat { position.y } var left: CGFloat { get { position.left } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } var top: CGFloat { get { position.top } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } var right: CGFloat { get { left + width } set { left = newValue - width } } var bottom: CGFloat { get { top + height } set { top = newValue - self.height } } var fromRight: CGFloat { get { superview.notNil ? superview!.width - (left + width) : 0 } set(value) { assert(superview.notNil, "Needs to have superview") left = superview!.width - (value + width) } } var fromBottom: CGFloat { get { superview.notNil ? superview!.height - (top + height) : 0 } set(value) { assert(superview.notNil, "Needs to have superview") top = superview!.height - (value + height) } } var leftFromRight: CGFloat { superview.notNil ? superview!.width - left : width } var topFromBottom: CGFloat { superview.notNil ? superview!.height - top : height } var screenTop: CGFloat { get { convert(CGPoint(x: 0, y: top), to: nil).y } set(value) { top = convert(CGPoint(x: 0, y: value), from: nil).y } } var screenBottom: CGFloat { get { convert(CGPoint(x: 0, y: bottom), to: nil).y } set(value) { bottom = convert(CGPoint(x: 0, y: value), from: nil).y } } func center(_ point: CGPoint) -> Self { center = point; return self } func center(_ x: CGFloat, _ y: CGFloat) -> Self { center(CGPoint(x: x, y: y)) } var centerTop: CGFloat { get { center.y } set(value) { center = CGPoint(x: center.x, y: value) } } var centerLeft: CGFloat { get { center.x } set(value) { center = CGPoint(x: value, y: center.y) } } @discardableResult func center(y: CGFloat) -> Self { invoke { centerTop = y } } @discardableResult func center(x: CGFloat) -> Self { invoke { centerLeft = x } } @discardableResult func center(top y: CGFloat) -> Self { invoke { centerTop = y } } @discardableResult func center(left x: CGFloat) -> Self { invoke { centerLeft = x } } @discardableResult func centerTop(as view: UIView) -> Self { center(top: view.centerTop) } @discardableResult func centerLeft(as view: UIView) -> Self { center(left: view.center.left) } @discardableResult func centerVertical(as view: UIView) -> Self { centerTop(as: view) } @discardableResult func centerHorizontal(as view: UIView) -> Self { centerLeft(as: view) } @discardableResult func centerVerticalAsPrevious() -> Self { assert(superview.notNil, "Needs to have superview") let previous = superview!.findPrevious(of: self) assert(previous.notNil, "Needs to have previous") return centerVertical(as: previous!) } @discardableResult func centered() -> Self { assert(superview.notNil, "Needs to have superview") center = CGPoint(x: superview!.width / 2, y: superview!.height / 2) return self } @discardableResult func centeredVertical() -> Self { assert(superview.notNil, "Needs to have superview") center = CGPoint(x: center.x, y: superview!.height / 2) return self } @discardableResult func centeredHorizontal() -> Self { assert(superview.notNil, "Needs to have superview") center = CGPoint(x: superview!.width / 2, y: center.y) return self } }
mit
1e5af859cdc9931db5bb347cc79bcaa2
28.814286
86
0.57896
4.087169
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Gallery/GalleryItemViewController.swift
3
1513
@objc(MWMGalleryItemViewController) final class GalleryItemViewController: MWMViewController { typealias Model = GalleryItemModel static func instance(model: Model) -> GalleryItemViewController { let vc = GalleryItemViewController(nibName: toString(self), bundle: nil) vc.model = model return vc } private var model: Model! @IBOutlet private weak var scrollView: UIScrollView! fileprivate var imageView: UIImageView! override var hasNavigationBar: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(frame: scrollView.bounds) imageView.contentMode = .scaleAspectFit scrollView.addSubview(imageView) imageView.wi_setImage(with: model.imageURL, transitionDuration: kDefaultAnimationDuration) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() imageView.frame = scrollView.bounds } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { [unowned self] _ in self.imageView.frame = CGRect(origin: CGPoint.zero, size: size) }) } @IBAction func backAction() { _ = navigationController?.popViewController(animated: true) } } extension GalleryItemViewController: UIScrollViewDelegate { func viewForZooming(in _: UIScrollView) -> UIView? { return imageView } }
apache-2.0
e2ea92f703561014460f1a8bf3dfa4a4
28.096154
110
0.750165
5.163823
false
false
false
false
zj-insist/QSImageBucket
QSIMageBucket/QS-AliOSS/AliOSSConfig.swift
1
2365
// // AliOSSConfig.swift // PicU // // Created by ZJ-Jie on 2017/8/8. // Copyright © 2017年 chenxt. All rights reserved. // import Cocoa import TMCache class AliOSSConfig: NSObject,NSCoding,DiskCache { var accessKey: String! var bucket:String! var secretKey:String! var zone:Int! var zoneHost:String! { get { switch zone { case 1: return "oss-cn-hangzhou.aliyuncs.com" case 2: return "oss-cn-shanghai.aliyuncs.com" case 3: return "oss-cn-qingdao.aliyuncs.com" case 4: return "oss-cn-beijing.aliyuncs.com" case 5: return "oss-cn-zhangjiakou.aliyuncs.com" case 6: return "oss-cn-shenzhen.aliyuncs.com" case 7: return "oss-cn-hongkong.aliyuncs.com" default: return "" } } } var location:String! { get { switch zone { case 1: return "oss-cn-hangzhou" case 2: return "oss-cn-shanghai" case 3: return "oss-cn-qingdao" case 4: return "oss-cn-beijing" case 5: return "oss-cn-zhangjiakou" case 6: return "oss-cn-shenzhen" case 7: return "oss-cn-hongkong" default: return "" } } } func encode(with aCoder: NSCoder) { aCoder.encode(accessKey, forKey: "accessKey") aCoder.encode(bucket, forKey: "bucket") aCoder.encode(secretKey, forKey: "secretKey") aCoder.encode(zone, forKey: "zone") } required init?(coder aDecoder: NSCoder) { super.init() accessKey = aDecoder.decodeObject(forKey: "accessKey") as! String bucket = aDecoder.decodeObject(forKey: "bucket") as! String secretKey = aDecoder.decodeObject(forKey: "secretKey") as! String zone = aDecoder.decodeObject(forKey: "zone") as! Int } init(accessKey:String, bucket:String, secretKey:String, zone:Int) { self.accessKey = accessKey; self.bucket = bucket; self.secretKey = secretKey; self.zone = zone; } }
mit
2f7c20699a4049639892ff79d22c00d3
26.788235
73
0.515665
4.210339
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/SkeletonView/Sources/Extensions/CALayer+Extensions.swift
1
5179
// // SkeletonLayer+Animations.swift // SkeletonView-iOS // // Created by Juanpe Catalán on 03/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit extension CALayer { @objc func tint(withColors colors: [UIColor]) { skeletonSublayers.recursiveSearch(leafBlock: { backgroundColor = colors.first?.cgColor }) { $0.tint(withColors: colors) } } } extension CAGradientLayer { override func tint(withColors colors: [UIColor]) { skeletonSublayers.recursiveSearch(leafBlock: { self.colors = colors.map { $0.cgColor } }) { $0.tint(withColors: colors) } } } // MARK: Skeleton sublayers extension CALayer { static let skeletonSubLayersName = "SkeletonSubLayersName" var skeletonSublayers: [CALayer] { return sublayers?.filter { $0.name == CALayer.skeletonSubLayersName } ?? [CALayer]() } func addMultilinesLayers(lines: Int, type: SkeletonType, lastLineFillPercent: Int, multilineCornerRadius: Int) { let numberOfSublayers = calculateNumLines(maxLines: lines) let layerBuilder = SkeletonMultilineLayerBuilder() .setSkeletonType(type) .setCornerRadius(multilineCornerRadius) (0..<numberOfSublayers).forEach { index in var width = getLineWidth(index: index, numberOfSublayers: numberOfSublayers, lastLineFillPercent: lastLineFillPercent) if index == numberOfSublayers - 1 && numberOfSublayers != 1 { width = width * CGFloat(lastLineFillPercent) / 100; } if let layer = layerBuilder .setIndex(index) .setWidth(width) .build() { addSublayer(layer) } } } func updateMultilinesLayers(lastLineFillPercent: Int) { let currentSkeletonSublayers = skeletonSublayers let numberOfSublayers = currentSkeletonSublayers.count for (index, layer) in currentSkeletonSublayers.enumerated() { let width = getLineWidth(index: index, numberOfSublayers: numberOfSublayers, lastLineFillPercent: lastLineFillPercent) layer.updateLayerFrame(for: index, width: width) } } private func getLineWidth(index: Int, numberOfSublayers: Int, lastLineFillPercent: Int) -> CGFloat { var width = bounds.width if index == numberOfSublayers - 1 && numberOfSublayers != 1 { width = width * CGFloat(lastLineFillPercent) / 100; } return width } func updateLayerFrame(for index: Int, width: CGFloat) { let spaceRequiredForEachLine = SkeletonAppearance.default.multilineHeight + SkeletonAppearance.default.multilineSpacing frame = CGRect(x: 0.0, y: CGFloat(index) * spaceRequiredForEachLine, width: width, height: SkeletonAppearance.default.multilineHeight) } private func calculateNumLines(maxLines: Int) -> Int { let spaceRequitedForEachLine = SkeletonAppearance.default.multilineHeight + SkeletonAppearance.default.multilineSpacing var numberOfSublayers = Int(round(CGFloat(bounds.height)/CGFloat(spaceRequitedForEachLine))) if maxLines != 0, maxLines <= numberOfSublayers { numberOfSublayers = maxLines } return numberOfSublayers } } // MARK: Animations public extension CALayer { var pulse: CAAnimation { let pulseAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.backgroundColor)) pulseAnimation.fromValue = backgroundColor pulseAnimation.toValue = UIColor(cgColor: backgroundColor!).complementaryColor.cgColor pulseAnimation.duration = 1 pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) pulseAnimation.autoreverses = true pulseAnimation.repeatCount = .infinity return pulseAnimation } var sliding: CAAnimation { let startPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.startPoint)) startPointAnim.fromValue = CGPoint(x: -1, y: 0.5) startPointAnim.toValue = CGPoint(x:1, y: 0.5) let endPointAnim = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.endPoint)) endPointAnim.fromValue = CGPoint(x: 0, y: 0.5) endPointAnim.toValue = CGPoint(x:2, y: 0.5) let animGroup = CAAnimationGroup() animGroup.animations = [startPointAnim, endPointAnim] animGroup.duration = 1.5 animGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn) animGroup.repeatCount = .infinity return animGroup } func playAnimation(_ anim: SkeletonLayerAnimation, key: String) { skeletonSublayers.recursiveSearch(leafBlock: { add(anim(self), forKey: key) }) { $0.playAnimation(anim, key: key) } } func stopAnimation(forKey key: String) { skeletonSublayers.recursiveSearch(leafBlock: { removeAnimation(forKey: key) }) { $0.stopAnimation(forKey: key) } } }
mit
c13d853fed2e334cfa6ba778d3eb7d10
35.716312
142
0.660614
5.035992
false
false
false
false
ninjaprawn/BigStats
BigStats/BSTotalViewCell.swift
1
731
// // BSTotalViewCell.swift // BigStats // // Created by George Dan on 5/01/2015. // Copyright (c) 2015 Ninjaprawn. All rights reserved. // import UIKit class BSTotalViewCell: UITableViewCell { @IBOutlet weak var tweakName: UILabel! @IBOutlet weak var downloadCount: UILabel! override func awakeFromNib() { super.awakeFromNib() //tweakName.text = "test" downloadCount.textAlignment = NSTextAlignment.Right } func updateCellWith(totalDownloads: Int) { var formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle downloadCount.text = "\(formatter.stringFromNumber(totalDownloads as NSNumber)!)" } }
mit
ead6674da45530950a6fc679f96e8a11
25.107143
89
0.678523
4.56875
false
false
false
false
themonki/onebusaway-iphone
Carthage/Checkouts/Hue/Example/Hex/Hex/Cells/GridHexCell.swift
4
1012
import UIKit import Sugar import Spots import Hue class GridHexCell: UICollectionViewCell, ItemConfigurable { lazy var label: UILabel = { [unowned self] in let label = UILabel(frame: CGRect.zero) label.font = UIFont.boldSystemFont(ofSize: 11) label.numberOfLines = 4 label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with item: Item) { let color = UIColor(hex:item.title) backgroundColor = color label.textColor = color.isDark ? UIColor.white : UIColor.darkGray label.attributedText = NSAttributedString(string: item.title, attributes: nil) label.frame.size.height = 44 label.frame.size.width = contentView.frame.size.width - 7.5 } func computeSize(for item: Item) -> CGSize { return CGSize(width: 125, height: 160) } }
apache-2.0
54cc24b65ca2ff6014f0d2e418629beb
24.3
69
0.69664
4.031873
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Logging/OSLog+WikiRaces.swift
2
1007
// // OSLog+WikiRaces.swift // WikiRaces // // Created by Andrew Finke on 6/30/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import Foundation import os.log extension OSLog { // MARK: - Types - private enum CustomCategory: String { case store, gameKit, nearby, matchSupport, raceLiveDatabase } private static let subsystem: String = { guard let identifier = Bundle.main.bundleIdentifier else { fatalError() } return identifier }() static let store = OSLog(subsystem: subsystem, category: CustomCategory.store.rawValue) static let gameKit = OSLog(subsystem: subsystem, category: CustomCategory.gameKit.rawValue) static let nearby = OSLog(subsystem: subsystem, category: CustomCategory.nearby.rawValue) static let matchSupport = OSLog(subsystem: subsystem, category: CustomCategory.matchSupport.rawValue) static let raceLiveDatabase = OSLog(subsystem: subsystem, category: CustomCategory.raceLiveDatabase.rawValue) }
mit
2ba0d50e9b018b58f3fe4537f9137ce7
31.451613
113
0.729622
4.491071
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Searching/WhenSceneSelectsEventFromSearchViewModel_SchedulePresenterShould.swift
1
1130
import EurofurenceModel import ScheduleComponent import XCTest import XCTEurofurenceModel class WhenSceneSelectsEventFromSearchViewModel_SchedulePresenterShould: XCTestCase { func testTellModuleEventWithResolvedIdentifierSelected() { let searchViewModel = CapturingScheduleSearchViewModel() let viewModelFactory = FakeScheduleViewModelFactory(searchViewModel: searchViewModel) let context = SchedulePresenterTestBuilder().with(viewModelFactory).build() let results = [ScheduleEventGroupViewModel].random context.simulateSceneDidLoad() searchViewModel.simulateSearchResultsUpdated(results) let randomGroup = results.randomElement() let randomEvent = randomGroup.element.events.randomElement() let indexPath = IndexPath(item: randomEvent.index, section: randomGroup.index) let selectedIdentifier = EventIdentifier.random searchViewModel.stub(selectedIdentifier, at: indexPath) context.simulateSceneDidSelectSearchResult(at: indexPath) XCTAssertEqual(selectedIdentifier, context.delegate.capturedEventIdentifier) } }
mit
6ca5ae72cd62605912446a65a428fc0e
44.2
93
0.782301
6.531792
false
true
false
false
4jchc/4jchc-BaiSiBuDeJie
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Tool/NSDate+Extension.swift
1
13399
// // NSDate+Extension.swift // 4jchc-BaiSiBuDeJie // // Created by 蒋进 on 16/2/22. // Copyright © 2016年 蒋进. All rights reserved. // import UIKit //MARK: - 微博版时间设置 extension NSDate{ //MARK: - 判断是否为- 今年 /// 判断是否为- 今年 func isThisYear()->Bool{ let calendar: NSCalendar = NSCalendar.currentCalendar() // 获得的年月日时分秒 let dateCmps: NSDateComponents = calendar.components(NSCalendarUnit.Year, fromDate:self) let nowCmps: NSDateComponents = calendar.components(NSCalendarUnit.Year, fromDate: NSDate()) return dateCmps.year == nowCmps.year; // let year = calendar.component(.Year, fromDate: self) // let nowYear = calendar.component(.Year, fromDate: NSDate()) // return year == nowYear } //MARK: - 判断是否为- 昨天 /// 判断是否为- 昨天 func isYesterday() ->Bool{ var now: NSDate = NSDate() // date == 2014-04-30 10:05:28 --> 2014-04-30 00:00:00 // now == 2014-05-01 09:22:10 --> 2014-05-01 00:00:00 let fmt: NSDateFormatter = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd"; // 2014-04-30 let dateStr: NSString = fmt.stringFromDate(self) // 2014-10-18 let nowStr: NSString = fmt.stringFromDate(now) // 2014-10-30 00:00:00 let date: NSDate = fmt.dateFromString(dateStr as String)! // 2014-10-18 00:00:00 now = fmt.dateFromString(nowStr as String)! let calendar: NSCalendar = NSCalendar.currentCalendar() let unit: NSCalendarUnit = [NSCalendarUnit.Year , NSCalendarUnit.Month , NSCalendarUnit.Day] let cmps: NSDateComponents = calendar.components(unit, fromDate: date, toDate: now, options: NSCalendarOptions()) return cmps.year == 0 && cmps.month == 0 && cmps.day == 1; /* let nowDate = NSDate().dateWithYMD() let selfDate = self.dateWithYMD() // 获得nowDate和selfDate的差距 let calendar = NSCalendar.currentCalendar() let cmps = calendar.components(NSCalendarUnit.Day, fromDate: selfDate, toDate: nowDate, options: NSCalendarOptions.WrapComponents) return cmps.day == 1; */ } //MARK: - 判断是否为- 今天 /// 判断是否为- 今天 func isToday()->Bool { let now: NSDate = NSDate() let fmt: NSDateFormatter = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd"; // 2014-04-30 let dateStr: NSString = fmt.stringFromDate(self) // 2014-10-18 let nowStr: NSString = fmt.stringFromDate(now) return dateStr.isEqualToString(nowStr as String) /* let calendar = NSCalendar.currentCalendar() let unitFlags: NSCalendarUnit = [.Year, .Day, .Month] // 1.获得当前时间的年月日 let nowCmps = calendar.components(unitFlags, fromDate: NSDate()) // 2.获得self的年月日 let selfCmps = calendar.components(unitFlags, fromDate: self) return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day); */ } //MARK: - 获取与当前时间的差距 /// 获取与当前时间的差距 func deltaWithNow() -> NSDateComponents { let calendar = NSCalendar.currentCalendar() return calendar.components([.Year,.Month,.Day,.Hour,.Minute,.Second], fromDate: self, toDate: NSDate(), options: NSCalendarOptions.WrapComponents) } //MARK: 返回一个只有年月日的时间 /// 返回一个只有年月日的时间 func dateWithYMD() -> NSDate { let fmt = NSDateFormatter() fmt.dateFormat = "yyyy-MM-dd" let selfStr = fmt.stringFromDate(self) return fmt.dateFromString(selfStr)! } /** 刚刚(一分钟内) X分钟前(一小时内) X小时前(当天) 昨天 HH:mm(昨天) MM-dd HH:mm(一年内) yyyy-MM-dd HH:mm(更早期) NS Calendar-日历 */ //MARK: - 时间描述-刚刚-X分钟前-X小时前-昨天 /// 时间描述-刚刚-X分钟前-X小时前-昨天 var descriptionDate:String{ let calendar = NSCalendar.currentCalendar() // 1.判断是否是今天 if calendar.isDateInToday(self)// @available(iOS 8.0, *) { // 1.0获取当前时间和系统时间之间的差距(秒数) let since = Int(NSDate().timeIntervalSinceDate(self)) // 1.1是否是刚刚 if since < 60 { return "刚刚" } // 1.2多少分钟以前 if since < 60 * 60 { return "\(since/60)分钟前" } // 1.3多少小时以前 return "\(since / (60 * 60))小时前" } // 2.判断是否是昨天 var formatterStr = "HH:mm" if calendar.isDateInYesterday(self) { // 昨天: HH:mm formatterStr = "昨天:" + formatterStr }else { // 3.处理一年以内 formatterStr = "MM-dd " + formatterStr // 4.处理更早时间 let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) if comps.year >= 1 { formatterStr = "yyyy-" + formatterStr } } // 5.按照指定的格式将时间转换为字符串 // 5.1.创建formatter let formatter = NSDateFormatter() // 5.2.设置时间的格式 formatter.dateFormat = formatterStr // 5.3设置时间的区域(真机必须设置, 否则可能不能转换成功) formatter.locale = NSLocale(localeIdentifier: "en") // 5.4格式化 return formatter.stringFromDate(self) } //MARK: - 时间描述-刚刚-X分钟前-X小时前-昨天 /// 时间描述-刚刚-X分钟前-X小时前-昨天 class func descriptionDate(created_at: String) ->String{ let fmt = NSDateFormatter() //fmt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒) fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" //微博发布的具体时间 let createDate: NSDate = fmt.dateFromString(created_at)! //判断是否为今年 if createDate.isThisYear() == true { //今天 if createDate.isToday() == true { let cmps = createDate.deltaWithNow() if cmps.hour >= 1 { //至少1小时前 return "\(cmps.hour)小时前" } else if (cmps.minute >= 1) {//1小时内 return "\(cmps.minute)分钟前" } else { //1分钟内 return "刚刚" } } else if createDate.isYesterday() == true { //昨天 fmt.dateFormat = "昨天 HH:mm" return fmt.stringFromDate(createDate) } else { //至少是前天 fmt.dateFormat = "MM-dd" return fmt.stringFromDate(createDate) } } else { fmt.dateFormat = "yyyy-MM-dd HH:mm" return fmt.stringFromDate(createDate) } } //MARK: - 将- 时间字符串转换为-NSDate /// 将- 时间字符串转换为-NSDate class func dateWithStr(time: String) ->NSDate { // 1.1.创建formatter let formatter = NSDateFormatter() // 1.2.设置时间的格式 formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy" // 1.3设置时间的区域(真机必须设置, 否则可能不能转换成功) formatter.locale = NSLocale(localeIdentifier: "en") // 1.4转换字符串, 转换好的时间是去除时区的时间 let createdDate = formatter.dateFromString(time)! return createdDate } } extension String { /** 刚刚(一分钟内) X分钟前(一小时内) X小时前(当天) 昨天 HH:mm(昨天) MM-dd HH:mm(一年内) yyyy-MM-dd HH:mm(更早期) NS Calendar-日历 */ //MARK: - 时间描述-刚刚-X分钟前-X小时前-昨天 /// 时间描述-刚刚-X分钟前-X小时前-昨天 func descriptionDate()->String { /* @available(iOS 8.0, *) let fmt = NSDateFormatter() //fmt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒) fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" //微博发布的具体时间 let createDate: NSDate = fmt.dateFromString(self)! let calendar = NSCalendar.currentCalendar() // 1.判断是否是今天 if calendar.isDateInToday(createDate)// @available(iOS 8.0, *) { // 1.0获取当前时间和系统时间之间的差距(秒数) let since = Int(NSDate().timeIntervalSinceDate(createDate)) // 1.1是否是刚刚 if since < 60 { return "刚刚" } // 1.2多少分钟以前 if since < 60 * 60 { return "\(since/60)分钟前" } // 1.3多少小时以前 return "\(since / (60 * 60))小时前" } // 2.判断是否是昨天 var formatterStr = "HH:mm" if calendar.isDateInYesterday(createDate) { // 昨天: HH:mm formatterStr = "昨天:" + formatterStr }else { // 3.处理一年以内 formatterStr = "MM-dd " + formatterStr // 4.处理更早时间 let comps = calendar.components(NSCalendarUnit.Year, fromDate: createDate, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) if comps.year >= 1 { formatterStr = "yyyy-" + formatterStr } } // 5.按照指定的格式将时间转换为字符串 // 5.1.创建formatter let formatter = NSDateFormatter() // 5.2.设置时间的格式 formatter.dateFormat = formatterStr // 5.3设置时间的区域(真机必须设置, 否则可能不能转换成功) formatter.locale = NSLocale(localeIdentifier: "en") // 5.4格式化 return formatter.stringFromDate(createDate) } */ let fmt = NSDateFormatter() //fmt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" // 设置日期格式(y:年,M:月,d:日,H:时,m:分,s:秒) fmt.dateFormat = "yyyy-MM-dd HH:mm:ss" //微博发布的具体时间 let createDate: NSDate = fmt.dateFromString(self)! //判断是否为今年 if createDate.isThisYear() == true { //今天 if createDate.isToday() == true { let cmps = createDate.deltaWithNow() if cmps.hour >= 1 { //至少1小时前 return "\(cmps.hour)小时前" } else if (cmps.minute >= 1) {//1小时内 return "\(cmps.minute)分钟前" } else { //1分钟内 return "刚刚" } } else if createDate.isYesterday() == true { //昨天 fmt.dateFormat = "昨天 HH:mm" return fmt.stringFromDate(createDate) } else { //至少是前天 fmt.dateFormat = "MM-dd" return fmt.stringFromDate(createDate) } } else { fmt.dateFormat = "yyyy-MM-dd HH:mm" return fmt.stringFromDate(createDate) } } } //MARK: - 转换为基本数据类型 extension String{ /** 将String类型转换转换为Int类型 - Parameter N/A - Returns:Int String转换后的Int值 */ func toInt()->Int{ return Int(self.toDouble()) } /** 将String类型转换转换为CGFloat类型 - Parameter N/A - Returns:CGFloat String转换后的CGFloat值 */ func toCGFloat()->CGFloat{ return CGFloat(self.toDouble()) } /** 将String类型转换转换为Double类型 - Parameter N/A - Returns:Double String转换后的Double值 */ func toDouble()->Double{ let lValue=Double(self) if (lValue != nil){ return lValue! }else{ return 0 } } //MARK: 将新字符串按路径的方式拼接到原字符串上,即字符串直接添加'/'字符 /** 将新字符串按路径的方式拼接到原字符串上,即字符串直接添加'/'字符 - Parameter str:String 要拼接上的字符串 - Returns:N/A */ func stringByAppendingPathComponent(str:String) -> String{ return self.stringByAppendingFormat("/%@", str) } }
apache-2.0
64ebff30ba873d0f49d46d11541ddfd4
28.104478
154
0.520427
4.100946
false
false
false
false
4jchc/4jchc-BaiSiBuDeJie
4jchc-MenuController/4jchc-MenuController/XMGLabel.swift
1
2662
// // XMGLabel.swift // 4jchc-MenuController // // Created by 蒋进 on 16/3/2. // Copyright © 2016年 蒋进. All rights reserved. // import UIKit class XMGLabel: UILabel { override func awakeFromNib(){ super.awakeFromNib() setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //fatalError("init(coder:) has not been implemented") } func setup(){ self.userInteractionEnabled = true } /// 让label有资格成为第一响应者 override func canBecomeFirstResponder() -> Bool { return true } /** * label能执行哪些操作(比如copy, paste等等) * @return YES:支持这种操作 */ override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return false } /* /** * label能执行哪些操作(比如copy, paste等等) * @return YES:支持这种操作 */ override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if (action == Selector("cut:") || action == Selector("copy:") || action == Selector("copy:") || action == Selector("paste:")) { return true } return false } func labelClick(){ // 1.label要成为第一响应者(作用是:告诉UIMenuController支持哪些操作, 这些操作如何处理) self.becomeFirstResponder() // 2.显示MenuController let menu:UIMenuController = UIMenuController.sharedMenuController() //var copyLink = UIMenuItem(title: "", action: Selector("copy:")) //UIMenuController.sharedMenuController().menuItems = NSArray(object:copyLink) // targetRect: MenuController需要指向的矩形框 // targetView: targetRect会以targetView的左上角为坐标原点 menu.setTargetRect(self.frame, inView: self.superview!) menu.setMenuVisible(true, animated: true) } // 将自己的文字复制到粘贴板 override func copy(menu: AnyObject?) { let pboard = UIPasteboard.generalPasteboard() pboard.string = self.text } // 将自己的文字复制到粘贴板 override func cut(sender: AnyObject?) { // 将自己的文字复制到粘贴板 copy(sender) // 清空文字 self.text = nil } override func paste(sender: AnyObject?) { // 将粘贴板的文字 复制 到自己身上 let pboard = UIPasteboard.generalPasteboard() self.text = pboard.string } */ }
apache-2.0
ffb3711c50865c58343f003326bf7ff3
21.235849
131
0.610522
4.09913
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIComponents/QMUIToastAnimator.swift
1
2842
// // QMUIToastAnimator.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // /** * `QMUIToastAnimatorDelegate`是所有`QMUIToastAnimator`或者其子类必须遵循的协议,是整个动画过程实现的地方。 */ protocol QMUIToastAnimatorDelegate { func show(with completion: ((Bool) -> Void)?) func hide(with completion: ((Bool) -> Void)?) var isShowing: Bool { get } var isAnimating: Bool { get } } // TODO: 实现多种animation类型 enum QMUIToastAnimationType: Int { case fade = 0 case zoom case slide } /** * `QMUIToastAnimator`可以让你通过实现一些协议来自定义ToastView显示和隐藏的动画。你可以继承`QMUIToastAnimator`,然后实现`QMUIToastAnimatorDelegate`中的方法,即可实现自定义的动画。QMUIToastAnimator默认也提供了几种type的动画:1、QMUIToastAnimationTypeFade;2、QMUIToastAnimationTypeZoom;3、QMUIToastAnimationTypeSlide; */ class QMUIToastAnimator: NSObject { internal var _isShowing = false internal var _isAnimating = false /** * 初始化方法,请务必使用这个方法来初始化。 * * @param toastView 要使用这个animator的QMUIToastView实例。 */ init(toastView: QMUIToastView) { super.init() self.toastView = toastView } /** * 获取初始化传进来的QMUIToastView。 */ private(set) var toastView: QMUIToastView? /** * 指定QMUIToastAnimator做动画的类型type。此功能暂时未实现,目前所有动画类型都是QMUIToastAnimationTypeFade。 */ private var animationType: QMUIToastAnimationType = .fade } extension QMUIToastAnimator: QMUIToastAnimatorDelegate { @objc func show(with completion: ((Bool) -> Void)?) { _isShowing = true _isAnimating = true UIView.animate(withDuration: 0.25, delay: 0, options: [.curveOut, .beginFromCurrentState], animations: { self.toastView?.backgroundView?.alpha = 1.0 self.toastView?.contentView?.alpha = 1.0 }, completion: { finished in self._isAnimating = false completion?(finished) }) } @objc func hide(with completion: ((Bool) -> Void)?) { _isShowing = false _isAnimating = true UIView.animate(withDuration: 0.25, delay: 0, options: [.curveOut, .beginFromCurrentState], animations: { self.toastView?.backgroundView?.alpha = 0.0 self.toastView?.contentView?.alpha = 0.0 }, completion: { finished in self._isAnimating = false completion?(finished) }) } var isShowing: Bool { return _isShowing } var isAnimating: Bool { return _isAnimating } }
mit
086eecf99f8758d0dc44e8b7a2125a1c
25.698925
249
0.651631
4.166107
false
false
false
false
PekanMmd/Pokemon-XD-Code
XD Randomiser/XDRViewController.swift
1
1850
// // ViewController.swift // XD Randomiser // // Created by The Steez on 05/09/2017. // // import Cocoa class XDRViewController: NSViewController, GoDViewLayoutManager { var contentview: NSView { return self.view } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } var active = false { didSet { activeSet() } } func activeSet() { return } var progressBar = NSProgressIndicator(frame: NSRect(x: 25, y: 160, width: 200, height: 80)) var back = NSImageView() var views : [String : NSView ] = [String : NSView ]() var metrics : [String : CGFloat] = [String : CGFloat]() var contentView : NSView! { get { return view } } override func viewDidLoad() { super.viewDidLoad() progressBar.controlTint = .blueControlTint progressBar.isIndeterminate = false back.frame = self.view.frame back.image = NSImage(named: "back") back.alphaValue = 0.25 back.imageScaling = .scaleAxesIndependently back.refusesFirstResponder = false } func showActivityView() { self.showActivityView(nil) } func showActivityView(_ completion: ( (Bool) -> Void)! ) { active = true // self.view.addSubview(back) self.view.addSubview(progressBar) dispatchAfter(dispatchTime: 0.5, closure: { DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async(execute: { () -> Void in completion(true) }) }) } func hideActivityView() { active = false // back.removeFromSuperview() progressBar.removeFromSuperview() progressBar.doubleValue = 0 } func dispatchAfter(dispatchTime: Double, closure: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(dispatchTime * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { closure() }) } }
gpl-2.0
2e35a37c70accc638c559e487b71a245
19.555556
148
0.678919
3.470919
false
false
false
false
PekanMmd/Pokemon-XD-Code
Revolution Tool CL/enums/PBRMoves.swift
1
3471
// // XGMoves.swift // XG Tool // // Created by StarsMmd on 01/06/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation enum PBRRandomMoveStyle : Int { case offensive = 0 case defensive = 1 var string : String { return self.rawValue == 0 ? "Offensive" : "Defensive" } } enum PBRRandomMoveType : Int { case levelup = 0 // not sure of the difference yet case tm = 1 case tm2 = 2 case tm3 = 3 case tm4 = 4 var string : String { return self.rawValue == 0 ? "Level-up Move" : "TM \(self.rawValue)" } } enum XGMoves: XGIndexedValue { case index(Int) case randomMove(PBRRandomMoveStyle, PBRRandomMoveType) var index : Int { switch self { case .index(let i): return i case .randomMove(let s, let t): return 0x8000 + (s.rawValue << 4) + t.rawValue } } var nameID : Int { switch self { case .index: return data.nameID default: return 0 } } var name : XGString { switch self { case .index: return getStringSafelyWithID(id: nameID) case .randomMove(let s, let t): let text = "Random " + s.string + " " + t.string return XGString(string: text, file: nil, sid: nil) } } var type : XGMoveTypes { return data.type } var data : XGMove { return XGMove(index: self.index) } var isShadowMove: Bool { return false } static func allMoves() -> [XGMoves] { var moves = [XGMoves]() for i in -1 ..< kNumberOfMoves { moves.append(.index(i)) } return moves } static func random() -> XGMoves { var rand = 0 while (rand == 0) || (XGMoves.index(rand).data.descriptionID == 0) { rand = Int.random(in: 1 ..< kNumberOfMoves) } return XGMoves.index(rand) } static func randomMoveset() -> [XGMoves] { return [XGMoves.random(),XGMoves.random(),XGMoves.random(),XGMoves.random()] } // The game already has logic around generating random movesets static func inGameRandomMoveset() -> [XGMoves] { return [XGMoves.randomMove(.offensive, .levelup),XGMoves.randomMove(.offensive, .levelup),XGMoves.randomMove(.defensive, .levelup),XGMoves.randomMove(.offensive, .tm)] } } func allMoves() -> [String : XGMoves] { var dic = [String : XGMoves]() for i in -1 ..< kNumberOfMoves { let a = XGMoves.index(i) dic[a.name.unformattedString.simplified] = a } return dic } let moves = allMoves() func move(_ name: String) -> XGMoves { if moves[name.simplified] == nil { printg("couldn't find: " + name) } return moves[name.simplified] ?? .index(0) } func allMovesArray() -> [XGMoves] { var moves: [XGMoves] = [] for i in -1 ..< kNumberOfMoves { moves.append(XGMoves.index(i)) } return moves } extension XGMoves: Codable { enum CodingKeys: String, CodingKey { case index, name } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let index = try container.decode(Int.self, forKey: .index) self = .index(index) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.index, forKey: .index) try container.encode(self.name.string, forKey: .name) } } extension XGMoves: XGEnumerable { var enumerableName: String { return name.unformattedString.spaceToLength(20) } var enumerableValue: String? { return index.string } static var className: String { return "Moves" } static var allValues: [XGMoves] { return XGMoves.allMoves() } }
gpl-2.0
a76aed2d26d09c99dd3a9903b06c6667
16.891753
169
0.661481
3.127027
false
false
false
false
oddevan/macguffin
macguffin/Battle.swift
1
5693
// // Battle.swift // macguffin // // Created by Evan Hildreth on 2/25/15. // Copyright (c) 2015 Evan Hildreth. All rights reserved. // protocol BattleDelegate { func battleCompleted(_ sender: Battle, protagonistsWon: Bool) func battleInvalidState(_ sender: Battle) } // All of these should be optional, but I don't feel like dealing with // a crapton of @objc crap in this crapfest. protocol BattleMonitor { func battleBegun(_ sender: Battle) func battle( _ sender: Battle, activeCharacter: Character, performedAttack: Attack, againstCharacter: Character, withResult: AttackResult) func battle(_ sender: Battle, activeCharacter: Character, usedItem: Item, againstCharacter: Character, forDamage: Int?, forStatus: Status?) func battle(_ sender: Battle, characterDied: Character) func battleEnded(_ sender: Battle) } class Battle { let proTeam: Team let antTeam: Team let delegate: BattleDelegate var proTeamQueuedExp: Int = 0 var antTeamQueuedExp: Int = 0 var battleQueue: [Character] let waitValue: Int var currentAttacker: Character? var currentDefender: Character? var monitor: BattleMonitor? init(proTeam: Team, antTeam: Team, delegate: BattleDelegate) { self.proTeam = proTeam self.antTeam = antTeam self.delegate = delegate self.battleQueue = proTeam.active + antTeam.active self.battleQueue.sort(by: { $0.spd < $1.spd }) if let slowest = battleQueue.first { self.waitValue = slowest.spd } else { self.waitValue = 0 } } func startBattle() { // First, check for a valid state if waitValue <= 0 || proTeam.active.isEmpty || antTeam.active.isEmpty || !isTeamAlive(proTeam) || !isTeamAlive(antTeam) { delegate.battleInvalidState(self) return } currentAttacker = nil currentDefender = nil monitor?.battleBegun(self) nextTurn() } func nextTurn() { sortQueue() if let next = battleQueue.first { if next.wait < waitValue { for char in battleQueue { char.wait += char.spd } nextTurn() } else { currentAttacker = next next.intelligence.characterNeedsDecision(next, forBattle: self) } } else { // battleQueue.first is nil? It's empty, which is no good delegate.battleInvalidState(self) } } func characterPerformAction(_ performer: Character, targeting: Character, withAttack: Attack) { //let prevHP = targeting.hp let attackResult = withAttack.perform(performer, victim: targeting) monitor?.battle(self, activeCharacter: performer, performedAttack: withAttack, againstCharacter: targeting, withResult: attackResult) performer.exp += (attackResult.damage / 2) if let attackingTeam = performer.team { if attackingTeam === proTeam { proTeamQueuedExp += (attackResult.damage / 3) } else { antTeamQueuedExp += (attackResult.damage / 3) } } if !targeting.isAlive { monitor?.battle(self, characterDied: targeting) } endTurn() } func characterPerformAction(_ performer: Character, targeting: Character, withItem: Item) { let prevHP = targeting.hp if withItem.use(targeting) { monitor?.battle(self, activeCharacter: performer, usedItem: withItem, againstCharacter: targeting, forDamage: prevHP - targeting.hp, forStatus: nil) if !targeting.isAlive { monitor?.battle(self, characterDied: targeting) } } endTurn() } func endTurn() { if let current = currentAttacker { current.wait -= waitValue } //not the end of the world if currentAttacker is nil, so just keep going currentAttacker = nil currentDefender = nil //clear out the KO'd from the queue battleQueue = battleQueue.filter({$0.isAlive}) if isTeamAlive(proTeam) && isTeamAlive(antTeam) { nextTurn() } else { endBattle(isTeamAlive(proTeam)) } } func endBattle(_ protagonistsWon: Bool) { if protagonistsWon { for member in proTeam.active + proTeam.bench { member.exp += proTeamQueuedExp } } else { for member in antTeam.active + antTeam.bench { member.exp += antTeamQueuedExp } } monitor?.battleEnded(self) delegate.battleCompleted(self, protagonistsWon: protagonistsWon) } // This function checks for anyone alive in the team's 'active' array // To override with other conditions, override this function. func isTeamAlive(_ checkMe: Team) -> Bool { for char in checkMe.active { if char.isAlive { return true } } return false } func sortQueue() { self.battleQueue.sort(by: { if $0.wait == $1.wait { return $0.spd > $1.spd } else { return $0.wait > $1.wait } }) } }
apache-2.0
768be02554d518e2eace8b7106dda509
28.194872
160
0.559283
4.812342
false
false
false
false
JosephNK/SwiftyIamport
SwiftyIamportDemo/Controller/RemoteViewController.swift
1
2971
// // RemoteViewController.swift // SwiftIamport // // Created by JosephNK on 2017. 4. 21.. // Copyright © 2017년 JosephNK. All rights reserved. // import UIKit import SwiftyIamport class RemoteViewController: UIViewController { lazy var webView: UIWebView = { var view = UIWebView() view.backgroundColor = UIColor.clear view.delegate = self return view }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(webView) self.webView.frame = self.view.bounds // 결제 환경 설정 IAMPortPay.sharedInstance.configure(scheme: "iamporttest") // info.plist에 설정한 scheme IAMPortPay.sharedInstance .setWebView(self.webView) // 현재 Controller에 있는 WebView 지정 .setRedirectUrl(nil) // m_redirect_url 주소 // ISP 취소시 이벤트 (NicePay만 가능) IAMPortPay.sharedInstance.setCancelListenerForNicePay { [weak self] in DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: "ISP 결제 취소", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self?.present(alert, animated: true, completion: nil) } } // 결제 웹페이지(Remote) 호출 if let url = URL(string: "http://www.iamport.kr/demo") { let request = URLRequest(url: url) self.webView.loadRequest(request) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension RemoteViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { // 해당 함수는 redirecURL의 결과를 직접 처리하고 할 때 사용하는 함수 (IAMPortPay.sharedInstance.configure m_redirect_url 값을 설정해야함.) IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in // Background Thread var resultData: [String: Any]? if let httpResponse = response as? HTTPURLResponse { let statusCode = httpResponse.statusCode switch statusCode { case 200: resultData = [ "isSuccess": "OK" ] break default: break } } return resultData }) { (pasingData) in // Main Thread } return IAMPortPay.sharedInstance.requestAction(for: request) } func webViewDidFinishLoad(_ webView: UIWebView) { // 직접 구현.. } }
mit
bf96fa7b760ccab0b84037d6384960fa
32.176471
131
0.580851
4.607843
false
false
false
false
FolioReader/FolioReaderKit
Source/EPUBCore/FRResources.swift
2
3079
// // FRResources.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit open class FRResources: NSObject { var resources = [String: FRResource]() /** Adds a resource to the resources. */ func add(_ resource: FRResource) { self.resources[resource.href] = resource } // MARK: Find /** Gets the first resource (random order) with the give mediatype. Useful for looking up the table of contents as it's supposed to be the only resource with NCX mediatype. */ func findByMediaType(_ mediaType: MediaType) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType == mediaType { return resource } } return nil } /** Gets the first resource (random order) with the give extension. Useful for looking up the table of contents as it's supposed to be the only resource with NCX extension. */ func findByExtension(_ ext: String) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType.defaultExtension == ext { return resource } } return nil } /** Gets the first resource (random order) with the give properties. - parameter properties: ePub 3 properties. e.g. `cover-image`, `nav` - returns: The Resource. */ func findByProperty(_ properties: String) -> FRResource? { for resource in resources.values { if resource.properties == properties { return resource } } return nil } /** Gets the resource with the given href. */ func findByHref(_ href: String) -> FRResource? { guard !href.isEmpty else { return nil } // This clean is neede because may the toc.ncx is not located in the root directory let cleanHref = href.replacingOccurrences(of: "../", with: "") return resources[cleanHref] } /** Gets the resource with the given href. */ func findById(_ id: String?) -> FRResource? { guard let id = id else { return nil } for resource in resources.values { if let resourceID = resource.id, resourceID == id { return resource } } return nil } /** Whether there exists a resource with the given href. */ func containsByHref(_ href: String) -> Bool { guard !href.isEmpty else { return false } return resources.keys.contains(href) } /** Whether there exists a resource with the given id. */ func containsById(_ id: String?) -> Bool { guard let id = id else { return false } for resource in resources.values { if let resourceID = resource.id, resourceID == id { return true } } return false } }
bsd-3-clause
4d831a59b2c24dcf4451cea00c8c659c
26.008772
109
0.580708
4.781056
false
false
false
false
benlangmuir/swift
test/Interpreter/type_wrappers.swift
1
11733
// RUN: %empty-directory(%t) // RUN: %target-build-swift -enable-experimental-feature TypeWrappers -parse-as-library -emit-library -emit-module-path %t/type_wrapper_defs.swiftmodule -module-name type_wrapper_defs %S/Inputs/type_wrapper_defs.swift -o %t/%target-library-name(type_wrapper_defs) // RUN: %target-build-swift -ltype_wrapper_defs -module-name main -I %t -L %t %s -o %t/main %target-rpath(%t) // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/%target-library-name(type_wrapper_defs) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: asserts // This requires executable tests to be run on the same machine as the compiler, // as it links with a dylib that it doesn't arrange to get uploaded to remote executors. // (rdar://99051588) // UNSUPPORTED: remote_run || device_run import type_wrapper_defs var p: Person<String> = .init(name: "P", projects: ["A", "B"]) // CHECK: Wrapper.init($Storage(name: "P", projects: ["A", "B"])) print(p.name) // CHECK: in getter // CHECK-NEXT: P print(p.projects) // CHECK: in getter // CHECK-NEXT: ["A", "B"] p.name = "OtherP" // CHECK: in setter => OtherP p.projects.append("C") // CHECK: in getter // CHECK-NEXT: in setter => ["A", "B", "C"] func addProjects<T>(p: inout Person<T>, _ newProjects: [T]) { p.projects.append(contentsOf: newProjects) } addProjects(p: &p, ["D"]) // CHECK: in getter // CHECK: in setter => ["A", "B", "C", "D"] print(p.name) // CHECK: in getter // CHECK-NEXT: OtherP print(p.projects) // CHECK: in getter // CHECK-NEXT: ["A", "B", "C", "D"] var pDefaults = PersonWithDefaults() // CHECK: Wrapper.init($Storage(name: "<no name>", age: 99)) print(pDefaults.name) // CHECK: in getter // CHECK: <no name> print(pDefaults.age) // CHECK: in getter // CHECK: 99 pDefaults.name = "Actual Name" // CHECK-NEXT: in setter => Actual Name pDefaults.age = 0 // CHECK-NEXT: in setter => 0 print(pDefaults.name) // CHECK: in getter // CHECK: Actual Name print(pDefaults.age) // CHECK: in getter // CHECK: 0 let pDefaultsAge = PersonWithDefaults(name: "Actual Name") print(pDefaultsAge.name) // CHECK: in getter // CHECK: Actual Name print(pDefaultsAge.age) // CHECK: in getter // CHECK: 99 let pDefaultsName = PersonWithDefaults(age: 31337) print(pDefaultsName.name) // CHECK: in getter // CHECK: <no name> print(pDefaultsName.age) // CHECK: in getter // CHECK: 31337 func testPropertyWrappers() { var wrapped1 = PropWrapperTest(test: 42) // CHECK: Wrapper.init($Storage(_test: type_wrapper_defs.PropWrapper<Swift.Int>(value: 42))) do { print(wrapped1.test) // CHECK: in getter // CHECK-NEXT: 42 wrapped1.test = 0 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Int>(value: 0) print(wrapped1.test) // CHECK: in getter // CHECK-NEXT: 0 } var wrapped2 = DefaultedPropWrapperTest() // CHECK: Wrapper.init($Storage(_test: type_wrapper_defs.PropWrapper<Swift.Int>(value: 0))) do { print(wrapped2.test) // CHECK: in getter // CHECK-NEXT: 0 wrapped2.test = 42 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Int>(value: 42) print(wrapped2.test) // CHECK: in getter // CHECK-NEXT: 42 } var wrapped3 = DefaultedPropWrapperTest(test: 1) // CHECK: Wrapper.init($Storage(_test: type_wrapper_defs.PropWrapper<Swift.Int>(value: 1))) do { print(wrapped3.test) // CHECK: in getter // CHECK-NEXT: 1 wrapped3.test = 31337 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Int>(value: 31337) print(wrapped3.test) // CHECK: in getter // CHECK-NEXT: 31337 } var wrapped4 = DefaultedPropWrapperWithArgTest() // CHECK: Wrapper.init($Storage(_test: type_wrapper_defs.PropWrapper<Swift.Int>(value: 3))) do { print(wrapped4.test) // CHECK: in getter // CHECK-NEXT: 3 wrapped4.test = 0 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Int>(value: 0) print(wrapped4.test) // CHECK: in getter // CHECK-NEXT: 0 } var wrapped5 = PropWrapperNoInitTest(a: PropWrapperWithoutInit(value: 1)) // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapperWithoutInit<Swift.Int>(value: 1), _b: type_wrapper_defs.PropWrapperWithoutInit<Swift.String>(value: "b"))) do { print(wrapped5.a) // CHECK: in getter // CHECK-NEXT: 1 print(wrapped5.b) // CHECK: in getter // CHECK-NEXT: b wrapped5.a = 42 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<Int>(value: 42) wrapped5.b = "not b" // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<String>(value: "not b") print(wrapped5.a) // CHECK: in getter // CHECK-NEXT: 42 print(wrapped5.b) // CHECK: in getter // CHECK-NEXT: not b } var wrapped6 = PropWrapperNoInitTest(a: PropWrapperWithoutInit(value: 1), b: PropWrapperWithoutInit(value: "hello")) // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapperWithoutInit<Swift.Int>(value: 1), _b: type_wrapper_defs.PropWrapperWithoutInit<Swift.String>(value: "hello"))) do { print(wrapped6.a) // CHECK: in getter // CHECK-NEXT: 1 print(wrapped6.b) // CHECK: in getter // CHECK-NEXT: hello wrapped6.a = 42 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<Int>(value: 42) wrapped6.b = "b" // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<String>(value: "b") print(wrapped6.a) // CHECK: in getter // CHECK-NEXT: 42 print(wrapped6.b) // CHECK: in getter // CHECK-NEXT: b } var wrapped7 = ComplexPropWrapperTest() // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapper<Swift.Array<Swift.String>>(value: ["a"]), _b: type_wrapper_defs.PropWrapperWithoutInit<type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [1, 2, 3])))) do { print(wrapped7.a) // CHECK: in getter // CHECK-NEXT: ["a"] print(wrapped7.b) // CHECK: in getter // CHECK-NEXT: [1, 2, 3] wrapped7.a = ["a", "b", "c"] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Array<String>>(value: ["a", "b", "c"]) print(wrapped7.a) // CHECK: in getter // CHECK-NEXT: ["a", "b", "c"] wrapped7.b = [0] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<PropWrapper<Array<Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [0])) print(wrapped7.b) // CHECK: in getter // CHECK-NEXT: [0] } var wrapped8 = ComplexPropWrapperTest(a: ["a", "b"]) // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapper<Swift.Array<Swift.String>>(value: ["a", "b"]), _b: type_wrapper_defs.PropWrapperWithoutInit<type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [1, 2, 3])))) do { print(wrapped8.a) // CHECK: in getter // CHECK-NEXT: ["a", "b"] print(wrapped8.b) // CHECK: in getter // CHECK-NEXT: [1, 2, 3] wrapped8.a = ["a", "b", "c"] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Array<String>>(value: ["a", "b", "c"]) print(wrapped8.a) // CHECK: in getter // CHECK-NEXT: ["a", "b", "c"] wrapped8.b = [0] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<PropWrapper<Array<Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [0])) print(wrapped8.b) // CHECK: in getter // CHECK-NEXT: [0] } var wrapped9 = ComplexPropWrapperTest(b: PropWrapperWithoutInit(value: PropWrapper(wrappedValue: [0]))) // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapper<Swift.Array<Swift.String>>(value: ["a"]), _b: type_wrapper_defs.PropWrapperWithoutInit<type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [0])))) do { print(wrapped9.a) // CHECK: in getter // CHECK-NEXT: ["a"] print(wrapped9.b) // CHECK: in getter // CHECK-NEXT: [0] wrapped9.a = ["a", "b", "c"] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Array<String>>(value: ["a", "b", "c"]) print(wrapped9.a) // CHECK: in getter // CHECK-NEXT: ["a", "b", "c"] wrapped9.b = [1, 2, 3] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<PropWrapper<Array<Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [1, 2, 3])) print(wrapped9.b) // CHECK: in getter // CHECK-NEXT: [1, 2, 3] } var wrapped10 = ComplexPropWrapperTest(a: [], b: PropWrapperWithoutInit(value: PropWrapper(wrappedValue: [0]))) // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapper<Swift.Array<Swift.String>>(value: []), _b: type_wrapper_defs.PropWrapperWithoutInit<type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [0])))) do { print(wrapped10.a) // CHECK: in getter // CHECK-NEXT: [] print(wrapped10.b) // CHECK: in getter // CHECK-NEXT: [0] wrapped10.a = ["a", "b", "c"] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<Array<String>>(value: ["a", "b", "c"]) print(wrapped10.a) // CHECK: in getter // CHECK-NEXT: ["a", "b", "c"] wrapped10.b = [1, 2, 3] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<PropWrapper<Array<Int>>>(value: type_wrapper_defs.PropWrapper<Swift.Array<Swift.Int>>(value: [1, 2, 3])) print(wrapped10.b) // CHECK: in getter // CHECK-NEXT: [1, 2, 3] } var wrapped11 = PropWrapperNoProjectionTest() // CHECK: Wrapper.init($Storage(_a: type_wrapper_defs.PropWrapperWithoutProjection<Swift.Int>(value: 0), _b: type_wrapper_defs.PropWrapperWithoutProjection<type_wrapper_defs.PropWrapper<Swift.String>>(value: type_wrapper_defs.PropWrapper<Swift.String>(value: "b")))) do { print(wrapped11.a) // CHECK: in getter // CHECK-NEXT: 0 print(wrapped11.b) // CHECK: in getter // CHECK-NEXT: b wrapped11.a = 42 // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutProjection<Int>(value: 42) wrapped11.b = "not b" // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutProjection<PropWrapper<String>>(value: type_wrapper_defs.PropWrapper<Swift.String>(value: "not b")) print(wrapped11.a) // CHECK: in getter // CHECK-NEXT: 42 print(wrapped11.b) // CHECK: in getter // CHECK-NEXT: not b } } testPropertyWrappers() do { var person = PersonWithUnmanagedTest(name: "Arthur Dent") // CHECK: Wrapper.init($Storage(_favoredColor: type_wrapper_defs.PropWrapper<Swift.String>(value: "red"))) print(person.name) // CHECK: Arthur Dent print(person.age) // CHECK: 30 print(person.placeOfBirth) // CHECK: Earth print(person.favoredColor) // CHECK: in getter // CHECK-NEXT: red person.favoredColor = "yellow" // CHECK: in getter // CHECK-NEXT: in setter => PropWrapper<String>(value: "yellow") print(person.favoredColor) // CHECK: in getter // CHECK-NEXT: yellow } do { var test = ClassWithDesignatedInit(a: 42) print(test.a) // CHECK: in getter // CHECK-NEXT: 42 print(test.b) // CHECK: in getter // CHECK-NEXT: [1, 2, 3] test.a = 0 // CHECK: in setter => 0 test.b = [42] // CHECK: in getter // CHECK-NEXT: in setter => PropWrapperWithoutInit<Array<Int>>(value: [42]) print(test.a) // CHECK: in getter // CHECK-NEXT: 0 print(test.b) // CHECK: in getter // CHECK-NEXT: [42] }
apache-2.0
1614c6dd5d55cfad5cd635cca3cdce6d
27.617073
296
0.642973
3.292088
false
true
false
false
milseman/swift
test/SILGen/pointer_conversion.swift
4
28107
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Foundation func sideEffect1() -> Int { return 1 } func sideEffect2() -> Int { return 2 } func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {} func takesConstPointer(_ x: UnsafePointer<Int>) {} func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {} func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {} func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {} func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {} func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {} func takesConstVoidPointer(_ x: UnsafeRawPointer) {} func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {} func takesConstRawPointer(_ x: UnsafeRawPointer) {} func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {} func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {} // CHECK-LABEL: sil hidden @_T018pointer_conversion0A9ToPointerySpySiG_SPySiGSvtF // CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer): func pointerToPointer(_ mp: UnsafeMutablePointer<Int>, _ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) { // There should be no conversion here takesMutablePointer(mp) // CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F // CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]]) takesMutableVoidPointer(mp) // CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer> // CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]] takesMutableRawPointer(mp) // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF : // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer> // CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]] takesConstPointer(mp) // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>> // CHECK: apply [[TAKES_CONST_POINTER]] takesConstVoidPointer(mp) // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer> // CHECK: apply [[TAKES_CONST_VOID_POINTER]] takesConstRawPointer(mp) // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF : // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer> // CHECK: apply [[TAKES_CONST_RAW_POINTER]] takesConstPointer(cp) // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF // CHECK: apply [[TAKES_CONST_POINTER]]([[CP]]) takesConstVoidPointer(cp) // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer> // CHECK: apply [[TAKES_CONST_VOID_POINTER]] takesConstRawPointer(cp) // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer> // CHECK: apply [[TAKES_CONST_RAW_POINTER]] takesConstRawPointer(mrp) // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer> // CHECK: apply [[TAKES_CONST_RAW_POINTER]] } // CHECK-LABEL: sil hidden @_T018pointer_conversion14arrayToPointeryyF func arrayToPointer() { var ints = [1,2,3] takesMutablePointer(&ints) // CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F // CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]] // CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesConstPointer(ints) // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF // CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]] // CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesMutableRawPointer(&ints) // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF : // CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]] // CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesConstRawPointer(ints) // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF : // CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] // CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesOptConstPointer(ints, and: sideEffect1()) // CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF : // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]] // CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] } // CHECK-LABEL: sil hidden @_T018pointer_conversion15stringToPointerySSF func stringToPointer(_ s: String) { takesConstVoidPointer(s) // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySV{{[_0-9a-zA-Z]*}}F // CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] // CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesConstRawPointer(s) // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySV{{[_0-9a-zA-Z]*}}F // CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] // CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]]) // CHECK: destroy_value [[OWNER]] takesOptConstRawPointer(s, and: sideEffect1()) // CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF : // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]], // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]] // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]] // CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] } // CHECK-LABEL: sil hidden @_T018pointer_conversion14inoutToPointeryyF func inoutToPointer() { var int = 0 // CHECK: [[INT:%.*]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[INT]] takesMutablePointer(&int) // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]]) // CHECK: apply [[TAKES_MUTABLE]] var logicalInt: Int { get { return 0 } set { } } takesMutablePointer(&logicalInt) // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F // CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sifg // CHECK: apply [[GETTER]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>> // CHECK: apply [[TAKES_MUTABLE]] // CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sifs // CHECK: apply [[SETTER]] takesMutableRawPointer(&int) // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]]) // CHECK: apply [[TAKES_MUTABLE]] takesMutableRawPointer(&logicalInt) // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sifg // CHECK: apply [[GETTER]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer> // CHECK: apply [[TAKES_MUTABLE]] // CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sifs // CHECK: apply [[SETTER]] } class C {} func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {} func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {} func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {} // CHECK-LABEL: sil hidden @_T018pointer_conversion19classInoutToPointeryyF func classInoutToPointer() { var c = C() // CHECK: [[VAR:%.*]] = alloc_box ${ var C } // CHECK: [[PB:%.*]] = project_box [[VAR]] takesPlusOnePointer(&c) // CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @_T018pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] // CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]]) // CHECK: apply [[TAKES_PLUS_ONE]] takesPlusZeroPointer(&c) // CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_T018pointer_conversion20takesPlusZeroPointerys026AutoreleasingUnsafeMutableF0VyAA1CCGF // CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C // CHECK: [[OWNED:%.*]] = load_borrow [[PB]] // CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]] // CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]] // CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F // CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]]) // CHECK: apply [[TAKES_PLUS_ZERO]] // CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]] // CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]] // CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]] // CHECK: assign [[OWNED_OUT_COPY]] to [[PB]] var cq: C? = C() takesPlusZeroOptionalPointer(&cq) } // Check that pointer types don't bridge anymore. @objc class ObjCMethodBridging : NSObject { // CHECK-LABEL: sil hidden [thunk] @_T018pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging) @objc func pointerArgs(_ x: UnsafeMutablePointer<Int>, y: UnsafePointer<Int>, z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {} } // rdar://problem/21505805 // CHECK-LABEL: sil hidden @_T018pointer_conversion22functionInoutToPointeryyF func functionInoutToPointer() { // CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned () -> () } var f: () -> () = {} // CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out () // CHECK: address_to_pointer [[REABSTRACT_BUF]] takesMutableVoidPointer(&f) } // rdar://problem/31781386 // CHECK-LABEL: sil hidden @_T018pointer_conversion20inoutPointerOrderingyyF func inoutPointerOrdering() { // CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> } // CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] : // CHECK: store {{.*}} to [init] [[ARRAY]] var array = [Int]() // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointerySpySiG_Si3andtF // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF // CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]() // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int> // CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]]) // CHECK: strong_unpin // CHECK: end_access [[ACCESS]] takesMutablePointer(&array[sideEffect1()], and: sideEffect2()) // CHECK: [[TAKES_CONST:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiG_Si3andtF // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF // CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]() // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int> // CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]]) // CHECK: end_access [[ACCESS]] takesConstPointer(&array[sideEffect1()], and: sideEffect2()) } // rdar://problem/31542269 // CHECK-LABEL: sil hidden @_T018pointer_conversion20optArrayToOptPointerySaySiGSg5array_tF func optArrayToOptPointer(array: [Int]?) { // CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF // CHECK: [[BORROW:%.*]] = begin_borrow %0 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[T0:%.*]] = select_enum [[COPY]] // CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]: // CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF // CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int> // CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]]) // CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]] // CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]] // CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value %0 // CHECK: [[NONE_BB]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>) takesOptConstPointer(array, and: sideEffect1()) } // CHECK-LABEL: sil hidden @_T018pointer_conversion013optOptArrayTodD7PointerySaySiGSgSg5array_tF func optOptArrayToOptOptPointer(array: [Int]??) { // CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD12ConstPointerySPySiGSgSg_Si3andtF // CHECK: [[BORROW:%.*]] = begin_borrow %0 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[T0:%.*]] = select_enum [[COPY]] // CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]: // CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]] // CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]] // CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]] // CHECK: [[SOME_NONE_BB]]: // CHECK: destroy_value [[SOME_VALUE]] // CHECK: br [[SOME_NONE_BB2:bb[0-9]+]] // CHECK: [[SOME_SOME_BB]]: // CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF // CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int> // CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]]) // CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]] // CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]] // CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt.1, [[OPTDEP]] // CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]] // CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value %0 // CHECK: [[SOME_NONE_BB2]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>) // CHECK: [[NONE_BB]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>) takesOptOptConstPointer(array, and: sideEffect1()) } // CHECK-LABEL: sil hidden @_T018pointer_conversion21optStringToOptPointerySSSg6string_tF func optStringToOptPointer(string: String?) { // CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF // CHECK: [[BORROW:%.*]] = begin_borrow %0 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[T0:%.*]] = select_enum [[COPY]] // CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]: // CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF // CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer // CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]]) // CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]] // CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]] // CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value %0 // CHECK: [[NONE_BB]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>) takesOptConstRawPointer(string, and: sideEffect1()) } // CHECK-LABEL: sil hidden @_T018pointer_conversion014optOptStringTodD7PointerySSSgSg6string_tF func optOptStringToOptOptPointer(string: String??) { // CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD15ConstRawPointerySVSgSg_Si3andtF // CHECK: [[BORROW:%.*]] = begin_borrow %0 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] // CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF // CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]() // CHECK: [[T0:%.*]] = select_enum [[COPY]] // FIXME: this should really go somewhere that will make nil, not some(nil) // CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]: // CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]] // CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]] // CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]] // CHECK: [[SOME_NONE_BB]]: // CHECK: destroy_value [[SOME_VALUE]] // CHECK: br [[SOME_NONE_BB2:bb[0-9]+]] // CHECK: [[SOME_SOME_BB]]: // CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]] // CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF // CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer // CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]]) // CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]] // CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]] // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]] // CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt.1, [[OPTDEP]] // CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : $Optional<AnyObject>): // CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]] // CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]]) // CHECK: destroy_value [[OWNER]] // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value %0 // CHECK: [[SOME_NONE_BB2]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>) // CHECK: [[NONE_BB]]: // CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none // CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none // CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>) takesOptOptConstRawPointer(string, and: sideEffect1()) }
apache-2.0
47144da410063606fec7c52be4cb4414
59.706263
260
0.644395
3.666928
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
2 - Introduction to UIKit/1 - Strings/lab/Lab - Strings.playground/Pages/2. Exercise - Concatenation and Interpolation.xcplaygroundpage/Contents.swift
1
1367
/*: ## Exercise - Concatenation and Interpolation Create a `city` constant and assign it a string literal representing your home city. Then create a `state` constant and assign it a string literal representing your home state. Finally, create a `home` constant and use string concatenation to assign it a string representing your home city and state (i.e. Portland, Oregon). Print the value of `home`. */ let city = "Seville" let state = "Andalusia" let home = "\(city), \(state)" print(home) /*: Use the compound assignment operator (`+=`) to add `home` to `introduction` below. Print the value of `introduction`. */ var introduction = "I live in" introduction += " \(home)" print(introduction) /*: Declare a `name` constant and assign it your name as a string literal. Then declare an `age` constant and give it your current age as an `Int`. Then print the following phrase using string interpolation: - "My name is <INSERT NAME HERE> and after my next birthday I will be <INSERT AGE HERE> years old." Insert `name` where indicated, and insert a mathematical expression that evaluates to your current age plus one where indicated. */ let name = "Guillermo" let age = 23 print("My name is \(name) and after my next birthday I will be \(age + 1) years old.") //: [Previous](@previous) | page 2 of 5 | [Next: App Exercise - Notifications](@next)
mit
4344f93da991a7d094e3ef16bff36297
46.137931
352
0.722751
4.032448
false
false
false
false
blockchain/My-Wallet-V3-iOS
BlockchainTests/AppFeature/Mocks/MockNabuUserService.swift
1
1084
import Combine import Errors import MoneyKit import PlatformKit import ToolKit final class MockNabuUserService: NabuUserServiceAPI { struct StubbedResults { var user: AnyPublisher<NabuUser, NabuUserServiceError> = .empty() var fetchUser: AnyPublisher<NabuUser, NabuUserServiceError> = .empty() var setInitialResidentialInfo: AnyPublisher<Void, NabuUserServiceError> = .empty() var setTradingCurrency: AnyPublisher<Void, Nabu.Error> = .empty() } var stubbedResults = StubbedResults() var user: AnyPublisher<NabuUser, NabuUserServiceError> { stubbedResults.user } func fetchUser() -> AnyPublisher<NabuUser, NabuUserServiceError> { stubbedResults.fetchUser } func setInitialResidentialInfo( country: String, state: String? ) -> AnyPublisher<Void, NabuUserServiceError> { stubbedResults.setInitialResidentialInfo } func setTradingCurrency( _ currency: FiatCurrency ) -> AnyPublisher<Void, Nabu.Error> { stubbedResults.setTradingCurrency } }
lgpl-3.0
7b3cc4cc081268f04e2f3056dfdcfd5a
27.526316
90
0.704797
5.186603
false
false
false
false
qiuncheng/study-for-swift
YLQRCode/YLQRCode/YLQRCodeHelper/YLQRScanCommon.swift
1
1173
// // YLCommon.swift // YLQRCode // // Created by yolo on 2017/1/1. // Copyright © 2017年 Qiuncheng. All rights reserved. // import UIKit import AudioToolbox typealias CompletionHandler<T> = (T) -> Void typealias YLQRScanResult = String extension DispatchQueue { static func safeMainQueue(block: @escaping () -> Void) { if !Thread.isMainThread { DispatchQueue.main.async(execute: block) } else { block() } } } struct YLQRScanCommon { static func playSound() { guard let filePath = Bundle.main.path(forResource: "sound", ofType: "caf") else { let alertView = UIAlertView(title: "提醒", message: "找不到音频文件", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alertView.show() return } let soundURL = URL(fileURLWithPath: filePath) var soundID: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID) // AudioServicesPlayAlertSound(soundID) AudioServicesPlaySystemSound(soundID) AudioServicesRemoveSystemSoundCompletion(soundID) } }
mit
4b433464691a06fbb16749a3dc45aeb2
27.6
137
0.645105
4.503937
false
false
false
false
abertelrud/swift-package-manager
Sources/Workspace/Diagnostics.swift
2
8973
//===----------------------------------------------------------------------===// // // This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Foundation import PackageGraph import PackageLoading import PackageModel import TSCBasic public struct ManifestParseDiagnostic: CustomStringConvertible { public let errors: [String] public let diagnosticFile: AbsolutePath? public init(_ errors: [String], diagnosticFile: AbsolutePath?) { self.errors = errors self.diagnosticFile = diagnosticFile } public var description: String { "manifest parse error(s):\n" + errors.joined(separator: "\n") } } public enum WorkspaceDiagnostics { // MARK: - Errors /// The diagnostic triggered when an operation fails because its completion /// would lose the uncommited changes in a repository. public struct UncommitedChanges: Error, CustomStringConvertible { /// The local path to the repository. public let repositoryPath: AbsolutePath public var description: String { return "repository '\(repositoryPath)' has uncommited changes" } } /// The diagnostic triggered when an operation fails because its completion /// would lose the unpushed changes in a repository. public struct UnpushedChanges: Error, CustomStringConvertible { /// The local path to the repository. public let repositoryPath: AbsolutePath public var description: String { return "repository '\(repositoryPath)' has unpushed changes" } } /// The diagnostic triggered when the unedit operation fails because the dependency /// is not in edit mode. public struct DependencyNotInEditMode: Error, CustomStringConvertible { /// The name of the dependency being unedited. public let dependencyName: String public var description: String { return "dependency '\(dependencyName)' not in edit mode" } } /// The diagnostic triggered when the edit operation fails because the branch /// to be created already exists. public struct BranchAlreadyExists: Error, CustomStringConvertible { /// The branch to create. public let branch: String public var description: String { return "branch '\(branch)' already exists" } } /// The diagnostic triggered when the edit operation fails because the specified /// revision does not exist. public struct RevisionDoesNotExist: Error, CustomStringConvertible { /// The revision requested. public let revision: String public var description: String { return "revision '\(revision)' does not exist" } } } extension Basics.Diagnostic { static func dependencyNotFound(packageName: String) -> Self { .warning("dependency '\(packageName)' was not found") } static func editBranchNotCheckedOut(packageName: String, branchName: String) -> Self { .warning("dependency '\(packageName)' already exists at the edit destination; not checking-out branch '\(branchName)'") } static func editRevisionNotUsed(packageName: String, revisionIdentifier: String) -> Self { .warning("dependency '\(packageName)' already exists at the edit destination; not using revision '\(revisionIdentifier)'") } static func editedDependencyMissing(packageName: String) -> Self { .warning("dependency '\(packageName)' was being edited but is missing; falling back to original checkout") } static func checkedOutDependencyMissing(packageName: String) -> Self { .warning("dependency '\(packageName)' is missing; cloning again") } static func registryDependencyMissing(packageName: String) -> Self { .warning("dependency '\(packageName)' is missing; downloading again") } static func customDependencyMissing(packageName: String) -> Self { .warning("dependency '\(packageName)' is missing; retrieving again") } static func artifactInvalidArchive(artifactURL: URL, targetName: String) -> Self { .error("invalid archive returned from '\(artifactURL.absoluteString)' which is required by binary target '\(targetName)'") } static func artifactChecksumChanged(targetName: String) -> Self { .error("artifact of binary target '\(targetName)' has changed checksum; this is a potential security risk so the new artifact won't be downloaded") } static func artifactInvalidChecksum(targetName: String, expectedChecksum: String, actualChecksum: String?) -> Self { .error("checksum of downloaded artifact of binary target '\(targetName)' (\(actualChecksum ?? "none")) does not match checksum specified by the manifest (\(expectedChecksum))") } static func artifactFailedDownload(artifactURL: URL, targetName: String, reason: String) -> Self { .error("failed downloading '\(artifactURL.absoluteString)' which is required by binary target '\(targetName)': \(reason)") } static func artifactFailedValidation(artifactURL: URL, targetName: String, reason: String) -> Self { .error("failed validating archive from '\(artifactURL.absoluteString)' which is required by binary target '\(targetName)': \(reason)") } static func remoteArtifactFailedExtraction(artifactURL: URL, targetName: String, reason: String) -> Self { .error("failed extracting '\(artifactURL.absoluteString)' which is required by binary target '\(targetName)': \(reason)") } static func localArtifactFailedExtraction(artifactPath: AbsolutePath, targetName: String, reason: String) -> Self { .error("failed extracting '\(artifactPath)' which is required by binary target '\(targetName)': \(reason)") } static func remoteArtifactNotFound(artifactURL: URL, targetName: String) -> Self { .error("downloaded archive of binary target '\(targetName)' from '\(artifactURL.absoluteString)' does not contain a binary artifact.") } static func localArchivedArtifactNotFound(archivePath: AbsolutePath, targetName: String) -> Self { .error("local archive of binary target '\(targetName)' at '\(archivePath)' does not contain a binary artifact.") } static func localArtifactNotFound(artifactPath: AbsolutePath, targetName: String) -> Self { .error("local binary target '\(targetName)' at '\(artifactPath)' does not contain a binary artifact.") } } extension FileSystemError: CustomStringConvertible { public var description: String { guard let path = path else { switch self.kind { case .invalidAccess: return "invalid access" case .ioError(let code): return "encountered I/O error (code: \(code))" case .isDirectory: return "is a directory" case .noEntry: return "doesn't exist in file system" case .notDirectory: return "is not a directory" case .unsupported: return "unsupported operation" case .unknownOSError: return "unknown system error" case .alreadyExistsAtDestination: return "already exists in file system" case .couldNotChangeDirectory: return "could not change directory" case .mismatchedByteCount(expected: let expected, actual: let actual): return "mismatched byte count, expected \(expected), got \(actual)" } } switch self.kind { case .invalidAccess: return "invalid access to \(path)" case .ioError(let code): return "encountered an I/O error (code: \(code)) while reading \(path)" case .isDirectory: return "\(path) is a directory" case .noEntry: return "\(path) doesn't exist in file system" case .notDirectory: return "\(path) is not a directory" case .unsupported: return "unsupported operation on \(path)" case .unknownOSError: return "unknown system error while operating on \(path)" case .alreadyExistsAtDestination: return "\(path) already exists in file system" case .couldNotChangeDirectory: return "could not change directory to \(path)" case .mismatchedByteCount(expected: let expected, actual: let actual): return "mismatched byte count, expected \(expected), got \(actual)" } } }
apache-2.0
ead2c4546fe5d048c38ccd6682be8a74
40.541667
184
0.655745
5.312611
false
false
false
false
abertelrud/swift-package-manager
Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift
2
44471
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Foundation @testable import PackageCollections import PackageModel import SPMTestSupport import TSCBasic import XCTest class PackageIndexAndCollectionsTests: XCTestCase { func testCollectionAddRemoveGetList() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections() let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list, mockCollections, "list count should match") } do { let collection = try tsc_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } XCTAssertEqual(collection, mockCollections.first, "collection should match") } do { _ = try tsc_await { callback in indexAndCollections.removeCollection(mockCollections.first!.source, callback: callback) } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count - 1, "list count should match") } } func testRefreshCollections() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections() let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } _ = try tsc_await { callback in indexAndCollections.refreshCollections(callback: callback) } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } func testRefreshCollection() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections() let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in // save directly to storage to circumvent refresh on add _ = try tsc_await { callback in storage.sources.add(source: collection.source, order: nil, callback: callback) } } _ = try tsc_await { callback in indexAndCollections.refreshCollection(mockCollections.first!.source, callback: callback) } let collection = try tsc_await { callback in indexAndCollections.getCollection(mockCollections.first!.source, callback: callback) } XCTAssertEqual(collection, mockCollections.first, "collection should match") } func testListPackages() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } var mockCollections = makeMockCollections(count: 5) let mockTargets = [UUID().uuidString, UUID().uuidString].map { PackageCollectionsModel.Target(name: $0, moduleName: $0) } let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]), PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)] let toolsVersion = ToolsVersion(string: "5.2")! let mockManifest = PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: UUID().uuidString, targets: mockTargets, products: mockProducts, minimumPlatformVersions: nil ) let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0), title: nil, summary: nil, manifests: [toolsVersion: mockManifest], defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil) let mockPackageURL = "https://packages.mock/\(UUID().uuidString)" let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL), location: mockPackageURL, summary: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], versions: [mockVersion], watchersCount: nil, readmeURL: nil, license: nil, authors: nil, languages: nil) let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) mockCollections.append(mockCollection) mockCollections.append(mockCollection2) let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { let fetchCollections = Set(mockCollections.map { $0.identifier } + [mockCollection.identifier, mockCollection2.identifier]) let expectedPackages = Set(mockCollections.flatMap { $0.packages.map { $0.identity } } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) let searchResult = try tsc_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") } // Call API for specific collections do { let fetchCollections = Set([mockCollections[0].identifier, mockCollection.identifier, mockCollection2.identifier]) let expectedPackages = Set(mockCollections[0].packages.map { $0.identity } + [mockPackage.identity]) let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier]) let searchResult = try tsc_await { callback in indexAndCollections.listPackages(collections: fetchCollections, callback: callback) } XCTAssertEqual(searchResult.items.count, expectedPackages.count, "list count should match") XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, "items should match") XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, "collections should match") } } func testListTargets() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections() let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } let targetsList = try tsc_await { callback in indexAndCollections.listTargets(callback: callback) } let expectedTargets = Set(mockCollections.flatMap { $0.packages.flatMap { $0.versions.flatMap { $0.defaultManifest!.targets.map { $0.name } } } }) XCTAssertEqual(Set(targetsList.map { $0.target.name }), expectedTargets, "targets should match") let targetsPackagesList = Set(targetsList.flatMap { $0.packages }) let expectedPackages = Set(mockCollections.flatMap { $0.packages.filter { !$0.versions.filter { !expectedTargets.isDisjoint(with: $0.defaultManifest!.targets.map { $0.name }) }.isEmpty } }.map { $0.identity }) XCTAssertEqual(targetsPackagesList.count, expectedPackages.count, "packages should match") let targetsCollectionsList = Set(targetsList.flatMap { $0.packages.flatMap { $0.collections } }) let expectedCollections = Set(mockCollections.filter { !$0.packages.filter { expectedPackages.contains($0.identity) }.isEmpty }.map { $0.identifier }) XCTAssertEqual(targetsCollectionsList, expectedCollections, "collections should match") } func testFindTargets() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } var mockCollections = makeMockCollections() let mockTargets = [UUID().uuidString, UUID().uuidString].map { PackageCollectionsModel.Target(name: $0, moduleName: $0) } let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]), PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)] let toolsVersion = ToolsVersion(string: "5.2")! let mockManifest = PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: UUID().uuidString, targets: mockTargets, products: mockProducts, minimumPlatformVersions: nil ) let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0), title: nil, summary: nil, manifests: [toolsVersion: mockManifest], defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil) let mockPackageURL = "https://packages.mock/\(UUID().uuidString)" let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL), location: mockPackageURL, summary: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], versions: [mockVersion], watchersCount: nil, readmeURL: nil, license: nil, authors: nil, languages: nil) let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let expectedCollections = [mockCollection, mockCollection2] let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted() mockCollections.append(contentsOf: expectedCollections) let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } do { // search by exact target name let searchResult = try tsc_await { callback in indexAndCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") } do { // search by prefix target name let searchResult = try tsc_await { callback in indexAndCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], "packages should match") XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, "collections should match") } do { // empty search let searchResult = try tsc_await { callback in indexAndCollections.findTargets(UUID().uuidString, searchType: .exactMatch, callback: callback) } XCTAssertEqual(searchResult.items.count, 0, "list count should match") } } func testListPackagesInIndex() throws { let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let packageCollections = makePackageCollections(mockCollections: [], storage: storage) let mockPackages = (0..<10).map { packageIndex -> PackageCollectionsModel.Package in makeMockPackage(id: "package-\(packageIndex)") } let packageIndex = MockPackageIndex(packages: mockPackages) let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } let result = try tsc_await { callback in indexAndCollections.listPackagesInIndex(offset: 1, limit: 5, callback: callback) } XCTAssertFalse(result.items.isEmpty) } func testGetPackageMetadata() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) let mockPackage = mockCollections.last!.packages.last! let mockMetadata = makeMockPackageBasicMetadata() let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata]) let packageCollections = makePackageCollections(mockCollections: mockCollections, metadataProvider: metadataProvider, storage: storage) let packageIndex = MockPackageIndex(packages: mockCollections.last!.packages) let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } let metadata = try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") // Metadata comes from package index - package returned as-is, no merging XCTAssertEqual(metadata.package, mockPackage) XCTAssertNotNil(metadata.provider) XCTAssertEqual(metadata.provider?.name, "package index") } func testGetPackageMetadata_brokenIndex() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let mockCollections = makeMockCollections(count: 3) let mockPackage = mockCollections.last!.packages.last! let mockMetadata = makeMockPackageBasicMetadata() let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata]) let packageCollections = makePackageCollections(mockCollections: mockCollections, metadataProvider: metadataProvider, storage: storage) let packageIndex = BrokenPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } do { let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, 0, "list should be empty") } do { try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, order: nil, callback: callback) } } let list = try tsc_await { callback in indexAndCollections.listCollections(callback: callback) } XCTAssertEqual(list.count, mockCollections.count, "list count should match") } let metadata = try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) } let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier }) XCTAssertEqual(Set(metadata.collections), expectedCollections, "collections should match") // Metadata comes from collections - merged with basic metadata let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: mockMetadata) XCTAssertEqual(metadata.package, expectedMetadata, "package should match") XCTAssertNil(metadata.provider) } func testGetPackageMetadata_indexAndCollectionError() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } let packageCollections = makePackageCollections(mockCollections: [], storage: storage) let packageIndex = BrokenPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } let mockPackage = makeMockPackage(id: "test-package") // Package not found in collections; index is broken XCTAssertThrowsError(try tsc_await { callback in indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, callback: callback) }) { error in // Index error is returned guard let _ = error as? BrokenPackageIndex.TerribleThing else { return XCTFail("Expected BrokenPackageIndex.TerribleThing") } } } func testFindPackages() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } var mockCollections = makeMockCollections() let mockTargets = [UUID().uuidString, UUID().uuidString].map { PackageCollectionsModel.Target(name: $0, moduleName: $0) } let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]), PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)] let toolsVersion = ToolsVersion(string: "5.2")! let mockManifest = PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: UUID().uuidString, targets: mockTargets, products: mockProducts, minimumPlatformVersions: nil ) let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0), title: nil, summary: nil, manifests: [toolsVersion: mockManifest], defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil) let url = "https://packages.mock/\(UUID().uuidString)" let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: url), location: url, summary: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], versions: [mockVersion], watchersCount: nil, readmeURL: nil, license: nil, authors: nil, languages: nil) let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let expectedCollections = [mockCollection, mockCollection2] let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted() mockCollections.append(contentsOf: expectedCollections) let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = MockPackageIndex(packages: [mockPackage]) let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } // both index and collections do { let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], "indexes should match") } // index only do { let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertTrue(searchResult.items.first?.collections.isEmpty ?? true, "collections should match") XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], "indexes should match") } // collections only do { let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") XCTAssertTrue(searchResult.items.first?.indexes.isEmpty ?? true, "indexes should match") } } func testFindPackages_brokenIndex() throws { try PackageCollectionsTests_skipIfUnsupportedPlatform() let storage = makeMockStorage() defer { XCTAssertNoThrow(try storage.close()) } var mockCollections = makeMockCollections() let mockTargets = [UUID().uuidString, UUID().uuidString].map { PackageCollectionsModel.Target(name: $0, moduleName: $0) } let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]), PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)] let toolsVersion = ToolsVersion(string: "5.2")! let mockManifest = PackageCollectionsModel.Package.Version.Manifest( toolsVersion: toolsVersion, packageName: UUID().uuidString, targets: mockTargets, products: mockProducts, minimumPlatformVersions: nil ) let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0), title: nil, summary: nil, manifests: [toolsVersion: mockManifest], defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, createdAt: nil) let url = "https://packages.mock/\(UUID().uuidString)" let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: url), location: url, summary: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], versions: [mockVersion], watchersCount: nil, readmeURL: nil, license: nil, authors: nil, languages: nil) let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: URL(string: "https://feed.mock/\(UUID().uuidString)")!), name: UUID().uuidString, overview: UUID().uuidString, keywords: [UUID().uuidString, UUID().uuidString], packages: [mockPackage], createdAt: Date(), createdBy: nil, signature: nil) let expectedCollections = [mockCollection, mockCollection2] let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted() mockCollections.append(contentsOf: expectedCollections) let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage) let packageIndex = BrokenPackageIndex() let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP) defer { XCTAssertNoThrow(try indexAndCollections.close()) } try mockCollections.forEach { collection in _ = try tsc_await { callback in indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) }, callback: callback) } } // both index and collections do { let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") // Results come from collections since index is broken XCTAssertEqual(searchResult.items.first?.indexes, [], "indexes should match") } // index only do { XCTAssertThrowsError(try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .index, callback: callback) }) { error in guard error is BrokenPackageIndex.TerribleThing else { return XCTFail("invalid error \(error)") } } } // collections only do { let searchResult = try tsc_await { callback in indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil), callback: callback) } XCTAssertEqual(searchResult.items.count, 1, "list count should match") XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, "collections should match") // Not searching in index so should not be impacted by its error XCTAssertTrue(searchResult.items.first?.indexes.isEmpty ?? true, "indexes should match") } } } private func makePackageCollections( mockCollections: [PackageCollectionsModel.Collection], metadataProvider: PackageMetadataProvider = MockMetadataProvider([:]), storage: PackageCollections.Storage ) -> PackageCollections { let configuration = PackageCollections.Configuration() let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)] let metadataProvider = metadataProvider return PackageCollections( configuration: configuration, fileSystem: localFileSystem, observabilityScope: ObservabilitySystem.NOOP, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider ) } private struct MockPackageIndex: PackageIndexProtocol { let isEnabled = true let url: URL private let packages: [PackageCollectionsModel.Package] init( url: URL = URL(string: "https://mock-package-index")!, packages: [PackageCollectionsModel.Package] = [] ) { self.url = url self.packages = packages } func getPackageMetadata( identity: PackageIdentity, location: String?, callback: @escaping (Result<PackageCollectionsModel.PackageMetadata, Error>) -> Void ) { guard let package = self.packages.first(where: { $0.identity == identity }) else { return callback(.failure(NotFoundError("Package \(identity) not found"))) } callback(.success((package: package, collections: [], provider: .init(name: "package index", authTokenType: nil, isAuthTokenConfigured: true)))) } func findPackages( _ query: String, callback: @escaping (Result<PackageCollectionsModel.PackageSearchResult, Error>) -> Void ) { let items = self.packages.filter { $0.identity.description.contains(query) } callback(.success(.init(items: items.map { .init(package: $0, collections: [], indexes: [self.url]) }))) } func listPackages( offset: Int, limit: Int, callback: @escaping (Result<PackageCollectionsModel.PaginatedPackageList, Error>) -> Void ) { guard !self.packages.isEmpty, offset < self.packages.count, limit > 0 else { return callback(.success(.init(items: [], offset: offset, limit: limit, total: self.packages.count))) } callback(.success(.init( items: Array(self.packages[offset..<min(self.packages.count, offset + limit)]), offset: offset, limit: limit, total: self.packages.count ))) } } private struct BrokenPackageIndex: PackageIndexProtocol { let isEnabled = true func getPackageMetadata( identity: PackageIdentity, location: String?, callback: @escaping (Result<PackageCollectionsModel.PackageMetadata, Error>) -> Void ) { callback(.failure(TerribleThing())) } func findPackages( _ query: String, callback: @escaping (Result<PackageCollectionsModel.PackageSearchResult, Error>) -> Void ) { callback(.failure(TerribleThing())) } func listPackages( offset: Int, limit: Int, callback: @escaping (Result<PackageCollectionsModel.PaginatedPackageList, Error>) -> Void ) { callback(.failure(TerribleThing())) } struct TerribleThing: Error {} }
apache-2.0
041d5bdb7c0fea05ceff87de1eacecf7
57.591568
217
0.576151
6.522587
false
false
false
false
DenHeadless/DTCollectionViewManager
Sources/DTCollectionViewManager/DTCollectionViewDelegateWrapper.swift
1
15542
// // DTCollectionViewDelegateWrapper.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 13.08.17. // Copyright © 2017 Denys Telezhkin. 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 UIKit import DTModelStorage /// Base class for delegate wrappers. open class DTCollectionViewDelegateWrapper : NSObject { /// Weak reference to `DTCollectionViewManageable` instance. It is used to dispatch `UICollectionView` delegate events in case `delegate` implements them. weak var delegate: AnyObject? var collectionView: UICollectionView? { return manager?.collectionView } var viewFactory: CollectionViewFactory? { return manager?.viewFactory } var storage: Storage? { return manager?.storage } weak var manager: DTCollectionViewManager? /// Creates delegate wrapper with `delegate` and `collectionViewManager` public init(delegate: AnyObject?, collectionViewManager: DTCollectionViewManager) { self.delegate = delegate manager = collectionViewManager } /// Array of `DTCollectionViewManager` reactions /// - SeeAlso: `EventReaction`. final var unmappedReactions = [EventReaction]() { didSet { delegateWasReset() } } func delegateWasReset() { // Subclasses need to override this method, resetting `UICollectionView` delegate or datasource. // Resetting delegate and dataSource are needed, because UICollectionView caches results of `respondsToSelector` call, and never calls it again until `setDelegate` method is called. // We force UICollectionView to flush that cache and query us again, because with new event we might have new delegate or datasource method to respond to. } /// Returns header model for section at `index`, or nil if it is not found. final func headerModel(forSection index: Int) -> Any? { return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.headerModel(forSection: index) as Any) } /// Returns footer model for section at `index`, or nil if it is not found. final func footerModel(forSection index: Int) -> Any? { return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.footerModel(forSection: index) as Any) } final func supplementaryModel(ofKind kind: String, forSectionAt indexPath: IndexPath) -> Any? { return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.supplementaryModel(ofKind: kind, forSectionAt: indexPath) as Any) } final internal func appendReaction<T, U>(for cellClass: T.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (T, T.ModelType, IndexPath) -> U) where T: ModelTransfer, T:UICollectionViewCell { let reaction = EventReaction(viewType: T.self, modelType: T.ModelType.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: .cell, type: T.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: T.self, methodName: methodName) } final internal func append4ArgumentReaction<Cell, Argument, Result> (for cellClass: Cell.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Argument, Cell, Cell.ModelType, IndexPath) -> Result) where Cell: ModelTransfer, Cell: UICollectionViewCell { let reaction = FourArgumentsEventReaction(Cell.self, modelType: Cell.ModelType.self, argument: Argument.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: .cell, type: Cell.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: Cell.self, methodName: methodName) } final internal func append5ArgumentReaction<Cell, ArgumentOne, ArgumentTwo, Result> (for cellClass: Cell.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (ArgumentOne, ArgumentTwo, Cell, Cell.ModelType, IndexPath) -> Result) where Cell: ModelTransfer, Cell: UICollectionViewCell { let reaction = FiveArgumentsEventReaction(Cell.self, modelType: Cell.ModelType.self, argumentOne: ArgumentOne.self, argumentTwo: ArgumentTwo.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: .cell, type: Cell.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: Cell.self, methodName: methodName) } final internal func appendReaction<Model, ReturnType>(viewType: ViewType, for modelClass: Model.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Model, IndexPath) -> ReturnType) { let reaction = EventReaction(modelType: Model.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: viewType, modelType: Model.self, reaction: reaction, signature: signature) manager?.verifyItemEvent(for: Model.self, methodName: methodName) } final func appendReaction<View, ReturnType>(forSupplementaryKind kind: String, supplementaryClass: View.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (View, View.ModelType, IndexPath) -> ReturnType) where View: ModelTransfer, View: UICollectionReusableView { let reaction = EventReaction(viewType: View.self, modelType: View.ModelType.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: .supplementaryView(kind: kind), type: View.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: View.self, methodName: methodName) } final private func appendMappedReaction<View:UIView>(viewType: ViewType, type: View.Type, reaction: EventReaction, signature: EventMethodSignature) { let compatibleMappings = (viewFactory?.mappings ?? []).filter { (($0.viewClass as? UIView.Type)?.isSubclass(of: View.self) ?? false) && $0.viewType == viewType } if compatibleMappings.count == 0 { manager?.anomalyHandler.reportAnomaly(.eventRegistrationForUnregisteredMapping(viewClass: String(describing: View.self), signature: signature.rawValue)) } compatibleMappings.forEach { mapping in mapping.reactions.append(reaction) } delegateWasReset() } final private func appendMappedReaction<Model>(viewType: ViewType, modelType: Model.Type, reaction: EventReaction, signature: EventMethodSignature) { let compatibleMappings = (viewFactory?.mappings ?? []).filter { $0.viewType == viewType && $0.modelTypeTypeCheckingBlock(Model.self) } if compatibleMappings.count == 0 { manager?.anomalyHandler.reportAnomaly(.eventRegistrationForUnregisteredMapping(viewClass: String(describing: Model.self), signature: signature.rawValue)) } compatibleMappings.forEach { mapping in mapping.reactions.append(reaction) } delegateWasReset() } final func appendNonCellReaction(_ signature: EventMethodSignature, closure: @escaping () -> Any) { unmappedReactions.append(EventReaction(signature: signature.rawValue, closure)) } final func appendNonCellReaction<Arg>(_ signature: EventMethodSignature, closure: @escaping (Arg) -> Any) { unmappedReactions.append(EventReaction(argument: Arg.self, signature: signature.rawValue, closure)) } final func appendNonCellReaction<Arg1, Arg2, Result>(_ signature: EventMethodSignature, closure: @escaping (Arg1, Arg2) -> Result) { unmappedReactions.append(EventReaction(argumentOne: Arg1.self, argumentTwo: Arg2.self, signature: signature.rawValue, closure)) } final func performCellReaction(_ signature: EventMethodSignature, location: IndexPath, provideCell: Bool) -> Any? { var cell : UICollectionViewCell? if provideCell { cell = collectionView?.cellForItem(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.performReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, view: cell, model: model, location: location) } final func perform4ArgumentCellReaction(_ signature: EventMethodSignature, argument: Any, location: IndexPath, provideCell: Bool) -> Any? { var cell : UICollectionViewCell? if provideCell { cell = collectionView?.cellForItem(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.perform4ArgumentsReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, argument: argument, view: cell, model: model, location: location) } final func perform5ArgumentCellReaction(_ signature: EventMethodSignature, argumentOne: Any, argumentTwo: Any, location: IndexPath, provideCell: Bool) -> Any? { var cell : UICollectionViewCell? if provideCell { cell = collectionView?.cellForItem(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.perform5ArgumentsReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, firstArgument: argumentOne, secondArgument: argumentTwo, view: cell, model: model, location: location) } final func performNillableCellReaction(_ reaction: EventReaction, location: IndexPath, provideCell: Bool) -> Any? { var cell : UICollectionViewCell? if provideCell { cell = collectionView?.cellForItem(at: location) } guard let model = storage?.item(at: location) else { return nil } return reaction.performWithArguments((cell as Any, model, location)) } final func cellReaction(_ signature: EventMethodSignature, location: IndexPath) -> EventReaction? { guard let model = storage?.item(at: location) else { return nil } return EventReaction.reaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, forModel: model, at: location, view: nil) } func performNonCellReaction(_ signature: EventMethodSignature) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue) } func performNonCellReaction<T>(_ signature: EventMethodSignature, argument: T) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue, argument: argument) } func performNonCellReaction<T, U>(_ signature: EventMethodSignature, argumentOne: T, argumentTwo: U) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue, argumentOne: argumentOne, argumentTwo: argumentTwo) } func performSupplementaryReaction(ofKind kind: String, signature: EventMethodSignature, location: IndexPath, view: UICollectionReusableView?) -> Any? { guard let model = supplementaryModel(ofKind: kind, forSectionAt: location) else { return nil } return EventReaction.performReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, view: view, model: model, location: location, supplementaryKind: kind) } // MARK: - Target Forwarding /// Forwards `aSelector`, that is not implemented by `DTCollectionViewManager` to delegate, if it implements it. /// /// - Returns: `DTCollectionViewManager` delegate open override func forwardingTarget(for aSelector: Selector) -> Any? { return delegate } /// Returns true, if `DTCollectionViewManageable` implements `aSelector`, or `DTCollectionViewManager` has an event, associated with this selector. /// /// - SeeAlso: `EventMethodSignature` open override func responds(to aSelector: Selector) -> Bool { if self.delegate?.responds(to: aSelector) ?? false { return true } if super.responds(to: aSelector) { if let eventSelector = EventMethodSignature(rawValue: String(describing: aSelector)) { return unmappedReactions.contains { $0.methodSignature == eventSelector.rawValue } || (viewFactory?.mappings ?? []) .contains(where: { mapping in mapping.reactions.contains(where: { reaction in reaction.methodSignature == eventSelector.rawValue }) }) } return true } return false } }
mit
1abca286c24a9bcd2125cac1f5fe8bd3
53.721831
189
0.624542
5.688507
false
false
false
false
badoo/Chatto
ChattoApp/ChattoApp/Source/Time Separator/TimeSeparatorCollectionViewCell.swift
1
2200
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 UIKit import Chatto class TimeSeparatorCollectionViewCell: UICollectionViewCell { private let label: UILabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.label.font = UIFont.systemFont(ofSize: 12) self.label.textAlignment = .center self.label.textColor = UIColor.gray self.contentView.addSubview(label) } var text: String = "" { didSet { if oldValue != text { self.setTextOnLabel(text) } } } private func setTextOnLabel(_ text: String) { self.label.text = text self.setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() self.label.bounds.size = self.label.sizeThatFits(self.contentView.bounds.size) self.label.center = self.contentView.center } }
mit
6d86ce91ca52d4db1dfc5291440b8ca7
31.352941
86
0.702727
4.700855
false
false
false
false
iOSTestApps/TheReservist
TheReservist/Products.swift
2
1314
// // Products.swift // TheReservist // // Created by Marcus Kida on 23/09/2014. // Copyright (c) 2014 Marcus Kida. All rights reserved. // import Foundation class Products { let json = JSON(data: NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("parts", ofType: "json")!)) func name(partNumber: String) -> String? { return property(partNumber, key: "localizedName") } func color(partNumber: String) -> String? { return property(partNumber, key: "colorName") } func size(partNumber: String) -> String? { return property(partNumber, key: "size") } func colorUrl(partNumber: String) -> NSURL? { if let urlString = property(partNumber, key: "colorUrl") { return NSURL(string: urlString) } return nil; } func colorUrl2x(partNumber: String) -> NSURL? { if let urlString = property(partNumber, key: "colorUrl2x") { return NSURL(string: urlString) } return nil; } private func property(partNumber: String, key: String) -> String? { if let product = json[partNumber].dictionaryValue { if let name = product[key] { return name.stringValue; } } return nil } }
mit
0a5341e80cd9c6f9debe99be9ef11066
25.836735
114
0.586758
4.322368
false
false
false
false
darthpelo/TimerH2O
TimerH2O/TimerH2O/AppDelegate.swift
1
2560
// // AppDelegate.swift // TimerH2O // // Created by Alessio Roberto on 23/10/16. // Copyright © 2016 Alessio Roberto. All rights reserved. // import UIKit import Fabric import FacebookCore import Firebase import Crashlytics import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var watcher = WatchManager() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Fabric.sharedSDK().debug = true Fabric.with([Crashlytics.self]) AppEventsLogger.activate(application) if UserDefaults.standard.userCreated == false { if let userId = UIDevice.current.identifierForVendor?.uuidString { RealmManager().create(newUser: userId) UserDefaults.standard.userCreated = true UserDefaults.standard.synchronize() } } return true } func applicationDidEnterBackground(_ application: UIApplication) { scheduleLocalNotification() } func applicationDidBecomeActive(_ application: UIApplication) { UIApplication.shared.applicationIconBadgeNumber = 0 if #available(iOS 10.0, *) { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [TH2OConstants.UserNotification.notificationRequest]) } Presenter().updateWatch() } func applicationWillTerminate(_ application: UIApplication) { AnswerManager().log(event: "Application Was Killed", withCustomAttributes: ["VC": "AppDelegate", "Function": "applicationWillTerminate"]) scheduleLocalNotification() } } extension AppDelegate { fileprivate func scheduleLocalNotification() { TimerManager.sharedInstance.stop() guard let endTime = SessionManagerImplementation().endTimer() else { return } // Create Notification Content if #available(iOS 10.0, *) { // Time interval let timeInterval = endTime.timeIntervalSince(Date()) if timeInterval >= 0 { localNotificationRequest(endTime: endTime) } } else { // Fallback on earlier versions } } }
mit
a58ed04231922e89aa7fc625275e7230
29.105882
151
0.616256
6.078385
false
false
false
false
FrainL/FxJSON
FxJSON.playground/Pages/Using Protocols.xcplaygroundpage/Contents.swift
1
3038
/*: > # To use **FxJSON.playground**: 1. Open **FxJSON.xcworkspace**. 1. Build the **FxJSON** scheme using iPhone 5s simulator (**Product** → **Build**). 1. Open **FxJSON** playground in the **Project navigator**. [Deal with JSON](@previous) */ import FxJSON import Foundation import UIKit //: Assume that you have a json data like this: let data = try? Data(contentsOf: #fileLiteral(resourceName: "JSON.json")) let json = JSON(jsonData: data) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let transform = DateTransform.formatter(formatter) DateTransform.default = transform //: ## 1. JSONDecodable, JSONEncodable //: Struct adopting JSONDecodable struct BasicStruct: JSONDecodable { let userID: Int64 let name: String let admin: Bool let signUpTime: Date? // init(decode json: JSON) throws { // userID = try json["userID"]< // name = try json["name"]< // admin = try json["admin"]< // signUpTime = try json["signUpTime"]< // } } extension BasicStruct { static func specificOptions() -> [String: SpecificOption] { return [ "userID": ["userID", .nonNil], // same as .index("userID") "admin": [.defaultValue(true), .ignore], "signUpTime": [.transform(transform), .ignoreIfNull] ] } } let admin = BasicStruct(json["data", "users", 0]) //: Class adopting JSONDecodable class BasicClass: JSONDecodable, JSONEncodable { let userID: Int64 let name: String let admin: Bool let signUpTime: Date? required init(decode json: JSON) throws { userID = try json["userID"]< name = try json["name"]< admin = try json["admin"]< signUpTime = try json["signUpTime"]< } func encode(mapper: JSON.Mapper) { mapper["userID"] << userID mapper["name"] << name mapper["admin"] << admin mapper[ignoreIfNull: "signUpTime"] << signUpTime } } let basicClass = BasicClass(json["data", "users", 0]) class UserClass: BasicClass { let website: URL? let friends: [BasicClass] required init(decode json: JSON) throws { website = try json["website"]< friends = try json["friends"]< try super.init(decode: json) } override func encode(mapper: JSON.Mapper) { mapper[ignoreIfNull: "website"] << website mapper["friends"] << friends super.encode(mapper: mapper) } } let userClass = UserClass(json["data", "users", 1]) userClass?.json //: ## 3. JSONConvertable、JSONCodable extension UIColor: JSONConvertable { public static func convert(from json: JSON) -> Self? { guard let hex = Int(json) else { return nil } let r = (CGFloat)((hex >> 16) & 0xFF) let g = (CGFloat)((hex >> 8) & 0xFF) let b = (CGFloat)(hex & 0xFF) return self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1) } } let color = UIColor(0xFF00FF as JSON) enum ErrorCode: Int, JSONCodable { case noError case netWorkError } let errorCode = ErrorCode(json["code"])
mit
9ffe989a27273dddc8f677d2421baa27
24.711864
83
0.634476
3.633533
false
false
false
false
wltrup/Swift-WTCoreGraphicsExtensions
Example/Tests/CGPointExtensionsTests.swift
1
16785
// // CGPointExtensionsTests.swift // WTCoreGraphicsExtensions // // Created by Wagner Truppel on 2016.12.03. // // Copyright (c) 2016 Wagner Truppel. All rights reserved. // import XCTest import Foundation import WTCoreGraphicsExtensions class CGPointExtensionsTests: WTCoreGraphicsExtensionsTestsBase { func test_initFromFloats() { (1...N).forEach { _ in let a = Float(CGFloat.random(rangeMin, rangeMax)) let b = Float(CGFloat.random(rangeMin, rangeMax)) let p = CGPoint(x: a, y: b) expectedValue = CGFloat(a) resultedValue = p.x assertAbsoluteDifferenceWithinTolerance() expectedValue = CGFloat(b) resultedValue = p.y assertAbsoluteDifferenceWithinTolerance() } } func test_randomGeneratesValuesInTheExpectedRange() { let min = (rangeMin <= rangeMax ? rangeMin : rangeMax) let max = (rangeMin >= rangeMax ? rangeMin : rangeMax) (1...N).forEach { _ in let p = CGPoint.random(rangeMin, rangeMax) XCTAssertTrue(p.x >= min && p.x <= max) XCTAssertTrue(p.y >= min && p.y <= max) } } /// Tests that `random(a:b:)` creates a `CGPoint` with pseudo-random coordinates /// satisfying, independently from one another, the property that their /// generated values have an average approximating 1/2 and a variance /// approximating 1/12, when the range is [0, 1]. func test_randomRandomness() { N = 10_000 tolerance = 1e-1 enum Coordinate { case x case y } func testCoordinate(_ c: Coordinate) { let values = (1...N).map { _ -> CGFloat in let p = CGPoint.random(0, 1) return (c == Coordinate.x ? p.x : p.y) } testRandomness(values) } testCoordinate(.x) testCoordinate(.y) } func test_isNearlyEqualWithNegativeToleranceThrows() { (1...N).forEach { _ in let p1 = CGPoint.random(rangeMin, rangeMax) let p2 = CGPoint.random(rangeMin, rangeMax) let tol = try! -CGFloat.randomNonZero(0, abs(rangeMax)) do { let _ = try p2.isNearlyEqual(to: p1, tolerance: tol) XCTFail() } catch { expectedError = WTCoreGraphicsExtensionsError.negativeTolerance resultedError = error assertEqualErrors() } } } func test_isNearlyEqualWithZeroTolerance1() { (1...N).forEach { _ in var nearlyEqual: Bool let p1 = CGPoint.random(rangeMin, rangeMax) let p2 = p1 nearlyEqual = try! p2.isNearlyEqual(to: p1, tolerance: 0.0) XCTAssertTrue(nearlyEqual) nearlyEqual = try! p1.isNearlyEqual(to: p2, tolerance: 0.0) XCTAssertTrue(nearlyEqual) } } func test_isNearlyEqualWithZeroTolerance2() { (1...N).forEach { _ in var nearlyEqual: Bool let p1 = CGPoint.random(rangeMin, rangeMax) var p2 = p1 p2.x += try! CGFloat.randomNonZero(rangeMin, rangeMax) nearlyEqual = try! p2.isNearlyEqual(to: p1, tolerance: 0.0) XCTAssertFalse(nearlyEqual) nearlyEqual = try! p1.isNearlyEqual(to: p2, tolerance: 0.0) XCTAssertFalse(nearlyEqual) } } func test_isNearlyEqualWithZeroTolerance3() { (1...N).forEach { _ in var nearlyEqual: Bool let p1 = CGPoint.random(rangeMin, rangeMax) var p2 = p1 p2.y += try! CGFloat.randomNonZero(rangeMin, rangeMax) nearlyEqual = try! p2.isNearlyEqual(to: p1, tolerance: 0.0) XCTAssertFalse(nearlyEqual) nearlyEqual = try! p1.isNearlyEqual(to: p2, tolerance: 0.0) XCTAssertFalse(nearlyEqual) } } func test_isNearlyEqualWithZeroTolerance4() { (1...N).forEach { _ in var nearlyEqual: Bool let p1 = CGPoint.random(rangeMin, rangeMax) var p2 = p1 p2.x += try! CGFloat.randomNonZero(rangeMin, rangeMax) p2.y += try! CGFloat.randomNonZero(rangeMin, rangeMax) nearlyEqual = try! p2.isNearlyEqual(to: p1, tolerance: 0.0) XCTAssertFalse(nearlyEqual) nearlyEqual = try! p1.isNearlyEqual(to: p2, tolerance: 0.0) XCTAssertFalse(nearlyEqual) } } func test_isNearlyEqualWithOrWithoutCustomTolerance() { func testNearlyEqual(maxDelta: CGFloat, shouldFail: Bool) { let usingDefaultTolerance = (tolerance == CGFloat.tolerance) (1...N).forEach { _ in let p1 = CGPoint.random(rangeMin, rangeMax) var p2 = p1 if shouldFail { p2.x += maxDelta p2.y += maxDelta } else { p2.x += CGFloat.random(-maxDelta, maxDelta) p2.y += CGFloat.random(-maxDelta, maxDelta) } let p1NearlyEqualToP2: Bool let p2NearlyEqualToP1: Bool if usingDefaultTolerance { p1NearlyEqualToP2 = try! p1.isNearlyEqual(to: p2) p2NearlyEqualToP1 = try! p2.isNearlyEqual(to: p1) } else { p1NearlyEqualToP2 = try! p1.isNearlyEqual(to: p2, tolerance: tolerance) p2NearlyEqualToP1 = try! p2.isNearlyEqual(to: p1, tolerance: tolerance) } XCTAssertFalse(p1NearlyEqualToP2 == shouldFail) XCTAssertFalse(p2NearlyEqualToP1 == shouldFail) } } tolerance = CGFloat.tolerance // default tolerance testNearlyEqual(maxDelta: tolerance / 2, shouldFail: false) testNearlyEqual(maxDelta: 10 * tolerance, shouldFail: true) tolerance = 1e-2 // custom non-zero tolerance testNearlyEqual(maxDelta: tolerance / 2, shouldFail: false) testNearlyEqual(maxDelta: 10 * tolerance, shouldFail: true) } func test_isNearlyZeroWithNegativeToleranceThrows() { (1...N).forEach { _ in let p = CGPoint.random(rangeMin, rangeMax) let tol = try! -CGFloat.randomNonZero(0, abs(rangeMax)) do { let _ = try p.isNearlyZero(tolerance: tol) XCTFail() } catch { expectedError = WTCoreGraphicsExtensionsError.negativeTolerance resultedError = error assertEqualErrors() } } } func test_isNearlyZeroWithZeroTolerance0() { let p = CGPoint.zero let nearlyZero = try! p.isNearlyZero(tolerance: 0.0) XCTAssertTrue(nearlyZero) } func test_isNearlyZeroWithZeroTolerance1() { (1...N).forEach { _ in let a = try! CGFloat.randomNonZero(rangeMin, rangeMax) let p = CGPoint(x: a, y: 0) let nearlyZero = try! p.isNearlyZero(tolerance: 0.0) XCTAssertFalse(nearlyZero) } } func test_isNearlyZeroWithZeroTolerance2() { (1...N).forEach { _ in let b = try! CGFloat.randomNonZero(rangeMin, rangeMax) let p = CGPoint(x: 0, y: b) let nearlyZero = try! p.isNearlyZero(tolerance: 0.0) XCTAssertFalse(nearlyZero) } } func test_isNearlyZeroWithZeroTolerance3() { (1...N).forEach { _ in let a = try! CGFloat.randomNonZero(rangeMin, rangeMax) let b = try! CGFloat.randomNonZero(rangeMin, rangeMax) let p = CGPoint(x: a, y: b) let nearlyZero = try! p.isNearlyZero(tolerance: 0.0) XCTAssertFalse(nearlyZero) } } func test_isNearlyZeroWithOrWithoutCustomTolerance() { func testNearlyZero(maxDelta: CGFloat, shouldFail: Bool) { let usingDefaultTolerance = (tolerance == CGFloat.tolerance) (1...N).forEach { _ in let p: CGPoint if shouldFail { p = CGPoint(x: maxDelta, y: maxDelta) } else { let a = CGFloat.random(-maxDelta, maxDelta) let b = CGFloat.random(-maxDelta, maxDelta) p = CGPoint(x: a, y: b) } let pNearlyZero: Bool if usingDefaultTolerance { pNearlyZero = try! p.isNearlyZero() } else { pNearlyZero = try! p.isNearlyZero(tolerance: tolerance) } XCTAssertFalse(pNearlyZero == shouldFail) } } tolerance = CGFloat.tolerance // default tolerance testNearlyZero(maxDelta: tolerance / 2, shouldFail: false) testNearlyZero(maxDelta: 10 * tolerance, shouldFail: true) tolerance = 1e-2 // custom non-zero tolerance testNearlyZero(maxDelta: tolerance / 2, shouldFail: false) testNearlyZero(maxDelta: 10 * tolerance, shouldFail: true) } func test_distanceTo() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x1 - x2 let dy = y1 - y2 expectedValue = CGFloat(sqrt(dx*dx + dy*dy)) resultedValue = p1.distance(to: p2) assertAbsoluteDifferenceWithinTolerance() resultedValue = p2.distance(to: p1) assertAbsoluteDifferenceWithinTolerance() } } func test_distanceSquaredTo() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x1 - x2 let dy = y1 - y2 expectedValue = (dx*dx + dy*dy) resultedValue = p1.distanceSquared(to: p2) assertAbsoluteDifferenceWithinTolerance() resultedValue = p2.distanceSquared(to: p1) assertAbsoluteDifferenceWithinTolerance() } } func test_manhattanDistanceTo() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x1 - x2 let dy = y1 - y2 expectedValue = abs(dx) + abs(dy) resultedValue = p1.manhattanDistance(to: p2) assertAbsoluteDifferenceWithinTolerance() resultedValue = p2.manhattanDistance(to: p1) assertAbsoluteDifferenceWithinTolerance() } } func test_vectorTo() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x2 - x1 let dy = y2 - y1 expectedVector = CGVector(dx: dx, dy: dy) resultedVector = p1.vector(to: p2) assertEqualVectorsWithinTolerance() } } func test_vectorFrom() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x2 - x1 let dy = y2 - y1 expectedVector = CGVector(dx: dx, dy: dy) resultedVector = p2.vector(from: p1) assertEqualVectorsWithinTolerance() } } func test_vectorFromTo() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x2 - x1 let dy = y2 - y1 expectedVector = CGVector(dx: dx, dy: dy) resultedVector = CGPoint.vector(from: p1, to: p2) assertEqualVectorsWithinTolerance() expectedVector = CGVector(dx: -dx, dy: -dy) resultedVector = CGPoint.vector(from: p2, to: p1) assertEqualVectorsWithinTolerance() } } func test_operatorPointPlusVector() { (1...N).forEach { _ in let x = CGFloat.random(rangeMin, rangeMax) let y = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x, y: y) let dx = CGFloat.random(rangeMin, rangeMax) let dy = CGFloat.random(rangeMin, rangeMax) let v = CGVector(dx: dx, dy: dy) let p2 = p1 + v expectedPoint = CGPoint(x: p1.x + v.dx, y: p1.y + v.dy) resultedPoint = p2 assertEqualPointsWithinTolerance() } } func test_operatorPointMinusVector() { (1...N).forEach { _ in let x = CGFloat.random(rangeMin, rangeMax) let y = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x, y: y) let dx = CGFloat.random(rangeMin, rangeMax) let dy = CGFloat.random(rangeMin, rangeMax) let v = CGVector(dx: dx, dy: dy) let p2 = p1 - v expectedPoint = CGPoint(x: p1.x - v.dx, y: p1.y - v.dy) resultedPoint = p2 assertEqualPointsWithinTolerance() } } func test_operatorPointMinusPoint() { (1...N).forEach { _ in let x1 = CGFloat.random(rangeMin, rangeMax) let y1 = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x1, y: y1) let x2 = CGFloat.random(rangeMin, rangeMax) let y2 = CGFloat.random(rangeMin, rangeMax) let p2 = CGPoint(x: x2, y: y2) let dx = x2 - x1 let dy = y2 - y1 expectedVector = CGVector(dx: dx, dy: dy) resultedVector = p2 - p1 assertEqualVectorsWithinTolerance() } } func test_operatorPlusEqual() { (1...N).forEach { _ in let x = CGFloat.random(rangeMin, rangeMax) let y = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x, y: y) let dx = CGFloat.random(rangeMin, rangeMax) let dy = CGFloat.random(rangeMin, rangeMax) let v = CGVector(dx: dx, dy: dy) var p2 = p1 p2 += v expectedPoint = CGPoint(x: p1.x + v.dx, y: p1.y + v.dy) resultedPoint = p2 assertEqualPointsWithinTolerance() } } func test_operatorMinusEqual() { (1...N).forEach { _ in let x = CGFloat.random(rangeMin, rangeMax) let y = CGFloat.random(rangeMin, rangeMax) let p1 = CGPoint(x: x, y: y) let dx = CGFloat.random(rangeMin, rangeMax) let dy = CGFloat.random(rangeMin, rangeMax) let v = CGVector(dx: dx, dy: dy) var p2 = p1 p2 -= v expectedPoint = CGPoint(x: p1.x - v.dx, y: p1.y - v.dy) resultedPoint = p2 assertEqualPointsWithinTolerance() } } func test_hashValue() { (1...N).forEach { _ in let x = CGFloat.random(rangeMin, rangeMax) let y = CGFloat.random(rangeMin, rangeMax) let p = CGPoint(x: x, y: y) let expectedHash = "\(x)\(y)".hashValue let resultedHash = p.hashValue XCTAssertEqual(resultedHash, expectedHash) } } }
mit
e7c32269e0a35709087b6e121c2f67a9
30.373832
91
0.541793
4.308265
false
true
false
false
fleurdeswift/data-structure
ExtraDataStructures/POSIX.swift
1
2122
// // POSIX.swift // ExtraDataStructures // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation public typealias DarwinStatStruct = Darwin.stat; public func DarwinStat(url: NSURL, inout _ buf: DarwinStatStruct) throws -> Void { if Darwin.stat(url.fileSystemRepresentation, &buf) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [ NSURLErrorKey: url ]); } } public func DarwinAccess(url: NSURL, _ amode: Int32) throws -> Void { if Darwin.access(url.fileSystemRepresentation, amode) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [ NSURLErrorKey: url ]); } } public func DarwinRename(old old: NSURL, new: NSURL) throws -> Void { if Darwin.rename(old.fileSystemRepresentation, new.fileSystemRepresentation) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [ NSURLErrorKey: [old, new] as NSArray ]); } } public func DarwinOpen(path: NSURL, _ oflags: Int32, _ mode: Darwin.mode_t = 0o755) throws -> Int32 { let fd = Darwin.open(path.fileSystemRepresentation, oflags, mode); if fd == -1 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [ NSURLErrorKey: path ]); } return fd; } public func DarwinRead(fd: Int32, _ buf: UnsafeMutablePointer<Void>, _ nbyte: Int) throws -> Int { let readed = Darwin.read(fd, buf, nbyte); if readed == -1 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil); } return readed; } public func DarwinWrite(fd: Int32, _ buf: UnsafePointer<Void>, _ nbyte: Int) throws -> Int { let written = Darwin.write(fd, buf, nbyte); if written == -1 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil); } return written; } public func DarwinClose(fd: Int32) throws { if Darwin.close(fd) != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil); } }
mit
80d18ca28a1e95e739ecda369ecc9756
28.458333
101
0.63885
3.920518
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/Widgets/TwoLineCell.swift
2
9756
/* 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 UIKit struct TwoLineCellUX { static let ImageSize: CGFloat = 29 static let ImageCornerRadius: CGFloat = 8 static let BorderViewMargin: CGFloat = 16 static let BadgeSize: CGFloat = 16 static let BadgeMargin: CGFloat = 16 static let BorderFrameSize: CGFloat = 32 static let TextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor.Defaults.Grey80 static let DetailTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGray : UIColor.gray static let DetailTextTopMargin: CGFloat = 0 } class TwoLineTableViewCell: UITableViewCell { fileprivate let twoLineHelper = TwoLineCellHelper() let _textLabel = UILabel() let _detailTextLabel = UILabel() // Override the default labels with our own to disable default UITableViewCell label behaviours like dynamic type override var textLabel: UILabel? { return _textLabel } override var detailTextLabel: UILabel? { return _detailTextLabel } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) contentView.addSubview(_textLabel) contentView.addSubview(_detailTextLabel) twoLineHelper.setUpViews(self, textLabel: textLabel!, detailTextLabel: detailTextLabel!, imageView: imageView!) indentationWidth = 0 layoutMargins = .zero separatorInset = UIEdgeInsets(top: 0, left: TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin, bottom: 0, right: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() twoLineHelper.layoutSubviews() } override func prepareForReuse() { super.prepareForReuse() self.textLabel!.alpha = 1 self.imageView!.alpha = 1 self.selectionStyle = .default separatorInset = UIEdgeInsets(top: 0, left: TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin, bottom: 0, right: 0) twoLineHelper.setupDynamicFonts() } // Save background color on UITableViewCell "select" because it disappears in the default behavior override func setHighlighted(_ highlighted: Bool, animated: Bool) { let color = imageView?.backgroundColor super.setHighlighted(highlighted, animated: animated) imageView?.backgroundColor = color } // Save background color on UITableViewCell "select" because it disappears in the default behavior override func setSelected(_ selected: Bool, animated: Bool) { let color = imageView?.backgroundColor super.setSelected(selected, animated: animated) imageView?.backgroundColor = color } func setRightBadge(_ badge: UIImage?) { if let badge = badge { self.accessoryView = UIImageView(image: badge) } else { self.accessoryView = nil } twoLineHelper.hasRightBadge = badge != nil } func setLines(_ text: String?, detailText: String?) { twoLineHelper.setLines(text, detailText: detailText) } func mergeAccessibilityLabels(_ views: [AnyObject?]? = nil) { twoLineHelper.mergeAccessibilityLabels(views) } } class SiteTableViewCell: TwoLineTableViewCell { let borderView = UIView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) twoLineHelper.setUpViews(self, textLabel: textLabel!, detailTextLabel: detailTextLabel!, imageView: imageView!) } override func layoutSubviews() { super.layoutSubviews() twoLineHelper.layoutSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TwoLineHeaderFooterView: UITableViewHeaderFooterView { fileprivate let twoLineHelper = TwoLineCellHelper() // UITableViewHeaderFooterView includes textLabel and detailTextLabel, so we can't override // them. Unfortunately, they're also used in ways that interfere with us just using them: I get // hard crashes in layout if I just use them; it seems there's a battle over adding to the // contentView. So we add our own members, and cover up the other ones. let _textLabel = UILabel() let _detailTextLabel = UILabel() let imageView = UIImageView() // Yes, this is strange. override var textLabel: UILabel? { return _textLabel } // Yes, this is strange. override var detailTextLabel: UILabel? { return _detailTextLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) twoLineHelper.setUpViews(self, textLabel: _textLabel, detailTextLabel: _detailTextLabel, imageView: imageView) contentView.addSubview(_textLabel) contentView.addSubview(_detailTextLabel) contentView.addSubview(imageView) layoutMargins = .zero } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() twoLineHelper.layoutSubviews() } override func prepareForReuse() { super.prepareForReuse() twoLineHelper.setupDynamicFonts() } func mergeAccessibilityLabels(_ views: [AnyObject?]? = nil) { twoLineHelper.mergeAccessibilityLabels(views) } } private class TwoLineCellHelper { weak var container: UIView? var textLabel: UILabel! var detailTextLabel: UILabel! var imageView: UIImageView! var hasRightBadge: Bool = false // TODO: Not ideal. We should figure out a better way to get this initialized. func setUpViews(_ container: UIView, textLabel: UILabel, detailTextLabel: UILabel, imageView: UIImageView) { self.container = container self.textLabel = textLabel self.detailTextLabel = detailTextLabel self.imageView = imageView if let headerView = self.container as? UITableViewHeaderFooterView { headerView.contentView.backgroundColor = UIColor.clear } else { self.container?.backgroundColor = UIColor.clear } textLabel.textColor = TwoLineCellUX.TextColor detailTextLabel.textColor = TwoLineCellUX.DetailTextColor setupDynamicFonts() imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 6 //hmm imageView.layer.masksToBounds = true } func setupDynamicFonts() { textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel detailTextLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS } func layoutSubviews() { guard let container = self.container else { return } let height = container.frame.height let textLeft = TwoLineCellUX.ImageSize + 2 * TwoLineCellUX.BorderViewMargin let textLabelHeight = textLabel.intrinsicContentSize.height let detailTextLabelHeight = detailTextLabel.intrinsicContentSize.height var contentHeight = textLabelHeight if detailTextLabelHeight > 0 { contentHeight += detailTextLabelHeight + TwoLineCellUX.DetailTextTopMargin } let textRightInset: CGFloat = hasRightBadge ? (TwoLineCellUX.BadgeSize + TwoLineCellUX.BadgeMargin) : 0 imageView.frame = CGRect(x: TwoLineCellUX.BorderViewMargin, y: (height - TwoLineCellUX.ImageSize) / 2, width: TwoLineCellUX.ImageSize, height: TwoLineCellUX.ImageSize) textLabel.frame = CGRect(x: textLeft, y: (height - contentHeight) / 2, width: container.frame.width - textLeft - TwoLineCellUX.BorderViewMargin - textRightInset, height: textLabelHeight) detailTextLabel.frame = CGRect(x: textLeft, y: textLabel.frame.maxY + TwoLineCellUX.DetailTextTopMargin, width: container.frame.width - textLeft - TwoLineCellUX.BorderViewMargin - textRightInset, height: detailTextLabelHeight) } func setLines(_ text: String?, detailText: String?) { if text?.isEmpty ?? true { textLabel.text = detailText detailTextLabel.text = nil } else { textLabel.text = text detailTextLabel.text = detailText } } func mergeAccessibilityLabels(_ labels: [AnyObject?]?) { let labels = labels ?? [textLabel, imageView, detailTextLabel] let label = labels.map({ (label: AnyObject?) -> NSAttributedString? in var label = label if let view = label as? UIView { label = view.value(forKey: "accessibilityLabel") as (AnyObject?) } if let attrString = label as? NSAttributedString { return attrString } else if let string = label as? String { return NSAttributedString(string: string) } else { return nil } }).filter({ $0 != nil }).reduce(NSMutableAttributedString(string: ""), { if $0.length > 0 { $0.append(NSAttributedString(string: ", ")) } $0.append($1!) return $0 }) container?.isAccessibilityElement = true container?.setValue(NSAttributedString(attributedString: label), forKey: "accessibilityLabel") } }
mpl-2.0
01f6bb0c359bb0dc358d2d9f42f5cf22
36.095057
175
0.675584
5.384106
false
false
false
false
slightair/syu
Syu/ViewController/ContentListViewController.swift
1
2287
import Cocoa import RxSwift import RxCocoa protocol ContentListViewControllerDelegate: class { func didSelectContent(requestKey: String) } class ContentListViewController: NSViewController, NSTableViewDelegate { @IBOutlet weak var searchField: NSSearchField! @IBOutlet weak var contentListView: NSTableView! weak var delegate: ContentListViewControllerDelegate? var documentation: APIDocumentation! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setUpSubscriptions() } private func setUpSubscriptions() { contentListView.rx.setDelegate(self) .addDisposableTo(disposeBag) searchField.rx.text.throttle(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged { lhs, rhs in lhs == rhs } .flatMapLatest { keyword -> Observable<[SearchIndex]> in guard let keyword = keyword, !keyword.isEmpty else { return .just([]) } return self.documentation.search(keyword: keyword).catchErrorJustReturn([]) } .observeOn(MainScheduler.instance) .bindTo(contentListView.rx.items) .addDisposableTo(disposeBag) } // MARK: NSTableViewDelegate func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let view = contentListView.make(withIdentifier: "ContentCell", owner: self) as? NSTableCellView guard let index = tableView.dataSource?.tableView!(tableView, objectValueFor: tableColumn, row: row) as? SearchIndex else { return nil } if let textField = view?.textField { textField.stringValue = "\(index.type): \(index.name)" textField.sizeToFit() } return view } func tableViewSelectionDidChange(_ notification: Notification) { if let tableView = notification.object as? NSTableView { guard let index = tableView.dataSource?.tableView!(tableView, objectValueFor: nil, row: tableView.selectedRow) as? SearchIndex else { return } delegate?.didSelectContent(requestKey: index.requestKey) } } }
mit
ede456f64b18d3b0afb03b59987c692d
33.134328
145
0.646261
5.550971
false
false
false
false
shahmishal/swift
test/SILOptimizer/di_property_wrappers.swift
1
7972
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test @propertyWrapper struct Wrapper<T> { var wrappedValue: T { didSet { print(" .. set \(wrappedValue)") } } init(wrappedValue initialValue: T) { print(" .. init \(initialValue)") self.wrappedValue = initialValue } } protocol IntInitializable { init(_: Int) } final class Payload : CustomStringConvertible, IntInitializable { let payload: Int init(_ p: Int) { self.payload = p print(" + payload alloc \(payload)") } deinit { print(" - payload free \(payload)") } var description: String { return "value = \(payload)" } } struct IntStruct { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } } final class IntClass { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } } struct RefStruct { @Wrapper var wrapped: Payload init() { wrapped = Payload(42) wrapped = Payload(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: Payload(32)) } else { wrapped = Payload(42) } } init(dynamic b: Bool) { if b { wrapped = Payload(42) } wrapped = Payload(27) } } final class GenericClass<T : IntInitializable> { @Wrapper var wrapped: T init() { wrapped = T(42) wrapped = T(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: T(32)) } else { wrapped = T(42) } } init(dynamic b: Bool) { if b { wrapped = T(42) } wrapped = T(27) } } func testIntStruct() { // CHECK: ## IntStruct print("\n## IntStruct") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 let t1 = IntStruct() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntStruct(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntStruct(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntStruct(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntStruct(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) } func testIntClass() { // CHECK: ## IntClass print("\n## IntClass") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 let t1 = IntClass() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntClass(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntClass(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntClass(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntClass(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) } func testRefStruct() { // CHECK: ## RefStruct print("\n## RefStruct") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. set value = 27 // CHECK-NEXT: - payload free 42 let t1 = RefStruct() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = RefStruct(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = RefStruct(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = RefStruct(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = RefStruct(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } func testGenericClass() { // CHECK: ## GenericClass print("\n## GenericClass") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. set value = 27 // CHECK-NEXT: - payload free 42 let t1 = GenericClass<Payload>() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = GenericClass<Payload>(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = GenericClass<Payload>(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = GenericClass<Payload>(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = GenericClass<Payload>(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } @propertyWrapper struct WrapperWithDefaultInit<Value> { private var _value: Value? = nil init() { print("default init called on \(Value.self)") } var wrappedValue: Value { get { return _value! } set { print("set value \(newValue)") _value = newValue } } } struct UseWrapperWithDefaultInit { @WrapperWithDefaultInit<Int> var x: Int @WrapperWithDefaultInit<String> var y: String init(y: String) { self.y = y } } func testDefaultInit() { // CHECK: ## DefaultInit print("\n## DefaultInit") let use = UseWrapperWithDefaultInit(y: "hello") // CHECK: default init called on Int // FIXME: DI should eliminate the following call // CHECK: default init called on String // CHECK: set value hello } // rdar://problem/51581937: DI crash with a property wrapper of an optional struct OptIntStruct { @Wrapper var wrapped: Int? init() { wrapped = 42 } } func testOptIntStruct() { // CHECK: ## OptIntStruct print("\n## OptIntStruct") let use = OptIntStruct() // CHECK-NEXT: .. init nil // CHECK-NEXT: .. set Optional(42) } // rdar://problem/53504653 struct DefaultNilOptIntStruct { @Wrapper var wrapped: Int? init() { } } func testDefaultNilOptIntStruct() { // CHECK: ## DefaultNilOptIntStruct print("\n## DefaultNilOptIntStruct") let use = DefaultNilOptIntStruct() // CHECK-NEXT: .. init nil } testIntStruct() testIntClass() testRefStruct() testGenericClass() testDefaultInit() testOptIntStruct() testDefaultNilOptIntStruct()
apache-2.0
3911703ee17bc25a7bc10a58238a34c2
19.493573
75
0.585173
3.469104
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift
2
5817
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public final class MD5: DigestType { static let blockSize: Int = 64 static let digestLength: Int = 16 // 128 / 8 fileprivate static let hashInitialValue: Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash: Array<UInt32> = MD5.hashInitialValue /** specifies the per-round shift amounts */ private let s: Array<UInt32> = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ] /** binary integer part of the sines of integers (Radians) */ private let k: Array<UInt32> = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ] public init() { } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { fatalError() } } // mutating currentHash in place is way faster than returning new result fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout Array<UInt32>) { assert(chunk.count == 16 * 4) // Initialize hash value for this chunk: var A: UInt32 = currentHash[0] var B: UInt32 = currentHash[1] var C: UInt32 = currentHash[2] var D: UInt32 = currentHash[3] var dTemp: UInt32 = 0 // Main loop for j in 0..<self.k.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 default: break } dTemp = D D = C C = B // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 and get M[g] value let gAdvanced = g << 2 var Mg = UInt32(chunk[chunk.startIndex &+ gAdvanced]) Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 1]) << 8 Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 2]) << 16 Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 3]) << 24 B = B &+ rotateLeft(A &+ F &+ self.k[j] &+ Mg, by: self.s[j]) A = dTemp } currentHash[0] = currentHash[0] &+ A currentHash[1] = currentHash[1] &+ B currentHash[2] = currentHash[2] &+ C currentHash[3] = currentHash[3] &+ D } } extension MD5: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { self.accumulated += bytes if isLast { let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b // Step 1. Append padding bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) // Step 2. Append Length a 64-bit representation of lengthInBits self.accumulated += lengthBytes.reversed() } var processedBytes = 0 for chunk in self.accumulated.batched(by: MD5.blockSize) { if isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize { self.process(block: chunk, currentHash: &self.accumulatedHash) processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) self.processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>() result.reserveCapacity(MD5.digestLength) for hElement in self.accumulatedHash { let hLE = hElement.littleEndian result += Array<UInt8>(arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)) } // reset hash value for instance if isLast { self.accumulatedHash = MD5.hashInitialValue } return result } }
mit
b74dcc719c6a86bd99e7279aabf1bb60
35.099379
217
0.646593
3.19692
false
false
false
false
achimk/Cars
CarsApp/Infrastructure/Cars/RestService/Tasks/BaseCarsTask.swift
1
1136
// // BaseCarsTask.swift // CarsApp // // Created by Joachim Kret on 01/08/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation import RxSwift class BaseCarsTask<I, O>: NetworkTask<I, O> { let endpointBuilder: RestCarsEndpointBuilderType init(dispatcher: NetworkDispatcherType, endpointBuilder: RestCarsEndpointBuilderType) { self.endpointBuilder = endpointBuilder super.init(dispatcher: dispatcher) } func createRequest( endpoint: RestCarsEndpoint, completion: ((BaseCarsRequest) -> Void)? = nil) -> Observable<NetworkRequestType> { let builder = endpointBuilder return Observable.create({ (observer: AnyObserver<NetworkRequestType>) -> Disposable in do { let url = try builder.create(endpoint) let request = BaseCarsRequest(url: url) completion?(request) observer.onNext(request) observer.onCompleted() } catch { observer.onError(error) } return Disposables.create() }) } }
mit
7f0a73520189d0d93153208badbd894d
28.102564
95
0.622026
4.729167
false
false
false
false
stockx/BubbleRankingIndicator
Source/BubbleRankView.swift
1
3995
// // BubbleRankView.swift // BubbleRankingIndicator // // Created by Sklar, Josh on 10/5/16. // Copyright © 2016 Sklar. All rights reserved. // import UIKit // Libs import SnapKit import Haneke class BubbleRankView: UIView { struct State { var rank: Rank var isActive: Bool var hasAchievedRank: Bool var outerRingColor: UIColor? var backgroundColor: UIColor var rankNameFont: UIFont var rankNameColor: UIColor /// Whether or not the rank level label is hidden. /// Defaults to false. var rankLevelLabelIsHidden: Bool } var state: State? { didSet { update() } } /** The label used to display the level name. */ fileprivate let label = UILabel() /** The inner subview. This view is slightly smaller than `self`, and is what is used to display the content of othe level (name and background image). */ fileprivate let contentView = UIView() /** The imageview to display the background image of the rank. */ fileprivate let imageView = UIImageView() /** The padding value between the contentView and its superview. In other words, the size of the outer ring. */ fileprivate let padding: CGFloat = 2.5 convenience init(state: State) { self.init(frame: CGRect.zero) self.state = state update() } override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFit contentView.addSubview(imageView) label.clipsToBounds = true label.textAlignment = .center contentView.addSubview(label) addSubview(contentView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented. Use init(state:).") } fileprivate func update() { guard let state = state else { return } label.text = state.rank.name self.backgroundColor = state.outerRingColor self.contentView.backgroundColor = state.backgroundColor if let imageURLString = state.rank.backgroundImageName, let imageURL = URL(string: imageURLString) { self.imageView.hnk_setImageFromURL(imageURL, placeholder: nil, format: Format<UIImage>(name: "RankImages"), failure: { (error) in print("Failed fetching rank image from URL \(imageURL). Error: \(error)") }, success: { (image) in self.imageView.image = image }) } imageView.isHidden = !state.hasAchievedRank if state.hasAchievedRank && !state.isActive { label.backgroundColor = UIColor.black.withAlphaComponent(0.25) } else { label.backgroundColor = .clear } label.isHidden = state.rankLevelLabelIsHidden label.font = state.rankNameFont label.textColor = state.rankNameColor } // MARK: View override func layoutSubviews() { super.layoutSubviews() makeCircular() contentView.makeCircular() } override func updateConstraints() { contentView.snp.remakeConstraints { make in make.edges.equalToSuperview().inset(self.padding) } imageView.snp.remakeConstraints { (make) in make.edges.equalToSuperview() } label.snp.remakeConstraints { make in make.edges.equalToSuperview() } super.updateConstraints() } }
mit
00b7113640313c180517b176ff3f0a93
27.126761
121
0.5666
5.269129
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/FeedProvider/Reddit/RedditFeedProvider.swift
1
14127
// // RedditFeedProvider.swift // Account // // Created by Maurice Parker on 5/2/20. // Copyright © 2020 Ranchero Software, LLC. All rights reserved. // import Foundation import os.log import OAuthSwift import Secrets import RSCore import RSParser import RSWeb public enum RedditFeedProviderError: LocalizedError { case rateLimitExceeded case accessFailure(Error) case unknown public var errorDescription: String? { switch self { case .rateLimitExceeded: return NSLocalizedString("Reddit API rate limit has been exceeded. Please wait a short time and try again.", comment: "Rate Limit") case .accessFailure(let error): return NSLocalizedString("An attempt to access your Reddit feed(s) failed.\n\nIf this problem persists, please deactivate and reactivate the Reddit extension to fix this problem.\n\n\(error.localizedDescription)", comment: "Reddit Access") case .unknown: return NSLocalizedString("A Reddit Feed Provider error has occurred.", comment: "Unknown error") } } } public enum RedditFeedType: Int { case home = 0 case popular = 1 case all = 2 case subreddit = 3 } public final class RedditFeedProvider: FeedProvider, RedditFeedProviderTokenRefreshOperationDelegate { var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "RedditFeedProvider") private static let homeURL = "https://www.reddit.com" private static let server = "www.reddit.com" private static let apiBase = "https://oauth.reddit.com" private static let userAgentHeaders = UserAgent.headers() as! [String: String] private static let pseudoSubreddits = [ "popular": NSLocalizedString("Popular", comment: "Popular"), "all": NSLocalizedString("All", comment: "All") ] private let operationQueue = MainThreadOperationQueue() private var parsingQueue = DispatchQueue(label: "RedditFeedProvider parse queue") public var username: String? var oauthTokenLastRefresh: Date? var oauthToken: String var oauthRefreshToken: String var oauthSwift: OAuth2Swift? private var client: OAuthSwiftClient? { return oauthSwift?.client } private var rateLimitRemaining: Int? private var rateLimitReset: Date? public convenience init?(username: String) { guard let tokenCredentials = try? CredentialsManager.retrieveCredentials(type: .oauthAccessToken, server: Self.server, username: username), let refreshTokenCredentials = try? CredentialsManager.retrieveCredentials(type: .oauthRefreshToken, server: Self.server, username: username) else { return nil } self.init(oauthToken: tokenCredentials.secret, oauthRefreshToken: refreshTokenCredentials.secret) self.username = username } init(oauthToken: String, oauthRefreshToken: String) { self.oauthToken = oauthToken self.oauthRefreshToken = oauthRefreshToken oauthSwift = Self.oauth2Swift oauthSwift!.client.credential.oauthToken = oauthToken oauthSwift!.client.credential.oauthRefreshToken = oauthRefreshToken } public func ability(_ urlComponents: URLComponents) -> FeedProviderAbility { guard urlComponents.host?.hasSuffix("reddit.com") ?? false else { return .none } if let username = urlComponents.user { if username == username { return .owner } else { return .none } } return .available } public func iconURL(_ urlComponents: URLComponents, completion: @escaping (Result<String, Error>) -> Void) { guard urlComponents.path.hasPrefix("/r/") else { completion(.failure(RedditFeedProviderError.unknown)) return } subreddit(urlComponents) { result in switch result { case .success(let subreddit): if let iconURL = subreddit.data?.iconURL, !iconURL.isEmpty { completion(.success(iconURL)) } else { completion(.failure(RedditFeedProviderError.unknown)) } case .failure(let error): completion(.failure(error)) } } } public func metaData(_ urlComponents: URLComponents, completion: @escaping (Result<FeedProviderFeedMetaData, Error>) -> Void) { let path = urlComponents.path // Reddit Home let splitPath = path.split(separator: "/") if path == "" || path == "/" || (splitPath.count == 1 && RedditSort(rawValue: String(splitPath[0])) != nil) { let name = NSLocalizedString("Reddit Home", comment: "Reddit Home") let metaData = FeedProviderFeedMetaData(name: name, homePageURL: Self.homeURL) completion(.success(metaData)) return } // Subreddits guard splitPath.count > 1, splitPath.count < 4, splitPath[0] == "r" else { completion(.failure(RedditFeedProviderError.unknown)) return } if splitPath.count == 3 && RedditSort(rawValue: String(splitPath[2])) == nil { completion(.failure(RedditFeedProviderError.unknown)) return } let homePageURL = "https://www.reddit.com/\(splitPath[0])/\(splitPath[1])" // Reddit Popular, Reddit All, etc... if let subredditName = Self.pseudoSubreddits[String(splitPath[1])] { let localized = NSLocalizedString("Reddit %@", comment: "Reddit") let name = NSString.localizedStringWithFormat(localized as NSString, subredditName) as String let metaData = FeedProviderFeedMetaData(name: name, homePageURL: homePageURL) completion(.success(metaData)) return } subreddit(urlComponents) { result in switch result { case .success(let subreddit): if let displayName = subreddit.data?.displayName { completion(.success(FeedProviderFeedMetaData(name: displayName, homePageURL: homePageURL))) } else { completion(.failure(RedditFeedProviderError.unknown)) } case .failure(let error): completion(.failure(error)) } } } public func refresh(_ webFeed: WebFeed, completion: @escaping (Result<Set<ParsedItem>, Error>) -> Void) { guard let urlComponents = URLComponents(string: webFeed.url) else { completion(.failure(RedditFeedProviderError.unknown)) return } let api: String if urlComponents.path.isEmpty { api = "/.json" } else { api = "\(urlComponents.path).json" } let splitPath = urlComponents.path.split(separator: "/") let identifySubreddit: Bool if splitPath.count > 1 { if Self.pseudoSubreddits.keys.contains(String(splitPath[1])) { identifySubreddit = true } else { identifySubreddit = !urlComponents.path.hasPrefix("/r/") } } else { identifySubreddit = true } fetch(api: api, parameters: [:], resultType: RedditLinkListing.self) { result in switch result { case .success(let linkListing): self.parsingQueue.async { let parsedItems = self.makeParsedItems(webFeed.url, identifySubreddit, linkListing) DispatchQueue.main.async { completion(.success(parsedItems)) } } case .failure(let error): if (error as? OAuthSwiftError)?.errorCode == -11 { completion(.success(Set<ParsedItem>())) } else { completion(.failure(RedditFeedProviderError.accessFailure(error))) } } } } public static func create(tokenSuccess: OAuthSwift.TokenSuccess, completion: @escaping (Result<RedditFeedProvider, Error>) -> Void) { let oauthToken = tokenSuccess.credential.oauthToken let oauthRefreshToken = tokenSuccess.credential.oauthRefreshToken let redditFeedProvider = RedditFeedProvider(oauthToken: oauthToken, oauthRefreshToken: oauthRefreshToken) redditFeedProvider.fetch(api: "/api/v1/me", resultType: RedditMe.self) { result in switch result { case .success(let user): guard let username = user.name else { completion(.failure(RedditFeedProviderError.unknown)) return } do { redditFeedProvider.username = username try storeCredentials(username: username, oauthToken: oauthToken, oauthRefreshToken: oauthRefreshToken) completion(.success(redditFeedProvider)) } catch { completion(.failure(error)) } case .failure(let error): completion(.failure(error)) } } } public static func buildURL(_ type: RedditFeedType, username: String?, subreddit: String?, sort: RedditSort) -> URL? { var components = URLComponents() components.scheme = "https" components.host = "www.reddit.com" switch type { case .home: guard let username = username else { return nil } components.user = username components.path = "/\(sort.rawValue)" case .popular: components.path = "/r/popular/\(sort.rawValue)" case .all: components.path = "/r/all/\(sort.rawValue)" case .subreddit: guard let subreddit = subreddit else { return nil } components.path = "/r/\(subreddit)/\(sort.rawValue)" } return components.url } static func storeCredentials(username: String, oauthToken: String, oauthRefreshToken: String) throws { let tokenCredentials = Credentials(type: .oauthAccessToken, username: username, secret: oauthToken) try CredentialsManager.storeCredentials(tokenCredentials, server: Self.server) let tokenSecretCredentials = Credentials(type: .oauthRefreshToken, username: username, secret: oauthRefreshToken) try CredentialsManager.storeCredentials(tokenSecretCredentials, server: Self.server) } } // MARK: OAuth1SwiftProvider extension RedditFeedProvider: OAuth2SwiftProvider { public static var oauth2Swift: OAuth2Swift { let oauth2 = OAuth2Swift(consumerKey: SecretsManager.provider.redditConsumerKey, consumerSecret: "", authorizeUrl: "https://www.reddit.com/api/v1/authorize.compact?", accessTokenUrl: "https://www.reddit.com/api/v1/access_token", responseType: "code") oauth2.accessTokenBasicAuthentification = true return oauth2 } public static var callbackURL: URL { return URL(string: "netnewswire://success")! } public static var oauth2Vars: (state: String, scope: String, params: [String : String]) { let state = generateState(withLength: 20) let scope = "identity mysubreddits read" let params = [ "duration" : "permanent", ] return (state: state, scope: scope, params: params) } } private extension RedditFeedProvider { func subreddit(_ urlComponents: URLComponents, completion: @escaping (Result<RedditSubreddit, Error>) -> Void) { let splitPath = urlComponents.path.split(separator: "/") guard splitPath.count > 1 else { completion(.failure(RedditFeedProviderError.unknown)) return } let secondElement = String(splitPath[1]) let api = "/r/\(secondElement)/about.json" fetch(api: api, parameters: [:], resultType: RedditSubreddit.self, completion: completion) } func fetch<R: Decodable>(api: String, parameters: [String: Any] = [:], resultType: R.Type, completion: @escaping (Result<R, Error>) -> Void) { guard let client = client else { completion(.failure(RedditFeedProviderError.unknown)) return } if let remaining = rateLimitRemaining, let reset = rateLimitReset, remaining < 1 && reset > Date() { completion(.failure(RedditFeedProviderError.rateLimitExceeded)) return } let url = "\(Self.apiBase)\(api)" var expandedParameters = parameters expandedParameters["raw_json"] = "1" client.get(url, parameters: expandedParameters, headers: Self.userAgentHeaders) { result in switch result { case .success(let response): if let remaining = response.response.value(forHTTPHeaderField: "X-Ratelimit-Remaining") { self.rateLimitRemaining = Int(remaining) } else { self.rateLimitRemaining = nil } if let reset = response.response.value(forHTTPHeaderField: "X-Ratelimit-Reset") { self.rateLimitReset = Date(timeIntervalSinceNow: Double(reset) ?? 0) } else { self.rateLimitReset = nil } self.parsingQueue.async { let decoder = JSONDecoder() do { let result = try decoder.decode(resultType, from: response.data) DispatchQueue.main.async { completion(.success(result)) } } catch { DispatchQueue.main.async { completion(.failure(error)) } } } case .failure(let oathError): self.handleFailure(error: oathError) { error in if let error = error { completion(.failure(error)) } else { self.fetch(api: api, parameters: parameters, resultType: resultType, completion: completion) } } } } } func makeParsedItems(_ webFeedURL: String,_ identifySubreddit: Bool, _ linkListing: RedditLinkListing) -> Set<ParsedItem> { var parsedItems = Set<ParsedItem>() guard let linkDatas = linkListing.data?.children?.compactMap({ $0.data }), !linkDatas.isEmpty else { return parsedItems } for linkData in linkDatas { guard let permalink = linkData.permalink else { continue } let parsedItem = ParsedItem(syncServiceID: nil, uniqueID: permalink, feedURL: webFeedURL, url: "https://www.reddit.com\(permalink)", externalURL: linkData.url, title: linkData.title, language: nil, contentHTML: linkData.renderAsHTML(identifySubreddit: identifySubreddit), contentText: linkData.selfText, summary: nil, imageURL: nil, bannerImageURL: nil, datePublished: linkData.createdDate, dateModified: nil, authors: makeParsedAuthors(linkData.author), tags: nil, attachments: nil) parsedItems.insert(parsedItem) } return parsedItems } func makeParsedAuthors(_ username: String?) -> Set<ParsedAuthor>? { guard let username = username else { return nil } var urlComponents = URLComponents(string: "https://www.reddit.com") urlComponents?.path = "/u/\(username)" let userURL = urlComponents?.url?.absoluteString return Set([ParsedAuthor(name: "u/\(username)", url: userURL, avatarURL: nil, emailAddress: nil)]) } func handleFailure(error: OAuthSwiftError, completion: @escaping (Error?) -> Void) { if case .tokenExpired = error { let op = RedditFeedProviderTokenRefreshOperation(delegate: self) op.completionBlock = { operation in let refreshOperation = operation as! RedditFeedProviderTokenRefreshOperation if let error = refreshOperation.error { completion(error) } else { completion(nil) } } operationQueue.add(op) } else { completion(error) } } }
mit
b9bfbfa7129a27eee3363e145df8761f
30.74382
242
0.707419
4.049885
false
false
false
false
ShinChven/DatePickerDialog-iOS-Swift
Demo/PickerDialog/DatePickerDialog.swift
1
12242
import UIKit import QuartzCore class DatePickerDialog: UIView { /* Consts */ private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50 private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1 private let kDatePickerDialogCornerRadius: CGFloat = 7 private let kDatePickerDialogCancelButtonTag: Int = 1 private let kDatePickerDialogDoneButtonTag: Int = 2 /* Views */ private var dialogView: UIView! private var titleLabel: UILabel! private var datePicker: UIDatePicker! private var cancelButton: UIButton! private var doneButton: UIButton! /* Vars */ private var title: String! private var doneButtonTitle: String! private var cancelButtonTitle: String! private var defaultDate: NSDate! private var datePickerMode: UIDatePickerMode! private var callback: ((date: NSDate) -> Void)! /* Overrides */ override init() { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* Handle device orientation changes */ func deviceOrientationDidChange(notification: NSNotification) { /* TODO */ } /* Create the dialog view, and animate opening the dialog */ func show(#title: String, datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { show(title: title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback) } func show(#title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) { self.title = title self.doneButtonTitle = doneButtonTitle self.cancelButtonTitle = cancelButtonTitle self.datePickerMode = datePickerMode self.callback = callback self.defaultDate = defaultDate self.dialogView = createContainerView() self.dialogView!.layer.shouldRasterize = true self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(self.dialogView!) /* Attached to the top most window (make sure we are using the right orientation) */ let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation switch(interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: let t: Double = M_PI * 270 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.LandscapeRight: let t: Double = M_PI * 90 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break case UIInterfaceOrientation.PortraitUpsideDown: let t: Double = M_PI * 180 / 180 self.transform = CGAffineTransformMakeRotation(CGFloat(t)) break default: break } self.frame = CGRectMake(0, 0, self.frame.width, self.frame.size.height) UIApplication.sharedApplication().windows.first!.addSubview(self) /* Anim */ UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } /* Dialog close animation then cleaning and removing the view from the parent */ private func close() { let currentTransform = self.dialogView.layer.transform let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber)? as? Double ?? 0.0 let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0) self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1)) self.dialogView.layer.opacity = 1 UIView.animateWithDuration( 0.2, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1)) self.dialogView.layer.opacity = 0 }) { (finished: Bool) -> Void in for v in self.subviews { v.removeFromSuperview() } self.removeFromSuperview() } } /* Creates the container view here: create the dialog, then add the custom content and buttons */ private func createContainerView() -> UIView { let screenSize = countScreenSize() let dialogSize = CGSizeMake( 300, 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight) // For the black background self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height) // This is the dialog's container; we attach the custom content and the buttons to this one let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height)) // First, we style the dialog to match the iOS8 UIAlertView >>> let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer) gradient.frame = dialogContainer.bounds gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor, UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor, UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor] let cornerRadius = kDatePickerDialogCornerRadius gradient.cornerRadius = cornerRadius dialogContainer.layer.insertSublayer(gradient, atIndex: 0) dialogContainer.layer.cornerRadius = cornerRadius dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = cornerRadius + 5 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2) dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath // There is a line above the button let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // ˆˆˆ //Title self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30)) self.titleLabel.textAlignment = NSTextAlignment.Center self.titleLabel.font = UIFont.boldSystemFontOfSize(17) self.titleLabel.text = self.title dialogContainer.addSubview(self.titleLabel) self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0)) self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin self.datePicker.frame.size.width = 300 self.datePicker.datePickerMode = self.datePickerMode self.datePicker.date = self.defaultDate dialogContainer.addSubview(self.datePicker) // Add the buttons addButtonsToView(dialogContainer) return dialogContainer } /* Add buttons to container */ private func addButtonsToView(container: UIView) { let buttonWidth = container.bounds.size.width / 2 self.cancelButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton self.cancelButton.frame = CGRectMake( 0, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.cancelButton.tag = kDatePickerDialogCancelButtonTag self.cancelButton.setTitle(self.cancelButtonTitle, forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.cancelButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.cancelButton) self.doneButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton self.doneButton.frame = CGRectMake( buttonWidth, container.bounds.size.height - kDatePickerDialogDefaultButtonHeight, buttonWidth, kDatePickerDialogDefaultButtonHeight ) self.doneButton.tag = kDatePickerDialogDoneButtonTag self.doneButton.setTitle(self.doneButtonTitle, forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14) self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) container.addSubview(self.doneButton) } func buttonTapped(sender: UIButton!) { if sender.tag == kDatePickerDialogDoneButtonTag { self.callback(date: self.datePicker.date) } else if sender.tag == kDatePickerDialogCancelButtonTag { //There's nothing do to here \o\ } close() } /* Helper function: count and return the screen's size */ func countScreenSize() -> CGSize { var screenWidth = UIScreen.mainScreen().bounds.size.width var screenHeight = UIScreen.mainScreen().bounds.size.height let interfaceOrientaion = UIApplication.sharedApplication().statusBarOrientation if UIInterfaceOrientationIsLandscape(interfaceOrientaion) { let tmp = screenWidth screenWidth = screenHeight screenHeight = tmp } return CGSizeMake(screenWidth, screenHeight) } }
mit
c8f20f3254b6db09ad6a8e083bc076c5
45.539924
250
0.654057
5.394006
false
false
false
false
WaterReporter/WaterReporter-iOS
WaterReporter/WaterReporter/_OLDProfileTableViewController.swift
1
9852
// // ProfileTableViewController.swift // WaterReporter // // Created by Viable Industries on 7/24/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import SwiftyJSON import UIKit class OLDProfileTableViewController: UITableViewController { @IBOutlet var profileHeaderView: UIView! @IBOutlet weak var buttonUserProfileOrganization: UIButton! @IBOutlet weak var buttonUserProfileSubmissions: UIButton! @IBOutlet weak var buttonUserProfileActions: UIButton! @IBOutlet var indicatorLoadingView: UIView! @IBOutlet weak var profileUserDescription: UILabel! @IBOutlet weak var profileUserImage: UIImageView! @IBOutlet weak var profileUserName: UILabel! @IBOutlet weak var profileUserTitleOrganization: UILabel! @IBOutlet weak var profileUserOrganizationName: UILabel! // // Controller-wide // var userProfile: JSON? var loadingView: UIView! override func viewDidLoad() { super.viewDidLoad() NSLog("ProfileViewController::viewDidLoad") // // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up // self.view.setNeedsLayout() self.view.layoutIfNeeded() // // Show the loading indicator while the profile loads // self.loading() // // Set the Navigation Bar title // self.navigationItem.title = "Profile" // // Restyle the form Log In Navigation button to appear with an underline // let border = CALayer() let buttonWidth = self.buttonUserProfileSubmissions.frame.width let buttonHeight = self.buttonUserProfileSubmissions.frame.size.height border.borderColor = CGColor.colorBrand() border.borderWidth = 2.0 border.frame = CGRectMake(0, self.buttonUserProfileSubmissions.frame.size.height - 2.0, buttonWidth, buttonHeight) self.buttonUserProfileSubmissions.layer.addSublayer(border) self.buttonUserProfileSubmissions.layer.masksToBounds = true // // // let _userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID")?.string if (_userId != "") { self.attemptLoadUserProfile() } else { self.attemptRetrieveUserID() } // // Setup Tap Gesture Recognizers so that we can toggle the // number of lines for user profile labels // self.profileUserTitleOrganization.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ProfileTableViewController.toggleUILableNumberOfLines(_:)))) self.profileUserDescription.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ProfileTableViewController.toggleUILableNumberOfLines(_:)))) self.profileUserOrganizationName.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ProfileTableViewController.toggleUILableNumberOfLines(_:)))) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) tableView.sectionHeaderHeight = UITableViewAutomaticDimension tableView.estimatedSectionHeaderHeight = 200.0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // // MARK: // override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView: UIView = self.profileHeaderView switch section { default: return headerView } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 200.0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UserProfileTableViewCell", forIndexPath: indexPath) return cell } // // MARK: Server Request/Response functionality // func loading() { // // Create a view that covers the entire screen // self.loadingView = self.indicatorLoadingView self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) self.view.addSubview(self.loadingView) self.view.bringSubviewToFront(self.loadingView) // // // self.profileHeaderView.hidden = true } func loadingComplete() { self.loadingView.removeFromSuperview() self.profileHeaderView.hidden = false } func attemptLoadUserProfile() { print("attemptLoadUserProfile") let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] if let _userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") { let revisedEndpoint = Endpoints.GET_USER_PROFILE + String(_userId) Alamofire.request(.GET, revisedEndpoint, headers: headers, encoding: .JSON).responseJSON { response in if let value = response.result.value { self.userProfile = JSON(value) print("self.userProfile \(self.userProfile)") self.attemptDisplayUserProfile() } } } } func attemptRetrieveUserID() { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): let json = JSON(value) if let data: AnyObject = json.rawValue { NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID") self.attemptLoadUserProfile() } case .Failure(let error): print(error) } } } func attemptDisplayUserProfile() { // // Display User's First and Last Name // if let _userFirstName = self.userProfile!["properties"]["first_name"].string, let _userLastName = self.userProfile!["properties"]["last_name"].string { self.profileUserName.text = _userFirstName + " " + _userLastName } // // Display User's Title and/or Organization Name // if let _userTitle = self.userProfile!["properties"]["title"].string, let _userOrganization = self.userProfile!["properties"]["organization_name"].string { self.profileUserTitleOrganization.text = _userTitle self.profileUserOrganizationName.text = "at " + _userOrganization } else if let _userOrganization = self.userProfile!["properties"]["organization_name"].string { self.profileUserOrganizationName.text = _userOrganization } else if let _userTitle = self.userProfile!["properties"]["title"].string { self.profileUserTitleOrganization.text = _userTitle } // // // if let _userDescription = self.userProfile!["properties"]["description"].string { self.profileUserDescription.text = _userDescription } // // Display User's Profile Image // var profileUserImageUrl:NSURL! = NSURL(string: "https://www.waterreporter.org/images/badget--MissingUser.png") if let thisProfileUserImageURL = self.userProfile!["properties"]["picture"].string { profileUserImageUrl = NSURL(string: String(thisProfileUserImageURL)) } self.profileUserImage.kf_indicatorType = .Activity self.profileUserImage.kf_showIndicatorWhenLoading = true self.profileUserImage.kf_setImageWithURL(profileUserImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in self.profileUserImage.image = image self.profileUserImage.layer.cornerRadius = 32.0 self.profileUserImage.clipsToBounds = true self.loadingComplete() }) // // // } @IBAction func toggleUILableNumberOfLines(sender: UITapGestureRecognizer) { let field: UILabel = sender.view as! UILabel var numberOfLines: Int = field.numberOfLines switch field.numberOfLines { case 0: if sender.view?.restorationIdentifier == "profileUserDescription" { numberOfLines = 3 } else { numberOfLines = 1 } break default: numberOfLines = 0 break } field.numberOfLines = numberOfLines } }
agpl-3.0
429f020ab160330dca2a795965d4570d
32.852234
178
0.60268
5.828994
false
false
false
false
vmanot/swift-package-manager
Sources/Commands/Destination.swift
1
7208
import Basic import Utility import POSIX enum DestinationError: Swift.Error { /// Couldn't find the Xcode installation. case invalidInstallation(String) /// The schema version is invalid. case invalidSchemaVersion } extension DestinationError: CustomStringConvertible { var description: String { switch self { case .invalidSchemaVersion: return "unsupported destination file schema version" case .invalidInstallation(let problem): return problem } } } /// The compilation destination, has information about everything that's required for a certain destination. public struct Destination { /// The clang/LLVM triple describing the target OS and architecture. /// /// The triple has the general format <arch><sub>-<vendor>-<sys>-<abi>, where: /// - arch = x86_64, i386, arm, thumb, mips, etc. /// - sub = for ex. on ARM: v5, v6m, v7a, v7m, etc. /// - vendor = pc, apple, nvidia, ibm, etc. /// - sys = none, linux, win32, darwin, cuda, etc. /// - abi = eabi, gnu, android, macho, elf, etc. /// /// for more information see //https://clang.llvm.org/docs/CrossCompilation.html public let target: String /// The SDK used to compile for the destination. public let sdk: AbsolutePath /// The binDir in the containing the compilers/linker to be used for the compilation. public let binDir: AbsolutePath /// The file extension for dynamic libraries (eg. `.so` or `.dylib`) public let dynamicLibraryExtension: String /// Additional flags to be passed to the C compiler. public let extraCCFlags: [String] /// Additional flags to be passed to the Swift compiler. public let extraSwiftCFlags: [String] /// Additional flags to be passed when compiling with C++. public let extraCPPFlags: [String] /// Returns the bin directory for the host. /// /// - Parameter originalWorkingDirectory: The working directory when the program was launched. private static func hostBinDir( originalWorkingDirectory: AbsolutePath = currentWorkingDirectory ) -> AbsolutePath { #if Xcode // For Xcode, set bin directory to the build directory containing the fake // toolchain created during bootstraping. This is obviously not production ready // and only exists as a development utility right now. // // This also means that we should have bootstrapped with the same Swift toolchain // we're using inside Xcode otherwise we will not be able to load the runtime libraries. // // FIXME: We may want to allow overriding this using an env variable but that // doesn't seem urgent or extremely useful as of now. return AbsolutePath(#file).parentDirectory .parentDirectory.parentDirectory.appending(components: ".build", hostTargetTriple, "debug") #else return AbsolutePath( CommandLine.arguments[0], relativeTo: originalWorkingDirectory).parentDirectory #endif } /// The destination describing the host OS. public static func hostDestination( _ binDir: AbsolutePath? = nil, originalWorkingDirectory: AbsolutePath = currentWorkingDirectory ) throws -> Destination { // Select the correct binDir. let binDir = binDir ?? Destination.hostBinDir( originalWorkingDirectory: originalWorkingDirectory) #if os(macOS) // Get the SDK. let sdkPath: AbsolutePath if let value = lookupExecutablePath(filename: getenv("SYSROOT")) { sdkPath = value } else { // No value in env, so search for it. let sdkPathStr = try Process.checkNonZeroExit( args: "xcrun", "--sdk", "macosx", "--show-sdk-path").chomp() guard !sdkPathStr.isEmpty else { throw DestinationError.invalidInstallation("default SDK not found") } sdkPath = AbsolutePath(sdkPathStr) } // Compute common arguments for clang and swift. // This is currently just frameworks path. let commonArgs = Destination.sdkPlatformFrameworkPath().map({ ["-F", $0.asString] }) ?? [] return Destination( target: hostTargetTriple, sdk: sdkPath, binDir: binDir, dynamicLibraryExtension: "dylib", extraCCFlags: ["-arch", "x86_64", "-mmacosx-version-min=10.10"] + commonArgs, extraSwiftCFlags: commonArgs, extraCPPFlags: ["-lc++"] ) #else return Destination( target: hostTargetTriple, sdk: .root, binDir: binDir, dynamicLibraryExtension: "so", extraCCFlags: ["-fPIC"], extraSwiftCFlags: [], extraCPPFlags: ["-lstdc++"] ) #endif } /// Returns macosx sdk platform framework path. public static func sdkPlatformFrameworkPath() -> AbsolutePath? { if let path = _sdkPlatformFrameworkPath { return path } let platformPath = try? Process.checkNonZeroExit( args: "xcrun", "--sdk", "macosx", "--show-sdk-platform-path").chomp() if let platformPath = platformPath, !platformPath.isEmpty { _sdkPlatformFrameworkPath = AbsolutePath(platformPath).appending( components: "Developer", "Library", "Frameworks") } return _sdkPlatformFrameworkPath } /// Cache storage for sdk platform path. private static var _sdkPlatformFrameworkPath: AbsolutePath? = nil #if os(macOS) /// Returns the host's dynamic library extension. public static let hostDynamicLibraryExtension = "dylib" /// Target triple for the host system. private static let hostTargetTriple = "x86_64-apple-macosx10.10" #else /// Returns the host's dynamic library extension. public static let hostDynamicLibraryExtension = "so" /// Target triple for the host system. private static let hostTargetTriple = "x86_64-unknown-linux" #endif } public extension Destination { /// Load a Destination description from a JSON representation from disk. public init(fromFile path: AbsolutePath, fileSystem: FileSystem = localFileSystem) throws { let json = try JSON(bytes: fileSystem.readFileContents(path)) try self.init(json: json) } } extension Destination: JSONMappable { /// The current schema version. static let schemaVersion = 1 public init(json: JSON) throws { // Check schema version. guard try json.get("version") == Destination.schemaVersion else { throw DestinationError.invalidSchemaVersion } try self.init( target: json.get("target"), sdk: AbsolutePath(json.get("sdk")), binDir: AbsolutePath(json.get("toolchain-bin-dir")), dynamicLibraryExtension: json.get("dynamic-library-extension"), extraCCFlags: json.get("extra-cc-flags"), extraSwiftCFlags: json.get("extra-swiftc-flags"), extraCPPFlags: json.get("extra-cpp-flags") ) } }
apache-2.0
6e64570e0a57b0497f8f86e7de1ecf4d
36.154639
108
0.641509
4.947152
false
false
false
false
Quick/Nimble
Sources/Nimble/Matchers/ThrowAssertion.swift
2
7238
// swiftlint:disable all #if canImport(CwlPreconditionTesting) && (os(macOS) || os(iOS)) import CwlPreconditionTesting #elseif canImport(CwlPosixPreconditionTesting) import CwlPosixPreconditionTesting #elseif canImport(Glibc) import Glibc // This function is called from the signal handler to shut down the thread and return 1 (indicating a SIGILL was received). private func callThreadExit() { pthread_exit(UnsafeMutableRawPointer(bitPattern: 1)) } // When called, this signal handler simulates a function call to `callThreadExit` private func sigIllHandler(code: Int32, info: UnsafeMutablePointer<siginfo_t>?, uap: UnsafeMutableRawPointer?) -> Void { guard let context = uap?.assumingMemoryBound(to: ucontext_t.self) else { return } // 1. Decrement the stack pointer context.pointee.uc_mcontext.gregs.15 /* REG_RSP */ -= Int64(MemoryLayout<Int>.size) // 2. Save the old Instruction Pointer to the stack. let rsp = context.pointee.uc_mcontext.gregs.15 /* REG_RSP */ if let ump = UnsafeMutablePointer<Int64>(bitPattern: Int(rsp)) { ump.pointee = rsp } // 3. Set the Instruction Pointer to the new function's address var f: @convention(c) () -> Void = callThreadExit withUnsafePointer(to: &f) { $0.withMemoryRebound(to: Int64.self, capacity: 1) { ptr in context.pointee.uc_mcontext.gregs.16 /* REG_RIP */ = ptr.pointee } } } /// Without Mach exceptions or the Objective-C runtime, there's nothing to put in the exception object. It's really just a boolean – either a SIGILL was caught or not. public class BadInstructionException { } /// Run the provided block. If a POSIX SIGILL is received, handle it and return a BadInstructionException (which is just an empty object in this POSIX signal version). Otherwise return nil. /// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a SIGILL is received, the block will be interrupted using a C `longjmp`. The risks associated with abrupt jumps apply here: most Swift functions are *not* interrupt-safe. Memory may be leaked and the program will not necessarily be left in a safe state. /// - parameter block: a function without parameters that will be run /// - returns: if an SIGILL is raised during the execution of `block` then a BadInstructionException will be returned, otherwise `nil`. public func catchBadInstruction(block: @escaping () -> Void) -> BadInstructionException? { // Construct the signal action var sigActionPrev = sigaction() var sigActionNew = sigaction() sigemptyset(&sigActionNew.sa_mask) sigActionNew.sa_flags = SA_SIGINFO sigActionNew.__sigaction_handler = .init(sa_sigaction: sigIllHandler) // Install the signal action if sigaction(SIGILL, &sigActionNew, &sigActionPrev) != 0 { fatalError("Sigaction error: \(errno)") } defer { // Restore the previous signal action if sigaction(SIGILL, &sigActionPrev, nil) != 0 { fatalError("Sigaction error: \(errno)") } } var b = block let caught: Bool = withUnsafeMutablePointer(to: &b) { blockPtr in // Run the block on its own thread var handlerThread: pthread_t = 0 let e = pthread_create(&handlerThread, nil, { arg in guard let arg = arg else { return nil } (arg.assumingMemoryBound(to: (() -> Void).self).pointee)() return nil }, blockPtr) precondition(e == 0, "Unable to create thread") // Wait for completion and get the result. It will be either `nil` or bitPattern 1 var rawResult: UnsafeMutableRawPointer? = nil let e2 = pthread_join(handlerThread, &rawResult) precondition(e2 == 0, "Thread join failed") return Int(bitPattern: rawResult) != 0 } return caught ? BadInstructionException() : nil } #endif public func throwAssertion<Out>() -> Predicate<Out> { return Predicate { actualExpression in #if (arch(x86_64) || arch(arm64)) && (canImport(Darwin) || canImport(Glibc)) let message = ExpectationMessage.expectedTo("throw an assertion") var actualError: Error? let caughtException: BadInstructionException? = catchBadInstruction { #if os(tvOS) if !NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning { print() print("[Nimble Warning]: If you're getting stuck on a debugger breakpoint for a " + "fatal error while using throwAssertion(), please disable 'Debug Executable' " + "in your scheme. Go to 'Edit Scheme > Test > Info' and uncheck " + "'Debug Executable'. If you've already done that, suppress this warning " + "by setting `NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning = true`. " + "This is required because the standard methods of catching assertions " + "(mach APIs) are unavailable for tvOS. Instead, the same mechanism the " + "debugger uses is the fallback method for tvOS." ) print() NimbleEnvironment.activeInstance.suppressTVOSAssertionWarning = true } #elseif os(watchOS) if !NimbleEnvironment.activeInstance.suppressWatchOSAssertionWarning { print() print("[Nimble Warning]: If you're getting stuck on a debugger breakpoint for a " + "fatal error while using throwAssertion(), please disable 'Debug Executable' " + "in your scheme. Go to 'Edit Scheme > Test > Info' and uncheck " + "'Debug Executable'. If you've already done that, suppress this warning " + "by setting `NimbleEnvironment.activeInstance.suppressWatchOSAssertionWarning = true`. " + "This is required because the standard methods of catching assertions " + "(mach APIs) are unavailable for watchOS. Instead, the same mechanism the " + "debugger uses is the fallback method for watchOS." ) print() NimbleEnvironment.activeInstance.suppressWatchOSAssertionWarning = true } #endif do { _ = try actualExpression.evaluate() } catch { actualError = error } } if let actualError = actualError { return PredicateResult( bool: false, message: message.appended(message: "; threw error instead <\(actualError)>") ) } else { return PredicateResult(bool: caughtException != nil, message: message) } #else let message = """ The throwAssertion Nimble matcher can only run on x86_64 and arm64 platforms. You can silence this error by placing the test case inside an #if arch(x86_64) || arch(arm64) conditional \ statement. """ fatalError(message) #endif } } // swiftlint:enable all
apache-2.0
f3ca3c02bfc4ae2c43354176e5f0c979
48.547945
386
0.639757
4.822667
false
true
false
false
AgaKhanFoundation/WCF-iOS
Pods/Quick/Sources/Quick/DSL/World+DSL.swift
3
10410
import Foundation /** Adds methods to World to support top-level DSL functions (Swift) and macros (Objective-C). These functions map directly to the DSL that test writers use in their specs. */ extension World { internal func beforeSuite(_ closure: @escaping BeforeSuiteClosure) { suiteHooks.appendBefore(closure) } internal func afterSuite(_ closure: @escaping AfterSuiteClosure) { suiteHooks.appendAfter(closure) } internal func sharedExamples(_ name: String, closure: @escaping SharedExampleClosure) { registerSharedExample(name, closure: closure) } internal func describe(_ description: String, flags: FilterFlags = [:], closure: () -> Void) { guard currentExampleMetadata == nil else { raiseError("'describe' cannot be used inside '\(currentPhase)', 'describe' may only be used inside 'context' or 'describe'.") } guard currentExampleGroup != nil else { // swiftlint:disable:next line_length raiseError("Error: example group was not created by its parent QuickSpec spec. Check that describe() or context() was used in QuickSpec.spec() and not a more general context (i.e. an XCTestCase test)") } let group = ExampleGroup(description: description, flags: flags) currentExampleGroup.appendExampleGroup(group) performWithCurrentExampleGroup(group, closure: closure) } internal func context(_ description: String, flags: FilterFlags = [:], closure: () -> Void) { guard currentExampleMetadata == nil else { raiseError("'context' cannot be used inside '\(currentPhase)', 'context' may only be used inside 'context' or 'describe'.") } self.describe(description, flags: flags, closure: closure) } internal func fdescribe(_ description: String, closure: () -> Void) { self.describe(description, flags: [Filter.focused: true], closure: closure) } internal func xdescribe(_ description: String, closure: () -> Void) { self.describe(description, flags: [Filter.pending: true], closure: closure) } internal func beforeEach(_ closure: @escaping BeforeExampleClosure) { guard currentExampleMetadata == nil else { raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'.") } currentExampleGroup.hooks.appendBefore(closure) } #if canImport(Darwin) @objc(beforeEachWithMetadata:) internal func beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) { currentExampleGroup.hooks.appendBefore(closure) } #else internal func beforeEach(closure: @escaping BeforeExampleWithMetadataClosure) { currentExampleGroup.hooks.appendBefore(closure) } #endif internal func afterEach(_ closure: @escaping AfterExampleClosure) { guard currentExampleMetadata == nil else { raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'.") } currentExampleGroup.hooks.appendAfter(closure) } #if canImport(Darwin) @objc(afterEachWithMetadata:) internal func afterEach(closure: @escaping AfterExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAfter(closure) } #else internal func afterEach(closure: @escaping AfterExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAfter(closure) } #endif internal func aroundEach(_ closure: @escaping AroundExampleClosure) { guard currentExampleMetadata == nil else { raiseError("'aroundEach' cannot be used inside '\(currentPhase)', 'aroundEach' may only be used inside 'context' or 'describe'. ") } currentExampleGroup.hooks.appendAround(closure) } #if canImport(Darwin) @objc(aroundEachWithMetadata:) internal func aroundEach(_ closure: @escaping AroundExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAround(closure) } #else internal func aroundEach(_ closure: @escaping AroundExampleWithMetadataClosure) { currentExampleGroup.hooks.appendAround(closure) } #endif @nonobjc internal func it(_ description: String, flags: FilterFlags = [:], file: FileString, line: UInt, closure: @escaping () throws -> Void) { if beforesCurrentlyExecuting { raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'.") } if aftersCurrentlyExecuting { raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'.") } guard currentExampleMetadata == nil else { raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'.") } let callsite = Callsite(file: file, line: line) let example = Example(description: description, callsite: callsite, flags: flags, closure: closure) currentExampleGroup.appendExample(example) } @nonobjc internal func fit(_ description: String, file: FileString, line: UInt, closure: @escaping () throws -> Void) { self.it(description, flags: [Filter.focused: true], file: file, line: line, closure: closure) } @nonobjc internal func xit(_ description: String, file: FileString, line: UInt, closure: @escaping () throws -> Void) { self.it(description, flags: [Filter.pending: true], file: file, line: line, closure: closure) } @nonobjc internal func itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, flags: FilterFlags = [:], file: FileString, line: UInt) { guard currentExampleMetadata == nil else { raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'.") } let callsite = Callsite(file: file, line: line) let closure = World.sharedWorld.sharedExample(name) let group = ExampleGroup(description: name, flags: flags) currentExampleGroup.appendExampleGroup(group) performWithCurrentExampleGroup(group) { closure(sharedExampleContext) } group.walkDownExamples { (example: Example) in example.isSharedExample = true example.callsite = callsite } } @nonobjc internal func fitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) { self.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: [Filter.focused: true], file: file, line: line) } @nonobjc internal func xitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) { self.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: [Filter.pending: true], file: file, line: line) } internal func itBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, flags: FilterFlags = [:], file: FileString, line: UInt) { guard currentExampleMetadata == nil else { raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'.") } let callsite = Callsite(file: file, line: line) let closure = behavior.spec let group = ExampleGroup(description: behavior.name, flags: flags) currentExampleGroup.appendExampleGroup(group) performWithCurrentExampleGroup(group) { closure(context) } group.walkDownExamples { (example: Example) in example.isSharedExample = true example.callsite = callsite } } internal func fitBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, file: FileString, line: UInt) { self.itBehavesLike(behavior, context: context, flags: [Filter.focused: true], file: file, line: line) } internal func xitBehavesLike<C>(_ behavior: Behavior<C>.Type, context: @escaping () -> C, file: FileString, line: UInt) { self.itBehavesLike(behavior, context: context, flags: [Filter.pending: true], file: file, line: line) } #if canImport(Darwin) && !SWIFT_PACKAGE @objc(itWithDescription:file:line:closure:) internal func objc_it(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) { it(description, file: file, line: line, closure: closure) } @objc(fitWithDescription:file:line:closure:) internal func objc_fit(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) { fit(description, file: file, line: line, closure: closure) } @objc(xitWithDescription:file:line:closure:) internal func objc_xit(_ description: String, file: FileString, line: UInt, closure: @escaping () -> Void) { xit(description, file: file, line: line, closure: closure) } @objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:) internal func objc_itBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) { itBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line) } @objc(fitBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:) internal func objc_fitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) { fitBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line) } @objc(xitBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:) internal func objc_xitBehavesLike(_ name: String, sharedExampleContext: @escaping SharedExampleContext, file: FileString, line: UInt) { xitBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line) } #endif internal func pending(_ description: String, closure: () -> Void) { print("Pending: \(description)") } private var currentPhase: String { if beforesCurrentlyExecuting { return "beforeEach" } else if aftersCurrentlyExecuting { return "afterEach" } return "it" } }
bsd-3-clause
3c5fa272b18ea86c86032ff61057dc95
44.26087
213
0.683285
4.85541
false
false
false
false
bitjammer/swift
test/IRGen/objc_structs.swift
5
3715
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo // CHECK: [[GIZMO:%TSo5GizmoC]] = type opaque // CHECK: [[NSRECT:%TSC6NSRectV]] = type <{ [[NSPOINT:%TSC7NSPointV]], [[NSSIZE:%TSC6NSSizeV]] }> // CHECK: [[NSPOINT]] = type <{ [[DOUBLE:%TSd]], [[DOUBLE]] }> // CHECK: [[DOUBLE]] = type <{ double }> // CHECK: [[NSSIZE]] = type <{ [[DOUBLE]], [[DOUBLE]] }> // CHECK: [[NSSTRING:%TSo8NSStringC]] = type opaque // CHECK: [[NSVIEW:%TSo6NSViewC]] = type opaque // CHECK: define hidden swiftcc { double, double, double, double } @_T012objc_structs8getFrame{{[_0-9a-zA-Z]*}}F([[GIZMO]]*) {{.*}} { func getFrame(_ g: Gizmo) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(frame)" // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}) return g.frame() } // CHECK: } // CHECK: define hidden swiftcc void @_T012objc_structs8setFrame{{[_0-9a-zA-Z]*}}F(%TSo5GizmoC*, double, double, double, double) {{.*}} { func setFrame(_ g: Gizmo, frame: NSRect) { // CHECK: load i8*, i8** @"\01L_selector(setFrame:)" // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) g.setFrame(frame) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @_T012objc_structs8makeRect{{[_0-9a-zA-Z]*}}F(double, double, double, double) func makeRect(_ a: Double, b: Double, c: Double, d: Double) -> NSRect { // CHECK: call void @NSMakeRect(%struct.NSRect* noalias nocapture sret {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}) return NSMakeRect(a,b,c,d) } // CHECK: } // CHECK: define hidden swiftcc [[stringLayout:[^@]*]] @_T012objc_structs14stringFromRect{{[_0-9a-zA-Z]*}}F(double, double, double, double) {{.*}} { func stringFromRect(_ r: NSRect) -> String { // CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect(%struct.NSRect* byval align 8 {{.*}}) return NSStringFromRect(r) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @_T012objc_structs9insetRect{{[_0-9a-zA-Z]*}}F(double, double, double, double, double, double) func insetRect(_ r: NSRect, x: Double, y: Double) -> NSRect { // CHECK: call void @NSInsetRect(%struct.NSRect* noalias nocapture sret {{.*}}, %struct.NSRect* byval align 8 {{.*}}, double {{.*}}, double {{.*}}) return NSInsetRect(r, x, y) } // CHECK: } // CHECK: define hidden swiftcc { double, double, double, double } @_T012objc_structs19convertRectFromBase{{[_0-9a-zA-Z]*}}F([[NSVIEW]]*, double, double, double, double) func convertRectFromBase(_ v: NSView, r: NSRect) -> NSRect { // CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}}) return v.convertRect(fromBase: r) } // CHECK: } // CHECK: define hidden swiftcc { {{.*}}*, {{.*}}*, {{.*}}*, {{.*}}* } @_T012objc_structs20useStructOfNSStringsSC0deF0VADF({{.*}}*, {{.*}}*, {{.*}}*, {{.*}}*) // CHECK: call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret {{%.*}}, %struct.StructOfNSStrings* byval align 8 {{%.*}}) func useStructOfNSStrings(_ s: StructOfNSStrings) -> StructOfNSStrings { return useStructOfNSStringsInObjC(s) }
apache-2.0
eb56024516e6876a1a6d4f689cfc0713
53.632353
231
0.618035
3.538095
false
false
false
false
Constructor-io/constructorio-client-swift
UserApplication/Screens/Sort/UI/SortOptionsViewController.swift
1
2280
// // SortOptionsViewController.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit class SortOptionsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let viewModel: SortViewModel let cellSortID = "cellSortID" init(viewModel: SortViewModel){ self.viewModel = viewModel self.viewModel.changed = false super.init(nibName: "SortOptionsViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UINib(nibName: "SortOptionTableViewCell", bundle: nil), forCellReuseIdentifier: self.cellSortID) self.tableView.tableFooterView = UIView(frame: .zero) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(didTapOnButtonDone)) } @objc func didTapOnButtonDone(){ self.viewModel.dismiss() self.dismiss(animated: true, completion: nil) } } extension SortOptionsViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.items.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellSortID) as! SortOptionTableViewCell let item = self.viewModel.items[indexPath.row] cell.labelSort.text = item.displayName cell.imageViewSort.image = item.image cell.accessoryType = item.selected ? .checkmark : .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.viewModel.toggle(indexPath: indexPath) self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic) } }
mit
793050a6cb502a1263d2042347c9e9ef
30.652778
146
0.697674
4.82839
false
false
false
false
gregomni/swift
stdlib/public/core/BridgingBuffer.swift
10
2011
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// internal struct _BridgingBufferHeader { internal var count: Int internal init(_ count: Int) { self.count = count } } // NOTE: older runtimes called this class _BridgingBufferStorage. // The two must coexist without a conflicting ObjC class name, so it // was renamed. The old name must not be used in the new runtime. internal final class __BridgingBufferStorage : ManagedBuffer<_BridgingBufferHeader, AnyObject> { } internal typealias _BridgingBuffer = ManagedBufferPointer<_BridgingBufferHeader, AnyObject> @available(OpenBSD, unavailable, message: "malloc_size is unavailable.") extension ManagedBufferPointer where Header == _BridgingBufferHeader, Element == AnyObject { internal init(_ count: Int) { self.init( _uncheckedBufferClass: __BridgingBufferStorage.self, minimumCapacity: count) self.withUnsafeMutablePointerToHeader { $0.initialize(to: Header(count)) } } internal var count: Int { @inline(__always) get { return header.count } @inline(__always) set { return header.count = newValue } } internal subscript(i: Int) -> Element { @inline(__always) get { return withUnsafeMutablePointerToElements { $0[i] } } } internal var baseAddress: UnsafeMutablePointer<Element> { @inline(__always) get { return withUnsafeMutablePointerToElements { $0 } } } internal var storage: AnyObject? { @inline(__always) get { return buffer } } }
apache-2.0
4588351bf4dd033f884e16e7e661ae7f
26.930556
80
0.640975
4.822542
false
false
false
false
fhbystudy/TYMutiTaskKit
TYMutiTaskKit/Libs/Haneke/UIButton+Haneke.swift
1
11692
// // UIButton+Haneke.swift // Haneke // // Created by Joan Romano on 10/1/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public extension UIButton { public var hnk_imageFormat : Format<UIImage> { let bounds = self.bounds assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(reflect(self).summary) \(__FUNCTION__)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.") let contentRect = self.contentRectForBounds(bounds) let imageInsets = self.imageEdgeInsets let scaleMode = self.contentHorizontalAlignment != UIControlContentHorizontalAlignment.Fill || self.contentVerticalAlignment != UIControlContentVerticalAlignment.Fill ? ImageResizer.ScaleMode.AspectFit : ImageResizer.ScaleMode.Fill let imageSize = CGSizeMake(CGRectGetWidth(contentRect) - imageInsets.left - imageInsets.right, CGRectGetHeight(contentRect) - imageInsets.top - imageInsets.bottom) return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: scaleMode, allowUpscaling: scaleMode == ImageResizer.ScaleMode.AspectFit ? false : true) } public func hnk_setImageFromURL(URL : NSURL, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = NetworkFetcher<UIImage>(URL: URL) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImage(image : UIImage, key : String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = SimpleFetcher<UIImage>(key: key, value: image) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed) } public func hnk_setImageFromFile(path : String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = DiskFetcher<UIImage>(path: path) self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setImageFromFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil){ self.hnk_cancelSetImage() self.hnk_imageFetcher = fetcher let didSetImage = self.hnk_fetchImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed) if didSetImage { return } if let placeholder = placeholder { self.setImage(placeholder, forState: state) } } public func hnk_cancelSetImage() { if let fetcher = self.hnk_imageFetcher { fetcher.cancelFetch() self.hnk_imageFetcher = nil } } // MARK: Internal Image // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_imageFetcher : Fetcher<UIImage>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.value as? Fetcher<UIImage> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } func hnk_fetchImageForFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool { let format = format ?? self.hnk_imageFormat let cache = Shared.imageCache if cache.formats[format.name] == nil { cache.addFormat(format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return } strongSelf.hnk_imageFetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return } strongSelf.hnk_setImage(image, state: state, animated: false, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setImage(image : UIImage, state : UIControlState, animated : Bool, success succeed : ((UIImage) -> ())?) { self.hnk_imageFetcher = nil if let succeed = succeed { succeed(image) } else { let duration : NSTimeInterval = animated ? 0.1 : 0 UIView.transitionWithView(self, duration: duration, options: .TransitionCrossDissolve, animations: { self.setImage(image, forState: state) }, completion: nil) } } func hnk_shouldCancelImageForKey(key:String) -> Bool { if self.hnk_imageFetcher?.key == key { return false } Log.error("Cancelled set image for \(key.lastPathComponent)") return true } // MARK: Background image public var hnk_backgroundImageFormat : Format<UIImage> { let bounds = self.bounds assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(reflect(self).summary) \(__FUNCTION__)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.") let imageSize = self.backgroundRectForBounds(bounds).size return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: .Fill) } public func hnk_setBackgroundImageFromURL(URL : NSURL, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = NetworkFetcher<UIImage>(URL: URL) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setBackgroundImage(image : UIImage, key : String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = SimpleFetcher<UIImage>(key: key, value: image) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed) } public func hnk_setBackgroundImageFromFile(path : String, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) { let fetcher = DiskFetcher<UIImage>(path: path) self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed) } public func hnk_setBackgroundImageFromFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil){ self.hnk_cancelSetBackgroundImage() self.hnk_backgroundImageFetcher = fetcher let didSetImage = self.hnk_fetchBackgroundImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed) if didSetImage { return } if let placeHolder = placeholder { self.setBackgroundImage(placeholder, forState: state) } } public func hnk_cancelSetBackgroundImage() { if let fetcher = self.hnk_backgroundImageFetcher { fetcher.cancelFetch() self.hnk_backgroundImageFetcher = nil } } // MARK: Internal Background image // See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances var hnk_backgroundImageFetcher : Fetcher<UIImage>! { get { let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey) as? ObjectWrapper let fetcher = wrapper?.value as? Fetcher<UIImage> return fetcher } set (fetcher) { var wrapper : ObjectWrapper? if let fetcher = fetcher { wrapper = ObjectWrapper(value: fetcher) } objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey, wrapper, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } func hnk_fetchBackgroundImageForFetcher(fetcher : Fetcher<UIImage>, state : UIControlState = .Normal, format : Format<UIImage>? = nil, failure fail : ((NSError?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool { let format = format ?? self.hnk_backgroundImageFormat let cache = Shared.imageCache if cache.formats[format.name] == nil { cache.addFormat(format) } var animated = false let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in if let strongSelf = self { if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return } strongSelf.hnk_backgroundImageFetcher = nil fail?(error) } }) { [weak self] image in if let strongSelf = self { if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return } strongSelf.hnk_setBackgroundImage(image, state: state, animated: false, success: succeed) } } animated = true return fetch.hasSucceeded } func hnk_setBackgroundImage(image : UIImage, state : UIControlState, animated : Bool, success succeed : ((UIImage) -> ())?) { self.hnk_backgroundImageFetcher = nil if let succeed = succeed { succeed(image) } else { let duration : NSTimeInterval = animated ? 0.1 : 0 UIView.transitionWithView(self, duration: duration, options: .TransitionCrossDissolve, animations: { self.setBackgroundImage(image, forState: state) }, completion: nil) } } func hnk_shouldCancelBackgroundImageForKey(key:String) -> Bool { if self.hnk_backgroundImageFetcher?.key == key { return false } Log.error("Cancelled set background image for \(key.lastPathComponent)") return true } }
apache-2.0
9fc5ca639897202919a8880078c17847
49.396552
278
0.626582
4.910542
false
false
false
false
edwardvalentini/Q
Pod/Classes/QSerializerNSDefaults.swift
1
2232
// // QSerializerNSDefaults.swift // Pods // // Created by Edward Valentini on 1/28/16. // import Foundation import UIKit open class QSerializerNSDefaults: QSerializerPrototol { open func serializeOperation(_ operation: QOperation, queue: Q) { if let queueName = queue.name { if let serialized = operation.toJSONString() { let defaults = UserDefaults.standard var stringArray: [String] if let curStringArray = defaults.stringArray(forKey: queueName) { stringArray = curStringArray stringArray.append(serialized) } else { stringArray = [serialized] } defaults.setValue(stringArray, forKey: queueName) defaults.synchronize() print("operation \(operation.operationID) was serialized") } else { print("unable to serialize operation - error") } } else { print("no queue name for queue - error") } } open func deSerializedOperations(queue: Q) -> [QOperation] { let defaults = UserDefaults.standard if let queueName = queue.name, let stringArray = defaults.stringArray(forKey: queueName) { print(stringArray.count) return stringArray .map { return QOperation(json: $0, queue: queue)} .filter { return $0 != nil } .map { return $0! } } return [] } open func removeOperation(_ operationID: String, queue: Q) { if let queueName = queue.name { var curArray: [QOperation] = deSerializedOperations(queue: queue) curArray = curArray.filter {return $0.operationID != operationID } let stringArray = curArray .map {return $0.toJSONString() } .filter { return $0 != nil} .map { return $0! } UserDefaults.standard.setValue(stringArray, forKey: queueName) } } }
mit
a45f76eb51be87849cdcadd821ab1da1
32.313433
85
0.518817
5.251765
false
false
false
false
auth0/SimpleKeychain
SimpleKeychainTests/AccessibilitySpec.swift
1
3379
import Security import Nimble import Quick import SimpleKeychain class AccessibilitySpec: QuickSpec { override func spec() { describe("raw representable") { context("from raw value to case") { it("should map kSecAttrAccessibleWhenUnlocked") { let sut = Accessibility(rawValue: kSecAttrAccessibleWhenUnlocked) expect(sut) == Accessibility.whenUnlocked } it("should map kSecAttrAccessibleWhenUnlockedThisDeviceOnly") { let sut = Accessibility(rawValue: kSecAttrAccessibleWhenUnlockedThisDeviceOnly) expect(sut) == Accessibility.whenUnlockedThisDeviceOnly } it("should map kSecAttrAccessibleAfterFirstUnlock") { let sut = Accessibility(rawValue: kSecAttrAccessibleAfterFirstUnlock) expect(sut) == Accessibility.afterFirstUnlock } it("should map kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly") { let sut = Accessibility(rawValue: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) expect(sut) == Accessibility.afterFirstUnlockThisDeviceOnly } it("should map kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly") { let sut = Accessibility(rawValue: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) expect(sut) == Accessibility.whenPasscodeSetThisDeviceOnly } it("should map unknown values") { let sut = Accessibility(rawValue: "foo" as CFString) expect(sut) == Accessibility.afterFirstUnlock } } context("from case to raw value") { it("should map whenUnlocked") { let sut = Accessibility.whenUnlocked.rawValue as String expect(sut) == (kSecAttrAccessibleWhenUnlocked as String) } it("should map whenUnlockedThisDeviceOnly") { let sut = Accessibility.whenUnlockedThisDeviceOnly.rawValue as String expect(sut) == (kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String) } it("should map afterFirstUnlock") { let sut = Accessibility.afterFirstUnlock.rawValue as String expect(sut) == (kSecAttrAccessibleAfterFirstUnlock as String) } it("should map afterFirstUnlockThisDeviceOnly") { let sut = Accessibility.afterFirstUnlockThisDeviceOnly.rawValue as String expect(sut) == (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String) } it("should map whenPasscodeSetThisDeviceOnly") { let sut = Accessibility.whenPasscodeSetThisDeviceOnly.rawValue as String expect(sut) == (kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String) } it("should map whenPasscodeSetThisDeviceOnly") { let sut = Accessibility.whenPasscodeSetThisDeviceOnly.rawValue as String expect(sut) == (kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String) } } } } }
mit
b487f8383e1ceb240b2147fc7c9a2f7d
44.662162
103
0.595146
7.732265
false
false
false
false
ketoo/actor-platform
actor-apps/app-ios/Actor/Controllers/Auth/AuthPhoneViewController.swift
55
11488
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class AuthPhoneViewController: AuthViewController, UITextFieldDelegate { // MARK: - // MARK: Private vars private var grayBackground: UIView! private var titleLabel: UILabel! private var countryButton: UIButton! private var phoneBackgroundView: UIImageView! private var countryCodeLabel: UILabel! private var phoneTextField: ABPhoneField! private var hintLabel: UILabel! private var navigationBarSeparator: UIView! // MARK: - // MARK: Public vars var currentIso: String = "" { didSet { phoneTextField.currentIso = currentIso let countryCode: String = ABPhoneField.callingCodeByCountryCode()[currentIso] as! String countryCodeLabel.text = "+\(countryCode)" countryButton.setTitle(ABPhoneField.countryNameByCountryCode()[currentIso] as? String, forState: UIControlState.Normal) } } // MARK: - // MARK: Constructors override init() { super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func loadView() { super.loadView() view.backgroundColor = UIColor.whiteColor() grayBackground = UIView() grayBackground.backgroundColor = UIColor.RGB(0xf2f2f2) view.addSubview(grayBackground) titleLabel = UILabel() titleLabel.backgroundColor = UIColor.clearColor() titleLabel.textColor = UIColor.blackColor() titleLabel.font = isIPad ? UIFont(name: "HelveticaNeue-Thin", size: 50.0) : UIFont(name: "HelveticaNeue-Light", size: 30.0) titleLabel.text = NSLocalizedString("AuthPhoneTitle", comment: "Title") grayBackground.addSubview(titleLabel) let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton") let countryImageHighlighted: UIImage! = UIImage(named: "ModernAuthCountryButtonHighlighted") countryButton = UIButton() countryButton.setBackgroundImage(countryImage.stretchableImageWithLeftCapWidth(Int(countryImage.size.width / 2), topCapHeight: 0), forState: UIControlState.Normal) countryButton.setBackgroundImage(countryImageHighlighted.stretchableImageWithLeftCapWidth(Int(countryImageHighlighted.size.width / 2), topCapHeight: 0), forState: UIControlState.Highlighted) countryButton.titleLabel?.font = UIFont.systemFontOfSize(20.0) countryButton.titleLabel?.textAlignment = NSTextAlignment.Left countryButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left countryButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) countryButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 14, bottom: 9, right: 14) countryButton.addTarget(self, action: Selector("showCountriesList"), forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(countryButton) let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground") phoneBackgroundView = UIImageView(image: phoneImage.stretchableImageWithLeftCapWidth(Int(phoneImage.size.width / 2), topCapHeight: 0)) view.addSubview(phoneBackgroundView) countryCodeLabel = UILabel() countryCodeLabel.font = UIFont.systemFontOfSize(20.0) countryCodeLabel.backgroundColor = UIColor.clearColor() countryCodeLabel.textAlignment = NSTextAlignment.Center phoneBackgroundView.addSubview(countryCodeLabel) phoneTextField = ABPhoneField() phoneTextField.font = UIFont.systemFontOfSize(20.0) phoneTextField.backgroundColor = UIColor.whiteColor() phoneTextField.placeholder = NSLocalizedString("AuthPhoneNumberHint", comment: "Hint") phoneTextField.keyboardType = UIKeyboardType.NumberPad; phoneTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center phoneTextField.delegate = self view.addSubview(phoneTextField) navigationBarSeparator = UIView() navigationBarSeparator.backgroundColor = UIColor.RGB(0xc8c7cc) view.addSubview(navigationBarSeparator) hintLabel = UILabel() hintLabel.font = UIFont.systemFontOfSize(17.0) hintLabel.textColor = UIColor.RGB(0x999999) hintLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping hintLabel.backgroundColor = UIColor.whiteColor() hintLabel.textAlignment = NSTextAlignment.Center hintLabel.contentMode = UIViewContentMode.Center hintLabel.numberOfLines = 0 hintLabel.text = NSLocalizedString("AuthPhoneHint", comment: "Hint") view.addSubview(hintLabel) var nextBarButton = UIBarButtonItem(title: NSLocalizedString("NavigationNext", comment: "Next Title"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("nextButtonPressed")) // TODO: Localize navigationItem.rightBarButtonItem = nextBarButton currentIso = phoneTextField.currentIso } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let screenSize = UIScreen.mainScreen().bounds.size let isWidescreen = screenSize.width > 320 || screenSize.height > 480 let isPortraint = screenSize.width < screenSize.height let bgSize = isIPad ? (isPortraint ? 304.0: 140) : (isWidescreen ? 131.0 : 90.0) grayBackground.frame = CGRect(x: 0.0, y: 0.0, width: screenSize.width, height: CGFloat(bgSize)) let padding = isIPad ? (isPortraint ? 48 : 20) : (20) titleLabel.sizeToFit() titleLabel.frame = CGRect(x: (screenSize.width - titleLabel.frame.size.width) / 2.0, y: grayBackground.frame.height - titleLabel.frame.size.height - CGFloat(padding), width: titleLabel.frame.size.width, height: titleLabel.frame.size.height) navigationBarSeparator.frame = CGRect(x: 0, y: grayBackground.bounds.size.height, width: screenSize.width, height: retinaPixel) let fieldWidth : CGFloat = isIPad ? (520) : (screenSize.width) let countryImage: UIImage! = UIImage(named: "ModernAuthCountryButton") countryButton.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: grayBackground.frame.origin.y + grayBackground.bounds.size.height, width: fieldWidth, height: countryImage.size.height) let phoneImage: UIImage! = UIImage(named: "ModernAuthPhoneBackground") phoneBackgroundView.frame = CGRect(x: (screenSize.width - fieldWidth) / 2, y: countryButton.frame.origin.y + 57, width: fieldWidth, height: phoneImage.size.height) let countryCodeLabelTopSpacing: CGFloat = 3.0 countryCodeLabel.frame = CGRect(x: 14, y: countryCodeLabelTopSpacing, width: 68, height: phoneBackgroundView.frame.size.height - countryCodeLabelTopSpacing) phoneTextField.frame = CGRect(x: (screenSize.width - fieldWidth) / 2 + 96.0, y: phoneBackgroundView.frame.origin.y + 1, width: fieldWidth - 96.0 - 10.0, height: phoneBackgroundView.frame.size.height - 2) let hintPadding : CGFloat = isIPad ? (isPortraint ? 460.0: 274.0) : (isWidescreen ? 274.0 : 214.0) let hintLabelSize = hintLabel.sizeThatFits(CGSize(width: 278.0, height: CGFloat.max)) hintLabel.frame = CGRect(x: (screenSize.width - hintLabelSize.width) / 2.0, y: hintPadding, width: hintLabelSize.width, height: hintLabelSize.height); } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) phoneTextField.becomeFirstResponder() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { MSG.trackAuthPhoneTypeWithValue(textField.text) return true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MainAppTheme.navigation.applyAuthStatusBar() MSG.trackAuthPhoneOpen() } // MARK: - // MARK: Methods func nextButtonPressed() { let action = "Request code" MSG.trackCodeRequest() let numberLength = count(phoneTextField.phoneNumber) as Int let numberRequiredLength: Int = (ABPhoneField.phoneMinLengthByCountryCode()[currentIso] as! String).toInt()! if (numberLength < numberRequiredLength) { var msg = NSLocalizedString("AuthPhoneTooShort", comment: "Too short error"); SVProgressHUD.showErrorWithStatus(msg) MSG.trackActionError(action, withTag: "LOCAL_EMPTY_PHONE", withMessage: msg) } else { execute(MSG.requestSmsObsoleteCommandWithPhone(jlong((phoneTextField.phoneNumber as NSString).longLongValue)), successBlock: { (val) -> () in MSG.trackActionSuccess(action) self.navigateToSms() }, failureBlock: { (val) -> () in var message = "Unknown error" var tag = "UNKNOWN" var canTryAgain = false if let exception = val as? AMRpcException { tag = exception.getTag() if (tag == "PHONE_NUMBER_INVALID") { message = NSLocalizedString("ErrorPhoneIncorrect", comment: "PHONE_NUMBER_INVALID error") } else { message = exception.getLocalizedMessage() } canTryAgain = exception.isCanTryAgain() } else if let exception = val as? JavaLangException { message = exception.getLocalizedMessage() canTryAgain = true } MSG.trackActionError(action, withTag: tag, withMessage: message) var alertView = UIAlertView(title: nil, message: message, delegate: self, cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok")) alertView.show() }) } } // MARK: - // MARK: Navigation func showCountriesList() { var countriesController = AuthCountriesViewController() countriesController.delegate = self countriesController.currentIso = currentIso var navigationController = AANavigationController(rootViewController: countriesController) presentViewController(navigationController, animated: true, completion: nil) } func navigateToSms() { var smsController = AuthSmsViewController() smsController.phoneNumber = "+\(phoneTextField.formattedPhoneNumber)" navigateNext(smsController, removeCurrent: false) } } // MARK: - // MARK: AAAuthCountriesController Delegate extension AuthPhoneViewController: AuthCountriesViewControllerDelegate { func countriesController(countriesController: AuthCountriesViewController, didChangeCurrentIso currentIso: String) { self.currentIso = currentIso } }
mit
7282f8afbe69b859ebb45ffde7be32fc
44.772908
248
0.65477
5.316057
false
false
false
false
HTWDD/htwcampus
HTWDD/Components/Onboarding/Welcome/OnboardWelcomeViewController.swift
1
4412
// // OnboardWelcomeViewController.swift // HTWDD // // Created by Fabian Ehlert on 12.10.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit class OnboardWelcomeViewController: ViewController { var onContinue: ((OnboardWelcomeViewController) -> Void)? // MARK: - ViewController lifecycle override func viewDidLoad() { super.viewDidLoad() } override func initialSetup() { // --- Title label --- let titleLabel = UILabel() titleLabel.font = .systemFont(ofSize: 44, weight: .bold) titleLabel.textAlignment = .left titleLabel.numberOfLines = 2 titleLabel.translatesAutoresizingMaskIntoConstraints = false let w = Loca.Onboarding.Welcome.Title let welcome = NSMutableAttributedString(string: w) welcome.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.htw.textHeadline, range: NSRange(location: 0, length: w.count)) if let r = w.rangeOfSubString("HTW") { welcome.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.htw.orange, range: r) } titleLabel.attributedText = welcome let titleContainer = UIView() titleContainer.translatesAutoresizingMaskIntoConstraints = false titleContainer.add(titleLabel) self.view.add(titleContainer) // --- Description box --- let descriptions: [(String, String)] = [ (Loca.Schedule.title, Loca.Onboarding.Welcome.ScheduleDescription), (Loca.Canteen.title, Loca.Onboarding.Welcome.CanteenDescription), (Loca.Grades.title, Loca.Onboarding.Welcome.GradesDescription) ] let stackViews: [UIStackView] = descriptions.map { descPair in let title = UILabel() title.text = descPair.0 title.font = .systemFont(ofSize: 20, weight: .semibold) title.textColor = UIColor.htw.textHeadline let desc = UILabel() desc.text = descPair.1 desc.font = .systemFont(ofSize: 17, weight: .medium) desc.textColor = UIColor.htw.textBody desc.numberOfLines = 0 let s = UIStackView(arrangedSubviews: [title, desc]) s.axis = .vertical return s } let descriptionStackView = UIStackView(arrangedSubviews: stackViews) descriptionStackView.translatesAutoresizingMaskIntoConstraints = false descriptionStackView.axis = .vertical descriptionStackView.distribution = .fillProportionally descriptionStackView.spacing = 20.0 self.view.add(descriptionStackView) // --- Continue Button --- let continueButton = ReactiveButton() continueButton.setTitle(Loca.nextStep, for: .normal) continueButton.titleLabel?.font = .systemFont(ofSize: 20, weight: .semibold) continueButton.backgroundColor = UIColor.htw.blue continueButton.layer.cornerRadius = 12 continueButton.translatesAutoresizingMaskIntoConstraints = false continueButton.addTarget(self, action: #selector(continueBoarding), for: .touchUpInside) self.view.add(continueButton) // --- Constraints --- NSLayoutConstraint.activate([ titleContainer.topAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.topAnchor, constant: 12), titleContainer.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), titleContainer.bottomAnchor.constraint(equalTo: descriptionStackView.topAnchor), titleContainer.widthAnchor.constraint(equalTo: descriptionStackView.widthAnchor), titleLabel.leadingAnchor.constraint(equalTo: titleContainer.leadingAnchor), titleLabel.centerYAnchor.constraint(equalTo: titleContainer.centerYAnchor), titleLabel.trailingAnchor.constraint(equalTo: titleContainer.trailingAnchor), descriptionStackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), descriptionStackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), descriptionStackView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8), continueButton.heightAnchor.constraint(equalToConstant: 55), continueButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), continueButton.widthAnchor.constraint(equalTo: descriptionStackView.widthAnchor), continueButton.bottomAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.bottomAnchor, constant: -20) ]) } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } // MARK: - Actions @objc private func continueBoarding() { self.onContinue?(self) } }
mit
2319071f1afb090be0491fd87b4451e3
34.007937
141
0.767173
4.446573
false
false
false
false
willpowell8/JIRAMobileKit
JIRAMobileKit/Classes/TableCells/JIRAEntities.swift
1
11459
// // JIRAEntities.swift // Pods // // Created by Will Powell on 30/08/2017. // // import Foundation protocol DisplayClass:NSObjectProtocol { var label:String?{get} func applyData(data:[AnyHashable:Any]) } protocol ChildrenClass { var children:[Any]?{get} } enum JIRASchemaType:String { case string = "string" case issuetype = "issuetype" case priority = "priority" case project = "project" case user = "user" case array = "array" case number = "number" case option = "option" } enum JIRAOperations:String { case set = "set" case add = "add" case remove = "remove" } enum JIRASchemaSystem:String { case assignee = "assignee" case fixVersions = "fixVersions" case labels = "labels" case issuelinks = "issuelinks" case priority = "priority" case environment = "environment" case attachment = "attachment" } class JIRAEntity :NSObject { required public override init() { super.init() } func export()->Any? { return [String:Any]() } } class JIRASchema{ var type:JIRASchemaType? var system:JIRASchemaSystem? var custom:String? var customId:Int? var items:String? func applyData(data:[AnyHashable:Any]){ if let typeStr = data["type"] as? String { if let type = JIRASchemaType(rawValue:typeStr) { self.type = type } } if let systemStr = data["system"] as? String { if let system = JIRASchemaSystem(rawValue:systemStr) { self.system = system } } if let customId = data["customId"] as? Int { self.customId = customId } if let custom = data["custom"] as? String { self.custom = custom } if let items = data["items"] as? String { self.items = items } } } class JIRAAllowedValue:JIRAEntity,DisplayClass{ var id:String? var name:String? var value:String? func applyData(data:[AnyHashable:Any]){ if let id = data["id"] as? String { self.id = id } if let name = data["name"] as? String { self.name = name } if let value = data["value"] as? String { self.value = value } } var label: String? { get{ if let name = name { return name } if let value = value { return value } return nil } } override func export()->Any?{ return ["id":id ?? "","name":name ?? "","value":value ?? ""] } } class JIRAJQLValue:JIRAEntity,DisplayClass{ var displayName:String? var value:String? func applyData(data:[AnyHashable:Any]){ if let displayName = data["displayName"] as? String { self.displayName = displayName } if let value = data["value"] as? String { self.value = value } } var label: String? { get{ if let displayName = displayName { return displayName } if let value = value { return value } return nil } } override func export()->Any?{ return ["displayName":displayName ?? "","value":value ?? ""] } } class JIRALabel:JIRAEntity,DisplayClass{ var labelVal:String? var html:String? required public init() { super.init() } func applyData(data:[AnyHashable:Any]){ if let label = data["label"] as? String { self.labelVal = label } if let html = data["html"] as? String { self.html = html } } var label: String? { get{ return labelVal } } override func export()->Any?{ return self.label } } class JIRAUser:JIRAEntity,DisplayClass{ var displayName:String? var key:String? var emailAddress:String? var active:Bool? var timeZone:String? var locale:String? var name:String? func applyData(data:[AnyHashable:Any]){ if let displayName = data["displayName"] as? String { self.displayName = displayName } if let key = data["key"] as? String { self.key = key } if let emailAddress = data["emailAddress"] as? String { self.emailAddress = emailAddress } if let active = data["active"] as? Bool { self.active = active } if let timeZone = data["timeZone"] as? String { self.timeZone = timeZone } if let locale = data["locale"] as? String { self.locale = locale } if let name = data["name"] as? String { self.name = name } } var label: String? { get{ return displayName } } override func export()->Any?{ return [ "key":key ?? "", "name":name ?? "" ] } } class JIRAField{ var required:Bool = false var schema:JIRASchema? var identifier:String? var name:String? var autoCompleteUrl:String? var hasDefaultValue:Bool = false var operations:[JIRAOperations]? var allowedValues:[JIRAAllowedValue]? var raw:[AnyHashable:Any]? func applyData(data:[AnyHashable:Any]){ self.raw = data if let required = data["required"] as? Bool { self.required = required } if let schemaData = data["schema"] as? [AnyHashable:Any] { let schema = JIRASchema() schema.applyData(data: schemaData) self.schema = schema } if let name = data["name"] as? String { self.name = name } if let operations = data["operations"] as? [String]{ let ops = operations.compactMap({ (operation) -> JIRAOperations? in return JIRAOperations(rawValue:operation) }) self.operations = ops } if let autoCompleteUrl = data["autoCompleteUrl"] as? String { self.autoCompleteUrl = autoCompleteUrl } if let hasDefaultValue = data["hasDefaultValue"] as? Bool { self.hasDefaultValue = hasDefaultValue } if let allowedValues = data["allowedValues"] as? [[AnyHashable:Any]] { var allowedValuesOutput = [JIRAAllowedValue]() allowedValues.forEach({ (allowedValueData) in let allowedValue = JIRAAllowedValue() allowedValue.applyData(data: allowedValueData) allowedValuesOutput.append(allowedValue) }) self.allowedValues = allowedValuesOutput } } } class JIRAIssueType{ var id:String? var desc:String? var iconUrl:String? var name:String? var subtask:Bool = false var fields:[JIRAField]? func applyData(data:[AnyHashable:Any]){ if let id = data["id"] as? String { self.id = id } if let desc = data["description"] as? String { self.desc = desc } if let iconUrl = data["iconUrl"] as? String { self.iconUrl = iconUrl } if let name = data["name"] as? String { self.name = name } var fields = [JIRAField]() if let jiraFields = data["fields"] as? [AnyHashable:Any] { JIRA.shared.preferredOrder.forEach { (identifier) in if let v = jiraFields[identifier] as? [AnyHashable:Any] { let field = JIRAField() field.identifier = identifier field.applyData(data: v) fields.append(field) } } var fieldsKeys = jiraFields.compactMap { (key, value) -> String? in guard let identifier = key as? String else { return nil } guard !JIRA.shared.preferredOrder.contains(identifier) else { return nil } return identifier } fieldsKeys = fieldsKeys.sorted() fieldsKeys.forEach { (f) in if let v = jiraFields[f] as? [AnyHashable:Any] { let field = JIRAField() field.identifier = f field.applyData(data: v) fields.append(field) } } } self.fields = fields } } class JIRAProject { var id:String? var key:String? var name:String? var avatarUrls:[String:String]? var issueTypes:[JIRAIssueType]? func applyData(data:[AnyHashable:Any]){ if let id = data["id"] as? String { self.id = id } if let key = data["key"] as? String { self.key = key } if let name = data["name"] as? String { self.name = name } if let issueTypes = data["issuetypes"] as? [[AnyHashable:Any]] { var issueTypesOutput = [JIRAIssueType]() issueTypes.forEach({ (issueTypeData) in let issueType = JIRAIssueType() issueType.applyData(data: issueTypeData) issueTypesOutput.append(issueType) }) self.issueTypes = issueTypesOutput } } } class JIRAIssueSection:JIRAEntity,DisplayClass,ChildrenClass { var labelStr:String? var sub:String? var id:String? var issues:[JIRAEntity]? func applyData(data:[AnyHashable:Any]){ if let id = data["id"] as? String { self.id = id } if let sub = data["sub"] as? String { self.sub = sub } if let label = data["label"] as? String { self.labelStr = label } var issues = [JIRAIssue]() if let ary = data["issues"] as? [[AnyHashable:Any]] { ary.forEach({ (item) in let issue = JIRAIssue() issue.applyData(data: item) issues.append(issue) }) } self.issues = issues } var children: [Any]?{ get{ return issues } } var label: String? { get{ return labelStr } } } class JIRAIssue:JIRAEntity,DisplayClass { var key:String? var keyHtml:String? var img:String? var summary:String? var summaryText:String? func applyData(data:[AnyHashable:Any]){ if let key = data["key"] as? String { self.key = key } if let keyHtml = data["keyHtml"] as? String { self.keyHtml = keyHtml } if let img = data["img"] as? String { self.img = img } if let summary = data["summary"] as? String { self.summary = summary } if let summaryText = data["summaryText"] as? String { self.summaryText = summaryText } } var label: String? { get{ var output = "" if let key = self.key { output = key } if let summary = self.summary { output += " - " + summary } return output } } }
mit
59a6988d357c255230a68c6b98ce8ed6
25.403226
79
0.519417
4.529249
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Authentication/TokenValidationServiceSpec.swift
1
2899
import XCTest import Quick import Nimble import Fleet import RxSwift @testable import FrequentFlyer class TokenValidationServiceSpec: QuickSpec { class MockHTTPClient: HTTPClient { var capturedRequest: URLRequest? var callCount = 0 var responseSubject = PublishSubject<HTTPResponse>() override func perform(request: URLRequest) -> Observable<HTTPResponse> { capturedRequest = request callCount += 1 return responseSubject } } override func spec() { describe("TokenValidationService") { var subject: TokenValidationService! var mockHTTPClient: MockHTTPClient! beforeEach { subject = TokenValidationService() mockHTTPClient = MockHTTPClient() subject.httpClient = mockHTTPClient } describe("Validating a token") { var capturedError: Error? beforeEach { let token = Token(value: "valid turtle token") subject.validate(token: token, forConcourse: "turtle_concourse.com") { error in capturedError = error } } it("uses the HTTPClient to make a request") { guard let request = mockHTTPClient.capturedRequest else { fail("Failed to make a call to the HTTPClient") return } expect(request.url?.absoluteString).to(equal("turtle_concourse.com/api/v1/containers")) expect(request.httpMethod).to(equal("GET")) expect(request.allHTTPHeaderFields?["Content-Type"]).to(equal("application/json")) expect(request.allHTTPHeaderFields?["Authorization"]).to(equal("Bearer valid turtle token")) } describe("When the token is valid") { beforeEach { let doesNotMatterData = Data() mockHTTPClient.responseSubject.onNext(HTTPResponseImpl(body: doesNotMatterData, statusCode: 200)) } it("resolves the original input completion block with no error") { expect(capturedError).to(beNil()) } } describe("When the token is not valid") { beforeEach { mockHTTPClient.responseSubject.onError(BasicError(details: "turtle error")) } it("resolves the original input completion block with the error from the network call") { expect(capturedError as? BasicError).to(equal(BasicError(details: "turtle error"))) } } } } } }
apache-2.0
8b48dcfc9d9b1ae8c400f66bebac8f12
35.696203
121
0.537082
6.090336
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Builds/BuildsDataDeserializerSpec.swift
1
8086
import XCTest import Quick import Nimble import SwiftyJSON import Result @testable import FrequentFlyer class BuildsDataDeserializerSpec: QuickSpec { class MockBuildDataDeserializer: BuildDataDeserializer { private var toReturnBuild: [Data : Build] = [:] private var toReturnError: [Data : DeserializationError] = [:] fileprivate func when(_ data: JSON, thenReturn build: Build) { let jsonData = try! data.rawData(options: .prettyPrinted) toReturnBuild[jsonData] = build } fileprivate func when(_ data: JSON, thenErrorWith error: DeserializationError) { let jsonData = try! data.rawData(options: .prettyPrinted) toReturnError[jsonData] = error } override func deserialize(_ data: Data) -> Result<Build, DeserializationError> { let inputAsJSON = JSON(data: data) for (keyData, build) in toReturnBuild { let keyAsJSON = JSON(data: keyData) if keyAsJSON == inputAsJSON { return Result.success(build) } } for (keyData, error) in toReturnError { let keyAsJSON = JSON(data: keyData) if keyAsJSON == inputAsJSON { return Result.failure(error) } } return Result.failure(DeserializationError(details: "fatal error in test", type: .missingRequiredData)) } } override func spec() { describe("BuildsDataDeserializer") { var subject: BuildsDataDeserializer! var mockBuildDataDeserializer: MockBuildDataDeserializer! var validBuildJSONOne: JSON! var validBuildJSONTwo: JSON! var validBuildJSONThree: JSON! var result: Result<[Build], DeserializationError>! beforeEach { subject = BuildsDataDeserializer() mockBuildDataDeserializer = MockBuildDataDeserializer() subject.buildDataDeserializer = mockBuildDataDeserializer validBuildJSONOne = JSON(dictionaryLiteral: [ ("id", 1), ("name", "name"), ("team_name", "team name"), ("status", "status 1"), ("job_name", "crab job name"), ("pipeline_name", "crab pipeline name") ]) validBuildJSONTwo = JSON(dictionaryLiteral: [ ("id", 2), ("name", "name"), ("team_name", "team name"), ("status", "status 2"), ("job_name", "turtle job name"), ("pipeline_name", "turtle pipeline name") ]) validBuildJSONThree = JSON(dictionaryLiteral: [ ("id", 3), ("name", "name"), ("team_name", "team name"), ("status", "status 3"), ("job_name", "puppy job name"), ("pipeline_name", "puppy pipeline name") ]) } describe("Deserializing builds data where all individual builds are valid") { let expectedBuildOne = Build(id: 1, name: "name", teamName:"team name", jobName: "crab job name", status: .started, pipelineName: "crab pipeline name", startTime: 5, endTime: 10) let expectedBuildTwo = Build(id: 2, name: "name", teamName:"team name", jobName: "turtle job name", status: .succeeded, pipelineName: "turtle pipeline name", startTime: 5, endTime: 10) let expectedBuildThree = Build(id: 2, name: "name", teamName: "team name", jobName: "puppy job name", status: .failed, pipelineName: "puppy pipeline name", startTime: 5, endTime: 10) beforeEach { let validBuildsJSON = JSON([ validBuildJSONOne, validBuildJSONTwo, validBuildJSONThree ]) mockBuildDataDeserializer.when(validBuildJSONOne, thenReturn: expectedBuildOne) mockBuildDataDeserializer.when(validBuildJSONTwo, thenReturn: expectedBuildTwo) mockBuildDataDeserializer.when(validBuildJSONThree, thenReturn: expectedBuildThree) let validData = try! validBuildsJSON.rawData(options: .prettyPrinted) result = subject.deserialize(validData) } it("returns a build for each JSON build entry") { guard let builds = result.value else { fail("Failed to return any builds from the JSON data") return } if builds.count != 3 { fail("Expected to return 3 builds, returned \(builds.count)") return } expect(builds[0]).to(equal(expectedBuildOne)) expect(builds[1]).to(equal(expectedBuildTwo)) expect(builds[2]).to(equal(expectedBuildThree)) } it("returns no error") { expect(result.error).to(beNil()) } } describe("Deserializing builds data where one of the builds errors") { let expectedBuildOne = Build(id: 1, name: "name", teamName:"team name", jobName: "crab job name", status: .started, pipelineName: "crab pipeline name", startTime: 5, endTime: 10) let expectedBuildTwo = Build(id: 3, name: "name", teamName: "team name", jobName: "puppy job name", status: .failed, pipelineName: "puppy pipeline name", startTime: 5, endTime: 10) beforeEach { let validBuildsJSON = JSON([ validBuildJSONOne, validBuildJSONTwo, validBuildJSONThree ]) mockBuildDataDeserializer.when(validBuildJSONOne, thenReturn: expectedBuildOne) mockBuildDataDeserializer.when(validBuildJSONTwo, thenErrorWith: DeserializationError(details: "error", type: .missingRequiredData)) mockBuildDataDeserializer.when(validBuildJSONThree, thenReturn: expectedBuildTwo) let validData = try! validBuildsJSON.rawData(options: .prettyPrinted) result = subject.deserialize(validData) } it("returns a build for each valid JSON build entry") { guard let builds = result.value else { fail("Failed to return any builds from the JSON data") return } if builds.count != 2 { fail("Expected to return 2 builds, returned \(builds.count)") return } expect(builds[0]).to(equal(expectedBuildOne)) expect(builds[1]).to(equal(expectedBuildTwo)) } it("returns no error") { expect(result.error).to(beNil()) } } describe("Given data cannot be interpreted as JSON") { var result: Result<[Build], DeserializationError>! beforeEach { let buildsDataString = "some string" let invalidbuildsData = buildsDataString.data(using: String.Encoding.utf8) result = subject.deserialize(invalidbuildsData!) } it("returns nil for the builds") { expect(result.value).to(beNil()) } it("returns an error") { expect(result.error).to(equal(DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat))) } } } } }
apache-2.0
67a853ed3b3dc44b154e80f49d0e2e7c
41.783069
200
0.530299
5.759259
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/StarWars/StarWars/StarWarsGLAnimator/Vector2.swift
3
3253
// // Created by Artem Sidorenko on 10/9/15. // Copyright © 2015 Yalantis. All rights reserved. // // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at https://github.com/Yalantis/StarWars.iOS // import UIKit struct Vector2 { var x : Float32 = 0.0 var y : Float32 = 0.0 init() { x = 0.0 y = 0.0 } init(value: Float32) { x = value y = value } init(x: Float32 ,y: Float32) { self.x = x self.y = y } init(x: CGFloat, y: CGFloat) { self.init(x: Float32(x), y: Float32(y)) } init(x: Int, y: Int) { self.init(x: Float32(x), y: Float32(y)) } init(other: Vector2) { x = other.x y = other.y } init(_ other: CGPoint) { x = Float32(other.x) y = Float32(other.y) } } extension Vector2: CustomStringConvertible { var description: String { return "[\(x),\(y)]" } } extension Vector2 : Equatable { func isFinite() -> Bool { return x.isFinite && y.isFinite } func distance(_ other: Vector2) -> Float32 { let result = self - other; return sqrt( result.dot(result) ) } mutating func normalize() { let m = magnitude() if m > 0 { let il:Float32 = 1.0 / m x *= il y *= il } } func magnitude() -> Float32 { return sqrtf( x*x + y*y ) } func dot( _ v: Vector2 ) -> Float32 { return x * v.x + y * v.y } mutating func lerp( _ a: Vector2, b: Vector2, coef : Float32) { let result = a + ( b - a) * coef x = result.x y = result.y } } func ==(lhs: Vector2, rhs: Vector2) -> Bool { return (lhs.x == rhs.x) && (lhs.y == rhs.y) } func * (left: Vector2, right : Float32) -> Vector2 { return Vector2(x:left.x * right, y:left.y * right) } func * (left: Vector2, right : Vector2) -> Vector2 { return Vector2(x:left.x * right.x, y:left.y * right.y) } func / (left: Vector2, right : Float32) -> Vector2 { return Vector2(x:left.x / right, y:left.y / right) } func / (left: Vector2, right : Vector2) -> Vector2 { return Vector2(x:left.x / right.x, y:left.y / right.y) } func + (left: Vector2, right: Vector2) -> Vector2 { return Vector2(x:left.x + right.x, y:left.y + right.y) } func - (left: Vector2, right: Vector2) -> Vector2 { return Vector2(x:left.x - right.x, y:left.y - right.y) } func + (left: Vector2, right: Float32) -> Vector2 { return Vector2(x:left.x + right, y:left.y + right) } func - (left: Vector2, right: Float32) -> Vector2 { return Vector2(x:left.x - right, y:left.y - right) } func += (left: inout Vector2, right: Vector2) { left = left + right } func -= (left: inout Vector2, right: Vector2) { left = left - right } func *= (left: inout Vector2, right: Vector2) { left = left * right } func /= (left: inout Vector2, right: Vector2) { left = left / right }
apache-2.0
e134a6faa4ccb193f656c72142a47a15
18.357143
75
0.509533
3.216617
false
false
false
false
WeHUD/app
weHub-ios/Gzone_App/Gzone_App/CreatePostViewController.swift
1
9145
// // CreatePostViewController.swift // Gzone_App // // Created by Lyes Atek on 06/07/2017. // Copyright © 2017 Tracy Sablon. All rights reserved. // import UIKit class CreatePostViewController : UIViewController,UITextViewDelegate{ @IBOutlet weak var rateLbl: UILabel! @IBOutlet weak var rate1: UIButton! @IBOutlet weak var rate2: UIButton! @IBOutlet weak var rate3: UIButton! @IBOutlet weak var rate4: UIButton! @IBOutlet weak var rate5: UIButton! @IBOutlet weak var videoBtn: UIButton! @IBOutlet weak var gameBtn: UIButton! @IBOutlet weak var userBtn: UIButton! @IBOutlet weak var url: UITextField! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var viewSegmentControl: UISegmentedControl! @IBOutlet weak var textPost: UITextView! var placeHolderUserComment : String = "Ajouter un commentaire" var isGame : Bool = false var rates : [UIButton] = [] var note : Int = 0 var user : User? var game : Game? var typePost : Int = 0 var isPost : Bool = true override func viewDidLoad() { super.viewDidLoad() self.initializeViewSegmentControl(isPost: isPost) self.initializeRates() self.initializeRatting(note: note) self.displayPostView(display: isPost) self.selectTypePost(typePost: typePost) self.view.closeTextField() } func initializeRatting(note : Int){ if(note == 0){ return } for i in 0 ..< (note) { self.rates[i].setImage(UIImage(named: "starFill.png"), for: .normal) } } func initializeViewSegmentControl(isPost : Bool){ if(isPost){ self.viewSegmentControl.selectedSegmentIndex = 0 }else{ self.viewSegmentControl.selectedSegmentIndex = 1 } } func selectTypePost(typePost : Int){ switch typePost { case 0: self.videoBtn.isSelected = false self.gameBtn.isSelected = false self.userBtn.isSelected = false case 1: self.videoBtn.isSelected = true self.gameBtn.isSelected = false self.userBtn.isSelected = false case 2: self.videoBtn.isSelected = false self.gameBtn.isSelected = true self.userBtn.isSelected = false case 3: self.videoBtn.isSelected = false self.gameBtn.isSelected = false self.userBtn.isSelected = true default: break } } func initializeRates(){ rates.append(rate1) rates.append(rate2) rates.append(rate3) rates.append(rate4) rates.append(rate5) } func setImageRates(){ for i in 0 ..< self.rates.count { self.rates[i].setImage(UIImage(named: "star.png"), for: .normal) } } //Function for placeHolder func createPlaceHolder(){ self.textPost.text = "Aujouter un commentaire" self.textPost.textColor = UIColor.lightGray } func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { self.createPlaceHolder() } } func textViewDidBeginEditing(_ textView: UITextView) { if self.textPost.textColor == UIColor.lightGray { self.textPost.text = nil self.textPost.textColor = UIColor.black } } @IBAction func rattingAction(_ sender: UIButton) { setImageRates() for i in 0 ..< self.rates.count { if(sender != self.rates[i]){ self.rates[i].setImage(UIImage(named: "starFill.png"), for: .normal) }else if(sender == self.rates[i]){ self.rates[i].setImage(UIImage(named: "starFill.png"), for: .normal) self.note = i + 1 return } } } @IBAction func indexChanged(_ sender: Any) { if(self.viewSegmentControl.selectedSegmentIndex == 0){ self.displayPostView(display: true) }else{ self.displayPostView(display: false) } } func displayPostView(display : Bool){ self.rate1.isHidden = display self.rate2.isHidden = display self.rate3.isHidden = display self.rate4.isHidden = display self.rate5.isHidden = display self.rateLbl.isHidden = display self.url.isHidden = !display self.videoBtn.isHidden = !display self.userBtn.isHidden = !display self.textPost.text = "" self.isPost = display } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "ListGame"){ let viewController = segue.destination as! ListGameViewController if(self.viewSegmentControl.selectedSegmentIndex == 0){ viewController.isPost = true }else{ viewController.isPost = false } viewController.note = self.note }else{ let viewController = segue.destination as! ListUserViewController if(self.viewSegmentControl.selectedSegmentIndex == 0){ viewController.isPost = true }else{ viewController.isPost = false } } } //Button Action @IBAction func VideoBtnClick(_ sender: Any) { self.url.isHidden = false self.typePost = 1 self.selectTypePost(typePost: typePost) } func sendPostGame(){ let postsWB : WBPost = WBPost() postsWB.addPostGame(userId: AuthenticationService.sharedInstance.currentUser!._id, text: self.textPost.text, author: AuthenticationService.sharedInstance.currentUser!.username, gameId: (self.game?._id)!, accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in if(result){ print(result) } } } func sendPost(){ let postsWB : WBPost = WBPost() if(self.url.text == ""){ postsWB.addPost(userId: AuthenticationService.sharedInstance.currentUser!._id, text: self.textPost.text, author: AuthenticationService.sharedInstance.currentUser!.username,accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in print(result) } }else { postsWB.addPostVideo(userId: AuthenticationService.sharedInstance.currentUser!._id, text: self.textPost.text, author: AuthenticationService.sharedInstance.currentUser!.username, accessToken: AuthenticationService.sharedInstance.accessToken!, video: self.url.text!){ (result: Bool) in print(result) } } } func sendPostUser(){ let postsWB : WBPost = WBPost() postsWB.addPostUser(userId: AuthenticationService.sharedInstance.currentUser!._id, text: self.textPost.text, author: AuthenticationService.sharedInstance.currentUser!.username, receiverId:(self.user?._id)!, accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in print(result) } } func sendOpinion(){ let postsWB : WBPost = WBPost() postsWB.addPostOpinion(userId: AuthenticationService.sharedInstance.currentUser!._id, text: self.textPost.text, gameId: (self.game?._id)!, author: AuthenticationService.sharedInstance.currentUser!.username, mark: self.note.description, flagOpinion: "true", accessToken: AuthenticationService.sharedInstance.accessToken!){ (result: Bool) in print(result) } } @IBAction func sendPost(_ sender: Any) { if(self.textPost.text == ""){ emptyFields(title: "Post", message: "Please write a post") return; } if(self.viewSegmentControl.selectedSegmentIndex == 0){ switch self.typePost { case 0: self.sendPost() case 1: self.sendPost() case 2: self.sendPostGame() case 3: self.sendPostUser() default: break } }else{ self.sendOpinion() } let storyboard = UIStoryboard(name: "Home", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "Home_ID") as! UITabBarController let topViewController = UIApplication.shared.keyWindow?.rootViewController topViewController?.present(vc, animated: true, completion: nil) self.present(vc, animated: true, completion: nil) } }
bsd-3-clause
b3237c92b8832db6b891b593fde75468
31.657143
329
0.587708
4.996721
false
false
false
false
KaushalElsewhere/AllHandsOn
PageViewControllerDemo/PageViewControllerDemo/ViewController.swift
1
2757
// // ViewController.swift // PageViewControllerDemo // // Created by Kaushal Elsewhere on 23/08/2016. // Copyright © 2016 Kaushal Elsewhere. All rights reserved. // import UIKit //MARK: Methods extension ViewController{ // func animateImage() { // counter = counter + 1 // let index = counter % self.dataSource.count // self.baseBackgroundView.frame = CGRect(x: 0, y: 0, width: self.baseBackgroundView.frame.size.width, height: self.baseBackgroundView.frame.size.height) // //self.baseBackgroundView.layer.removeAllAnimations() // // UIView.transitionWithView(self.baseBackgroundView, duration: 0.6, options: [.TransitionCrossDissolve ], animations: { // self.baseBackgroundView.image = self.dataSource[index] // }, completion: nil) // // UIView.animateWithDuration(6, delay: 0, options: [.CurveEaseIn ], animations: { // self.baseBackgroundView.frame = CGRect(x: -50, y: -30, width: self.baseBackgroundView.frame.size.width, height: self.baseBackgroundView.frame.size.height) // self.baseBackgroundView.image = self.dataSource[index] // // // }, completion:nil) // } } //MARK: setups extension ViewController { override func viewDidLoad() { super.viewDidLoad() view.addSubview(baseBackgroundView) baseBackgroundView.start() //// let transition = CATransition() //// transition.duration = 1 //// transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) //[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; //// transition.type = kCATransitionFade; //// //// baseBackgroundView.layer.addAnimation(transition, forKey: nil) // // // animateImage() // NSTimer.scheduledTimerWithTimeInterval(6, target: self, selector: #selector(animateImage), userInfo: nil, repeats: true) } } class ViewController: UIViewController { var counter:Int = -1 let dataSource:[UIImage] = [ UIImage(named: "onb0")!, UIImage(named: "onb1")!, UIImage(named: "onb2")!, UIImage(named: "onb3")! ] lazy var baseBackgroundView:SlideImageView = { let view:SlideImageView = SlideImageView(images: self.dataSource) view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width+100, height: self.view.frame.size.height+100) view.contentMode = .ScaleAspectFill view.image = self.dataSource[0] return view }() } //dispatch_async(dispatch_get_main_queue(),{[unowned self] in // let i = (index+1) % self.dataSource.count // self.animateImage(i) // })
mit
5e2ec4223166d90200a5028703de9c97
34.805195
184
0.646589
4.253086
false
false
false
false
BenEmdon/swift-algorithm-club
All-Pairs Shortest Paths/APSP/APSP/Helpers.swift
1
1346
// // Helpers.swift // APSP // // Created by Andrew McKnight on 5/6/16. // import Foundation /** Print a matrix, optionally specifying only the cells to display with the triplet (i, j, k) -> matrix[i][j], matrix[i][k], matrix[k][j] */ func printMatrix(matrix: [[Double]], i: Int = -1, j: Int = -1, k: Int = -1) { if i >= 0 { print(" k: \(k); i: \(i); j: \(j)\n") } var grid = [String]() let n = matrix.count for x in 0..<n { var row = "" for y in 0..<n { if i < 0 || ( x == i && y == j ) || ( x == i && y == k ) || ( x == k && y == j ) { let value = NSString(format: "%.1f", matrix[x][y]) row += "\(matrix[x][y] >= 0 ? " " : "")\(value) " } else { row += " . " } } grid.append(row) } print((grid as NSArray).componentsJoinedByString("\n")) print(" =======================") } func printIntMatrix(matrix: [[Int?]]) { var grid = [String]() let n = matrix.count for x in 0..<n { var row = "" for y in 0..<n { if let value = matrix[x][y] { let valueString = NSString(format: "%i", value) row += "\(matrix[x][y] >= 0 ? " " : "")\(valueString) " } else { row += " ø " } } grid.append(row) } print((grid as NSArray).componentsJoinedByString("\n")) print(" =======================") }
mit
7d863064670d2ab1d701ae3cf6009556
21.79661
135
0.458736
3.106236
false
false
false
false
dreamsxin/swift
stdlib/public/core/AssertCommon.swift
3
8154
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Implementation Note: this file intentionally uses very LOW-LEVEL // CONSTRUCTS, so that assert and fatal may be used liberally in // building library abstractions without fear of infinite recursion. // // FIXME: We could go farther with this simplification, e.g. avoiding // UnsafeMutablePointer @_transparent public // @testable func _isDebugAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 0 } @_versioned @_transparent internal func _isReleaseAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 1 } @_transparent public // @testable func _isFastAssertConfiguration() -> Bool { // The values for the assert_configuration call are: // 0: Debug // 1: Release // 2: Fast return Int32(Builtin.assert_configuration()) == 2 } @_transparent public // @testable func _isStdlibInternalChecksEnabled() -> Bool { #if INTERNAL_CHECKS_ENABLED return true #else return false #endif } @_versioned @_transparent internal func _fatalErrorFlags() -> UInt32 { // The current flags are: // (1 << 0): Report backtrace on fatal error #if os(iOS) || os(tvOS) || os(watchOS) return 0 #else return _isDebugAssertConfiguration() ? 1 : 0 #endif } @_silgen_name("_swift_stdlib_reportFatalErrorInFile") func _reportFatalErrorInFile( // FIXME(ABI): add argument labels to conform to API guidelines. _ prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, flags: UInt32) @_silgen_name("_swift_stdlib_reportFatalError") func _reportFatalError( // FIXME(ABI): add argument labels to conform to API guidelines. _ prefix: UnsafePointer<UInt8>, _ prefixLength: UInt, _ message: UnsafePointer<UInt8>, _ messageLength: UInt, flags: UInt32) @_versioned @_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile") func _reportUnimplementedInitializerInFile( // FIXME(ABI): add argument labels to conform to API guidelines. _ className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, _ file: UnsafePointer<UInt8>, _ fileLength: UInt, _ line: UInt, _ column: UInt, flags: UInt32) @_versioned @_silgen_name("_swift_stdlib_reportUnimplementedInitializer") func _reportUnimplementedInitializer( // FIXME(ABI): add argument labels to conform to API guidelines. _ className: UnsafePointer<UInt8>, _ classNameLength: UInt, _ initName: UnsafePointer<UInt8>, _ initNameLength: UInt, flags: UInt32) /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and inlining just /// bloats code. @_versioned @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( // FIXME(ABI): add argument labels to conform to API guidelines. _ prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in message.withUTF8Buffer { (message) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress!, UInt(prefix.count), message.baseAddress!, UInt(message.count), file.baseAddress!, UInt(file.count), line, flags: flags) Builtin.int_trap() } } } Builtin.int_trap() } /// This function should be used only in the implementation of user-level /// assertions. /// /// This function should not be inlined because it is cold and inlining just /// bloats code. @_versioned @noreturn @inline(never) @_semantics("stdlib_binary_only") func _assertionFailed( // FIXME(ABI): add argument labels to conform to API guidelines. _ prefix: StaticString, _ message: String, _ file: StaticString, _ line: UInt, flags: UInt32 ) { prefix.withUTF8Buffer { (prefix) -> Void in message._withUnsafeBufferPointerToUTF8 { (messageUTF8) -> Void in file.withUTF8Buffer { (file) -> Void in _reportFatalErrorInFile( prefix.baseAddress!, UInt(prefix.count), messageUTF8.baseAddress!, UInt(messageUTF8.count), file.baseAddress!, UInt(file.count), line, flags: flags) } } } Builtin.int_trap() } /// This function should be used only in the implementation of stdlib /// assertions. /// /// This function should not be inlined because it is cold and it inlining just /// bloats code. @_versioned @noreturn @inline(never) @_semantics("stdlib_binary_only") @_semantics("arc.programtermination_point") func _fatalErrorMessage( // FIXME(ABI): add argument labels to conform to API guidelines. _ prefix: StaticString, _ message: StaticString, _ file: StaticString, _ line: UInt, flags: UInt32 ) { #if INTERNAL_CHECKS_ENABLED prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in file.withUTF8Buffer { (file) in _reportFatalErrorInFile( prefix.baseAddress!, UInt(prefix.count), message.baseAddress!, UInt(message.count), file.baseAddress!, UInt(file.count), line, flags: flags) } } } #else prefix.withUTF8Buffer { (prefix) in message.withUTF8Buffer { (message) in _reportFatalError( prefix.baseAddress!, UInt(prefix.count), message.baseAddress!, UInt(message.count), flags: flags) } } #endif Builtin.int_trap() } // FIXME(ABI): rename to lower camel case to conform to API guidelines. /// Prints a fatal error message when an unimplemented initializer gets /// called by the Objective-C runtime. @_transparent @noreturn public // COMPILER_INTRINSIC func _unimplemented_initializer(className: StaticString, initName: StaticString = #function, file: StaticString = #file, line: UInt = #line, column: UInt = #column) { // This function is marked @_transparent so that it is inlined into the caller // (the initializer stub), and, depending on the build configuration, // redundant parameter values (#file etc.) are eliminated, and don't leak // information about the user's source. if _isDebugAssertConfiguration() { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in file.withUTF8Buffer { (file) in _reportUnimplementedInitializerInFile( className.baseAddress!, UInt(className.count), initName.baseAddress!, UInt(initName.count), file.baseAddress!, UInt(file.count), line, column, flags: 0) } } } } else { className.withUTF8Buffer { (className) in initName.withUTF8Buffer { (initName) in _reportUnimplementedInitializer( className.baseAddress!, UInt(className.count), initName.baseAddress!, UInt(initName.count), flags: 0) } } } Builtin.int_trap() } // FIXME(ABI): rename to something descriptive. @noreturn public // COMPILER_INTRINSIC func _undefined<T>( _ message: @autoclosure () -> String = String(), file: StaticString = #file, line: UInt = #line ) -> T { _assertionFailed("fatal error", message(), file, line, flags: 0) }
apache-2.0
805d7ba3c7e9bfa004820888df56d849
29.2
80
0.659676
4.282563
false
false
false
false
dreamsxin/swift
stdlib/public/core/Join.swift
1
6227
//===--- Join.swift - Protocol and Algorithm for concatenation ------------===// // // 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 // //===----------------------------------------------------------------------===// internal enum _JoinIteratorState { case start case generatingElements case generatingSeparator case end } /// An iterator that presents the elements of the sequences traversed /// by `Base`, concatenated using a given separator. public struct JoinedIterator<Base : IteratorProtocol> : IteratorProtocol where Base.Element : Sequence { /// Creates an iterator that presents the elements of the sequences /// traversed by `base`, concatenated using `separator`. /// /// - Complexity: O(`separator.count`). public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Iterator.Element == Base.Element.Iterator.Element { self._base = base self._separatorData = ContiguousArray(separator) } /// 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`. public mutating func next() -> Base.Element.Iterator.Element? { repeat { switch _state { case .start: if let nextSubSequence = _base.next() { _inner = nextSubSequence.makeIterator() _state = .generatingElements } else { _state = .end return nil } case .generatingElements: let result = _inner!.next() if _fastPath(result != nil) { return result } _inner = _base.next()?.makeIterator() if _inner == nil { _state = .end return nil } if !_separatorData.isEmpty { _separator = _separatorData.makeIterator() _state = .generatingSeparator } case .generatingSeparator: let result = _separator!.next() if _fastPath(result != nil) { return result } _state = .generatingElements case .end: return nil } } while true } internal var _base: Base internal var _inner: Base.Element.Iterator? internal var _separatorData: ContiguousArray<Base.Element.Iterator.Element> internal var _separator: ContiguousArray<Base.Element.Iterator.Element>.Iterator? internal var _state: _JoinIteratorState = .start } /// A sequence that presents the elements of the `Base` sequences /// concatenated using a given separator. public struct JoinedSequence<Base : Sequence> : Sequence where Base.Iterator.Element : Sequence { /// Creates a sequence that presents the elements of `base` sequences /// concatenated using `separator`. /// /// - Complexity: O(`separator.count`). public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Iterator.Element == Base.Iterator.Element.Iterator.Element { self._base = base self._separator = ContiguousArray(separator) } /// Return an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> JoinedIterator<Base.Iterator> { return JoinedIterator( base: _base.makeIterator(), separator: _separator) } public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Base.Iterator.Element.Iterator.Element> { var result = ContiguousArray<Iterator.Element>() let separatorSize: Int = numericCast(_separator.count) let reservation = _base._preprocessingPass { () -> Int in var r = 0 for chunk in _base { r += separatorSize + chunk.underestimatedCount } return r - separatorSize } if let n = reservation { result.reserveCapacity(numericCast(n)) } if separatorSize == 0 { for x in _base { result.append(contentsOf: x) } return result._buffer } var iter = _base.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: _separator) result.append(contentsOf: next) } } return result._buffer } internal var _base: Base internal var _separator: ContiguousArray<Base.Iterator.Element.Iterator.Element> } extension Sequence where Iterator.Element : Sequence { /// Returns the concatenated elements of this sequence of sequences, /// inserting the given separator between each element. /// /// This example shows how an array of `[Int]` instances can be joined, using /// another `[Int]` instance as the separator: /// /// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] /// let joined = nestedNumbers.join(separator: [-1, -2]) /// print(Array(joined)) /// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]" /// /// - Parameter separator: A sequence to insert between each of this /// sequence's elements. /// - Returns: The joined sequence of elements. /// /// - SeeAlso: `flatten()` public func joined<Separator : Sequence>( separator: Separator ) -> JoinedSequence<Self> where Separator.Iterator.Element == Iterator.Element.Iterator.Element { return JoinedSequence(base: self, separator: separator) } } @available(*, unavailable, renamed: "JoinedIterator") public struct JoinGenerator<Base : IteratorProtocol> where Base.Element : Sequence {} extension JoinedSequence { @available(*, unavailable, renamed: "makeIterator") public func generate() -> JoinedIterator<Base.Iterator> { Builtin.unreachable() } } extension Sequence where Iterator.Element : Sequence { @available(*, unavailable, renamed: "joined") public func joinWithSeparator<Separator : Sequence>( _ separator: Separator ) -> JoinedSequence<Self> where Separator.Iterator.Element == Iterator.Element.Iterator.Element { Builtin.unreachable() } }
apache-2.0
3e49815e4665363e6af8491d679422b5
30.291457
80
0.648788
4.457409
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document11.playgroundchapter/Pages/Challenge1.playgroundpage/Contents.swift
1
1684
//#-hidden-code // // Contents.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // //#-end-hidden-code /*: **Challenge:** Create an instance of type `Expert` and use the expert to solve the puzzle. Use this challenge to practice initializing an instance of your expert. As you write a solution to the puzzle, remember what you’ve learned about factoring your code into clear and [reusable](glossary://reusability) functions. * callout(New Ability): In addition to `turnLockUp()`, you can also use `turnLockDown()` to move a platform down from its current position. Start by [initializing](glossary://initialization) an instance of your expert. Direct your expert to move around, collect the gems, and toggle open the switches. Then have your expert turn the lock to reveal the path to the disconnected platforms. */ //#-code-completion(everything, hide) //#-code-completion(currentmodule, show) //#-code-completion(identifier, show, isOnOpenSwitch, if, func, for, while, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, Expert, Character, (, ), (), turnLockUp(), turnLockDown(), isOnClosedSwitch, var, ., let, =, <, >, ==, !=, +, -, isBlocked, true, false, isBlockedLeft, &&, ||, !, isBlockedRight) //#-hidden-code playgroundPrologue() typealias Character = Actor //#-end-hidden-code //#-editable-code Initialize your expert here let expert = <#initialize#> //#-end-editable-code //#-hidden-code world.place(expert, facing: west, at: Coordinate(column: 3, row: 2)) //#-end-hidden-code //#-editable-code Enter the rest of your solution here //#-end-editable-code //#-hidden-code playgroundEpilogue() //#-end-hidden-code
mit
e01b64df9fbee5610aec6a58af221d52
43.263158
333
0.719976
4.102439
false
false
false
false
Swift-Flow/CounterExample
Carthage/Checkouts/ReSwift-Router/ReSwiftRouterTests/ReSwiftRouterIntegrationTests.swift
3
9794
// // SwiftFlowRouterTests.swift // SwiftFlowRouterTests // // Created by Benjamin Encz on 12/2/15. // Copyright © 2015 DigiTales. All rights reserved. // import Quick import Nimble import ReSwift @testable import ReSwiftRouter class MockRoutable: Routable { var callsToPushRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = [] var callsToPopRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = [] var callsToChangeRouteSegment: [( from: RouteElementIdentifier, to: RouteElementIdentifier, animated: Bool )] = [] func pushRouteSegment( _ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler ) -> Routable { callsToPushRouteSegment.append( (routeElement: routeElementIdentifier, animated: animated) ) completionHandler() return MockRoutable() } func popRouteSegment( _ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) { callsToPopRouteSegment.append( (routeElement: routeElementIdentifier, animated: animated) ) completionHandler() } func changeRouteSegment( _ from: RouteElementIdentifier, to: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler ) -> Routable { completionHandler() callsToChangeRouteSegment.append((from: from, to: to, animated: animated)) return MockRoutable() } } struct FakeAppState: StateType { var navigationState = NavigationState() } func fakeReducer(action: Action, state: FakeAppState?) -> FakeAppState { return state ?? FakeAppState() } func appReducer(action: Action, state: FakeAppState?) -> FakeAppState { return FakeAppState( navigationState: NavigationReducer.handleAction(action, state: state?.navigationState) ) } class SwiftFlowRouterIntegrationTests: QuickSpec { override func spec() { describe("routing calls") { var store: Store<FakeAppState>! beforeEach { store = Store(reducer: appReducer, state: FakeAppState()) } describe("setup") { it("does not request the root view controller when no route is provided") { class FakeRootRoutable: Routable { var called = false func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, completionHandler: RoutingCompletionHandler) -> Routable { called = true return MockRoutable() } } let routable = FakeRootRoutable() let _ = Router(store: store, rootRoutable: routable) { state in state.select { $0.navigationState } } expect(routable.called).to(beFalse()) } it("requests the root with identifier when an initial route is provided") { store.dispatch( SetRouteAction( ["TabBarViewController"] ) ) class FakeRootRoutable: Routable { var calledWithIdentifier: (RouteElementIdentifier?) -> Void init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) { self.calledWithIdentifier = calledWithIdentifier } func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) -> Routable { calledWithIdentifier(routeElementIdentifier) completionHandler() return MockRoutable() } } waitUntil(timeout: 2.0) { fullfill in let rootRoutable = FakeRootRoutable { identifier in if identifier == "TabBarViewController" { fullfill() } } let _ = Router(store: store, rootRoutable: rootRoutable) { state in state.select { $0.navigationState } } } } it("calls push on the root for a route with two elements") { store.dispatch( SetRouteAction( ["TabBarViewController", "SecondViewController"] ) ) class FakeChildRoutable: Routable { var calledWithIdentifier: (RouteElementIdentifier?) -> Void init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) { self.calledWithIdentifier = calledWithIdentifier } func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) -> Routable { calledWithIdentifier(routeElementIdentifier) completionHandler() return MockRoutable() } } waitUntil(timeout: 5.0) { completion in let fakeChildRoutable = FakeChildRoutable() { identifier in if identifier == "SecondViewController" { completion() } } class FakeRootRoutable: Routable { let injectedRoutable: Routable init(injectedRoutable: Routable) { self.injectedRoutable = injectedRoutable } func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier, animated: Bool, completionHandler: @escaping RoutingCompletionHandler) -> Routable { completionHandler() return injectedRoutable } } let _ = Router(store: store, rootRoutable: FakeRootRoutable(injectedRoutable: fakeChildRoutable)) { state in state.select { $0.navigationState } } } } } } describe("route specific data") { var store: Store<FakeAppState>! beforeEach { store = Store(reducer: appReducer, state: nil) } context("when setting route specific data") { beforeEach { store.dispatch(SetRouteSpecificData(route: ["part1", "part2"], data: "UserID_10")) } it("allows accessing the data when providing the expected type") { let data: String? = store.state.navigationState.getRouteSpecificState( ["part1", "part2"] ) expect(data).toEventually(equal("UserID_10")) } } } describe("configuring animated/unanimated navigation") { var store: Store<FakeAppState>! var mockRoutable: MockRoutable! var router: Router<FakeAppState>! beforeEach { store = Store(reducer: appReducer, state: nil) mockRoutable = MockRoutable() router = Router(store: store, rootRoutable: mockRoutable) { state in state.select { $0.navigationState } } // silence router not read warning, need to keep router alive via reference _ = router } context("when dispatching an animated route change") { beforeEach { store.dispatch(SetRouteAction(["someRoute"], animated: true)) } it("calls routables asking for an animated presentation") { expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue()) } } context("when dispatching an unanimated route change") { beforeEach { store.dispatch(SetRouteAction(["someRoute"], animated: false)) } it("calls routables asking for an animated presentation") { expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beFalse()) } } context("when dispatching a default route change") { beforeEach { store.dispatch(SetRouteAction(["someRoute"])) } it("calls routables asking for an animated presentation") { expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue()) } } } } }
mit
34ad2e0a701d169cc99453f5541fc5eb
33.850534
180
0.512815
6.829149
false
false
false
false
rnystrom/GitHawk
Classes/Utility/URLBuilder.swift
1
1605
// // URLBuilder.swift // Freetime // // Created by Ryan Nystrom on 11/10/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation final class URLBuilder { private var components = URLComponents() private var pathComponents = [String]() init(host: String, scheme: String) { components.host = host components.scheme = scheme } convenience init(host: String, https: Bool = true) { self.init(host: host, scheme: https ? "https" : "http") } static func github() -> URLBuilder { return URLBuilder(host: "github.com", https: true) } @discardableResult func add(path: LosslessStringConvertible) -> URLBuilder { pathComponents.append(String(describing: path)) return self } @discardableResult func add(paths: [LosslessStringConvertible]) -> URLBuilder { paths.forEach { self.add(path: $0) } return self } @discardableResult func add(item: String, value: LosslessStringConvertible) -> URLBuilder { var items = components.queryItems ?? [] items.append(URLQueryItem(name: item, value: String(describing: value))) components.queryItems = items return self } @discardableResult func set(fragment: String) -> URLBuilder { components.fragment = fragment return self } var url: URL? { var components = self.components if !pathComponents.isEmpty { components.path = "/" + pathComponents.joined(separator: "/") } return components.url } }
mit
7280cc898a0524d260cc8a7ee506a6cd
24.460317
80
0.626559
4.582857
false
false
false
false
saragiotto/TMDbFramework
TMDbFramework/Classes/Model/TMDbCast.swift
1
761
// // TMDbCast.swift // Pods // // Created by Leonardo Augusto N Saragiotto on 15/08/17. // // import Foundation import SwiftyJSON open class TMDbCast { public let castId: Int? public let character: String? public let creditId: String? public let gender: Int? public let id: Int? public let name: String? public let order: Int? public let profilePath: String? init(data: JSON) { castId = data["cast_id"].int character = data["character"].string creditId = data["credit_id"].string gender = data["gender"].int id = data["id"].int name = data["name"].string order = data["order"].int profilePath = data["profile_path"].string } }
mit
3d50c394f21329a6223fbae7d7ee9401
20.742857
57
0.591327
3.902564
false
false
false
false
adrfer/swift
test/SILGen/metatype_object_conversion.swift
14
1230
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s // REQUIRES: objc_interop import Foundation class C {} protocol CP : class {} @objc protocol OP {} // CHECK-LABEL: sil hidden @_TF26metatype_object_conversion16metatypeToObjectFMCS_1CPs9AnyObject_ func metatypeToObject(x: C.Type) -> AnyObject { // CHECK: bb0([[THICK:%.*]] : $@thick C.Type): // CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[THICK]] // CHECK: [[OBJECT:%.*]] = objc_metatype_to_object [[OBJC]] // CHECK: return [[OBJECT]] return x } // CHECK-LABEL: sil hidden @_TF26metatype_object_conversion27existentialMetatypeToObjectFPMPS_2CP_Ps9AnyObject_ func existentialMetatypeToObject(x: CP.Type) -> AnyObject { // CHECK: bb0([[THICK:%.*]] : $@thick CP.Type): // CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[THICK]] // CHECK: [[OBJECT:%.*]] = objc_existential_metatype_to_object [[OBJC]] // CHECK: return [[OBJECT]] return x } // CHECK-LABEL: sil hidden @_TF26metatype_object_conversion23protocolToProtocolClassFT_CSo8Protocol func protocolToProtocolClass() -> Protocol { // CHECK: [[PROTO:%.*]] = objc_protocol #OP // CHECK: return [[PROTO]] return OP.self }
apache-2.0
eb045ee4f79bb73598a477b695a92d85
33.166667
111
0.670732
3.435754
false
false
false
false
ephread/Instructions
Sources/Instructions/Helpers/Internal/ErrorMessage.swift
2
2880
// Copyright (c) 2020-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import Foundation struct ErrorMessage { struct Info { static let nilPointOfInterestZeroOffset = "[INFO] The point of interest is nil, offset will be zero." static let nilPointOfInterestCenterAlignment = "[INFO] The point of interest is nil, alignment will fall back to .center." static let skipViewNoSuperviewNotShown = "[INFO] skipView has no superview and won't be shown." static let skipViewNoSuperviewNotUpdated = "[INFO] skipView has no superview and won't be updated." } struct Warning { static let unsupportedWindowLevel = "[WARNING] Displaying Instructions over the status bar is unsupported in iOS 13+." static let nilDataSource = "[WARNING] dataSource is nil." static let noCoachMarks = "[WARNING] dataSource.numberOfCoachMarks(for:) returned 0." static let noParent = "[WARNING] View has no parent, cannot define constraints." static let frameWithNoWidth = "[WARNING] frame has no width, alignment will fall back to .center." static let negativeNumberOfCoachMarksToSkip = "[WARNING] numberToSkip is negative, ignoring." static let anchorViewIsNotInTheViewHierarchy = """ [WARNING] The view passed to the coach mark creator is not in any hierarchy, \ the resulting cutout path may not display correctly. """ } struct Error { static let couldNotBeAttached = """ [ERROR] Instructions could not be properly attached to the window \ did you call `start(in:)` inside `viewDidLoad` instead of `viewDidAppear`? """ static let notAChild = """ [WARNING] `coachMarkView` is not a child of `parentView`. \ The array of constraints will be empty. """ static let updateWentWrong = """ [ERROR] Something went wrong, did you call \ `updateCurrentCoachMark()` without pausing the controller first? """ static let overlayEmptyBounds = """ [ERROR] The overlay view added to the window has empty bounds, \ Instructions will stop. """ } struct Fatal { static let negativeNumberOfCoachMarks = "dataSource.numberOfCoachMarks(for:) returned a negative number." static let windowContextNotAvailableInAppExtensions = "PresentationContext.newWindow(above:) is not available in App Extensions." static let doesNotSupportNSCoding = "This class does not support NSCoding." } }
mit
c548eb46a4ee95de1bc80dede7ef8013
33.674699
94
0.61918
5.471483
false
false
false
false
filippotosetto/SwiftOpenWeatherMapAPI
SwiftOpenWeatherMapAPI/ViewController.swift
1
3115
// // ViewController.swift // SwiftOpenWeatherMapAPI // // Created by Filippo Tosetto on 16/04/2015. // // import UIKit import SwiftyJSON class ViewController: UIViewController { // TODO: Set correct API key let apiManager = WAPIManager(apiKey: "271537219331766fbdaf30a4ef37fb33", temperatureFormat: .Celsius, lang: .Italian) let city = "London,UK" @IBOutlet weak var cityNameLabel: UILabel! @IBOutlet weak var currentTemperatureLabel: UILabel! @IBOutlet weak var weatherDescriptionLabel: UILabel! @IBOutlet weak var tableView: UITableView! var currentWeather: Weather? { didSet { self.currentTemperatureLabel.text = (currentWeather?.temperature)! + " C" self.weatherDescriptionLabel.text = currentWeather?.description } } var weatherList = [Weather]() { didSet { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() apiManager.currentWeatherByCityNameAsJson(city, data: { (result) -> Void in switch result { case .Success(let json): self.cityNameLabel.text = json["name"].stringValue self.currentWeather = Weather(json: json) break case .Error(let errorMessage): self.showErrorAlert(errorMessage) break } }) apiManager.forecastWeatherByCityNameAsJson(city, data: { (result) -> Void in switch result { case .Success(let json): self.weatherList = json["list"].array!.map() { Weather(json: $0) } break case .Error(let errorMessage): self.showErrorAlert(errorMessage) break } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weatherList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let weather = weatherList[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) cell.textLabel?.text = weather.description + " " + weather.temperature + " C" cell.detailTextLabel?.text = weather.dateTime return cell } } extension ViewController { private func showErrorAlert(errorMessage: String) { let alertController = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
24aee424b7bebd8619126e1c2ee047c8
30.15
121
0.61862
5.217755
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/misc/MurmurHash.swift
6
5568
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// https://en.wikipedia.org/wiki/MurmurHash /// /// - Author: Sam Harwell /// public final class MurmurHash { private static let DEFAULT_SEED: UInt32 = 0 private static let c1 = UInt32(0xCC9E2D51) private static let c2 = UInt32(0x1B873593) private static let r1 = UInt32(15) private static let r2 = UInt32(13) private static let m = UInt32(5) private static let n = UInt32(0xE6546B64) /// /// Initialize the hash using the default seed value. /// /// - Returns: the intermediate hash value /// public static func initialize() -> UInt32 { return initialize(DEFAULT_SEED) } /// /// Initialize the hash using the specified `seed`. /// /// - Parameter seed: the seed /// - Returns: the intermediate hash value /// public static func initialize(_ seed: UInt32) -> UInt32 { return seed } private static func calcK(_ value: UInt32) -> UInt32 { var k = value k = k &* c1 k = (k << r1) | (k >> (32 - r1)) k = k &* c2 return k } /// /// Update the intermediate hash value for the next input `value`. /// /// - Parameter hash: the intermediate hash value /// - Parameter value: the value to add to the current hash /// - Returns: the updated intermediate hash value /// public static func update2(_ hashIn: UInt32, _ value: Int) -> UInt32 { return updateInternal(hashIn, UInt32(truncatingIfNeeded: value)) } private static func updateInternal(_ hashIn: UInt32, _ value: UInt32) -> UInt32 { let k = calcK(value) var hash = hashIn hash = hash ^ k hash = (hash << r2) | (hash >> (32 - r2)) hash = hash &* m &+ n // print("murmur update2 : \(hash)") return hash } /// /// Update the intermediate hash value for the next input `value`. /// /// - Parameter hash: the intermediate hash value /// - Parameter value: the value to add to the current hash /// - Returns: the updated intermediate hash value /// public static func update<T:Hashable>(_ hash: UInt32, _ value: T?) -> UInt32 { return update2(hash, value?.hashValue ?? 0) } /// /// Apply the final computation steps to the intermediate value `hash` /// to form the final result of the MurmurHash 3 hash function. /// /// - Parameter hash: the intermediate hash value /// - Parameter numberOfWords: the number of UInt32 values added to the hash /// - Returns: the final hash result /// public static func finish(_ hashin: UInt32, _ numberOfWords: Int) -> Int { return Int(finish(hashin, byteCount: (numberOfWords &* 4))) } private static func finish(_ hashin: UInt32, byteCount byteCountInt: Int) -> UInt32 { let byteCount = UInt32(truncatingIfNeeded: byteCountInt) var hash = hashin hash ^= byteCount hash ^= (hash >> 16) hash = hash &* 0x85EBCA6B hash ^= (hash >> 13) hash = hash &* 0xC2B2AE35 hash ^= (hash >> 16) //print("murmur finish : \(hash)") return hash } /// /// Utility function to compute the hash code of an array using the /// MurmurHash algorithm. /// /// - Parameter <T>: the array element type /// - Parameter data: the array data /// - Parameter seed: the seed for the MurmurHash algorithm /// - Returns: the hash code of the data /// public static func hashCode<T:Hashable>(_ data: [T], _ seed: Int) -> Int { var hash = initialize(UInt32(truncatingIfNeeded: seed)) for value in data { hash = update(hash, value) } return finish(hash, data.count) } /// /// Compute a hash for the given String and seed. The String is encoded /// using UTF-8, then the bytes are interpreted as unsigned 32-bit /// little-endian values, giving UInt32 values for the update call. /// /// If the bytes do not evenly divide by 4, the final bytes are treated /// slightly differently (not doing the final rotate / multiply / add). /// /// This matches the treatment of byte sequences in publicly available /// test patterns (see MurmurHashTests.swift) and the example code on /// Wikipedia. /// public static func hashString(_ s: String, _ seed: UInt32) -> UInt32 { let bytes = Array(s.utf8) return hashBytesLittleEndian(bytes, seed) } private static func hashBytesLittleEndian(_ bytes: [UInt8], _ seed: UInt32) -> UInt32 { let byteCount = bytes.count var hash = seed for i in stride(from: 0, to: byteCount - 3, by: 4) { var word = UInt32(bytes[i]) word |= UInt32(bytes[i + 1]) << 8 word |= UInt32(bytes[i + 2]) << 16 word |= UInt32(bytes[i + 3]) << 24 hash = updateInternal(hash, word) } let remaining = byteCount & 3 if remaining != 0 { var lastWord = UInt32(0) for r in 0 ..< remaining { lastWord |= UInt32(bytes[byteCount - 1 - r]) << (8 * (remaining - 1 - r)) } let k = calcK(lastWord) hash ^= k } return finish(hash, byteCount: byteCount) } private init() { } }
bsd-3-clause
f15dffdf17e9bfc40537d5d6a3c476cc
31.184971
91
0.583872
4.121392
false
false
false
false
khizkhiz/swift
test/Generics/associated_types.swift
1
3473
// RUN: %target-parse-verify-swift // Deduction of associated types. protocol Fooable { associatedtype AssocType func foo(x : AssocType) } struct X : Fooable { func foo(x: Float) {} } struct Y<T> : Fooable { func foo(x: T) {} } struct Z : Fooable { func foo(x: Float) {} func blah() { var a : AssocType // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} {{9-10=_}} } // FIXME: We should be able to find this. func blarg() -> AssocType {} // expected-error{{use of undeclared type 'AssocType'}} func wonka() -> Z.AssocType {} } var xa : X.AssocType = Float() var yf : Y<Float>.AssocType = Float() var yd : Y<Double>.AssocType = Double() var f : Float f = xa f = yf var d : Double d = yd protocol P1 { associatedtype Assoc1 func foo() -> Assoc1 } struct S1 : P1 { func foo() -> X {} } prefix operator % {} protocol P2 { associatedtype Assoc2 prefix func %(target: Self) -> Assoc2 } prefix func % <P:P1>(target: P) -> P.Assoc1 { } extension S1 : P2 { typealias Assoc2 = X } // <rdar://problem/14418181> protocol P3 { associatedtype Assoc3 func foo() -> Assoc3 } protocol P4 : P3 { associatedtype Assoc4 func bar() -> Assoc4 } func takeP4<T : P4>(x: T) { } struct S4<T> : P3, P4 { func foo() -> Int {} func bar() -> Double {} } takeP4(S4<Int>()) // <rdar://problem/14680393> infix operator ~> { precedence 255 } protocol P5 { } struct S7a {} protocol P6 { func foo<Target: P5>(target: inout Target) } protocol P7 : P6 { associatedtype Assoc : P6 func ~> (x: Self, _: S7a) -> Assoc } func ~> <T:P6>(x: T, _: S7a) -> S7b { return S7b() } struct S7b : P7 { typealias Assoc = S7b func foo<Target: P5>(target: inout Target) {} } // <rdar://problem/14685674> struct zip<A : IteratorProtocol, B : IteratorProtocol> : IteratorProtocol, Sequence { func next() -> (A.Element, B.Element)? { } typealias Generator = zip func makeIterator() -> zip { } } protocol P8 { } protocol P9 { associatedtype A1 : P8 } protocol P10 { associatedtype A1b : P8 associatedtype A2 : P9 func f() func g(a: A1b) func h(a: A2) } struct X8 : P8 { } struct Y9 : P9 { typealias A1 = X8 } struct Z10 : P10 { func f() { } func g(a: X8) { } func h(a: Y9) { } } struct W : Fooable { func foo(x: String) {} } struct V<T> : Fooable { func foo(x: T) {} } // FIXME: <rdar://problem/16123805> Inferred associated types can't be used in expression contexts var w = W.AssocType() var v = V<String>.AssocType() // // SR-427 protocol A { func c() // expected-note {{protocol requires function 'c()' with type '() -> ()'}} } protocol B : A { associatedtype e : A = C<Self> // expected-note {{default type 'C<C<a>>' for associated type 'e' (from protocol 'B') does not conform to 'A'}} } extension B { func c() { // expected-note {{candidate has non-matching type '<Self> () -> ()' (aka '<τ_0_0> () -> ()')}} } } struct C<a : B> : B { // expected-error {{type 'C<a>' does not conform to protocol 'B'}} expected-error {{type 'C<a>' does not conform to protocol 'A'}} } // SR-511 protocol sr511 { typealias Foo // expected-warning {{use of 'typealias' to declare associated types is deprecated; use 'associatedtype' instead}} {{3-12=associatedtype}} } associatedtype Foo = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}}
apache-2.0
60c6edc571b04ac62ddbb88c711ae618
18.288889
181
0.627016
3.034965
false
false
false
false
richa008/PitchPerfect
PitchPerfect/PitchPerfect/RecordSoundViewController.swift
1
2583
// // ViewController.swift // PitchPerfect // // Created by Deshmukh,Richa on 4/17/16. // Copyright © 2016 Richa. All rights reserved. // import UIKit import AVFoundation class RecordSoundViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var recordingLabel: UILabel! var audioRecorder: AVAudioRecorder! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { stopButton.enabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func recordAudio(sender: AnyObject) { recordingLabel.text = "Recording..." recordButton.enabled = false stopButton.enabled = true let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let recordingName = "recordedVoice.wav" let pathArray = [dirPath, recordingName] let filePath = NSURL.fileURLWithPathComponents(pathArray) print(filePath) let session = AVAudioSession.sharedInstance() try! session.setCategory(AVAudioSessionCategoryPlayAndRecord) try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:]) audioRecorder.delegate = self; audioRecorder.meteringEnabled = true audioRecorder.prepareToRecord() audioRecorder.record() } @IBAction func stopRecording(sender: AnyObject) { recordingLabel.text = "Tap to record" recordButton.enabled = true stopButton.enabled = false audioRecorder.stop() let audioSession = AVAudioSession.sharedInstance() try! audioSession.setActive(false) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "stopRecordingSegue"){ let playSoundVC = segue.destinationViewController as! PlaySoundViewController let recordedAudioURL = sender as! NSURL playSoundVC.recordedAudioURL = recordedAudioURL } } // MARK: - Audio recorder delegate functions func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) { if(flag){ self.performSegueWithIdentifier("stopRecordingSegue", sender: audioRecorder.url) }else{ print("Saving failed") } } }
mit
d050f8c8d54d7632cb0a722b9307cc5e
29.738095
103
0.662665
5.674725
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/PBMVideoViewTest.swift
1
17059
/*   Copyright 2018-2021 Prebid.org, 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 XCTest @testable import PrebidMobile class PBMVideoViewTest: XCTestCase, PBMCreativeResolutionDelegate, PBMCreativeViewDelegate, PBMVideoViewDelegate { var vc: UIViewController? let connection = UtilitiesForTesting.createConnectionForMockedTest() var videoCreative:PBMVideoCreative! var expectationDownloadCompleted:XCTestExpectation? var expectationCreativeReady:XCTestExpectation? var expectationCreativeDidComplete:XCTestExpectation? var expectationCreativeWasClicked:XCTestExpectation? var expectationClickthroughBrowserClosed:XCTestExpectation? var expectationVideoViewCompletedDisplay:XCTestExpectation? var isVideoViewCompletedDisplay = false; // MARK: - Setup override func setUp() { MockServer.shared.reset() } override func tearDown() { MockServer.shared.reset() self.videoCreative = nil self.expectationDownloadCompleted = nil self.expectationCreativeReady = nil self.expectationCreativeDidComplete = nil self.expectationCreativeWasClicked = nil self.expectationClickthroughBrowserClosed = nil self.expectationVideoViewCompletedDisplay = nil } // MARK: - Tests func testLearnMoreButton() { self.setupVideoCreative() self.videoCreative.creativeModel!.clickThroughURL = "www.openx.com" self.vc = UIViewController() //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 15, handler:nil) //Wait half a second, then force a click self.vc?.view.addSubview(videoCreative.view!) self.videoCreative?.display(withRootViewController: UIViewController()) self.expectationCreativeWasClicked = expectation(description: "expectationCreativeWasClicked") DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { [weak self] in guard let strongSelf = self else { XCTFail("Self deallocated") return } guard let videoView = strongSelf.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.btnLearnMoreClick() }) self.waitForExpectations(timeout: 15, handler:nil) } func testVastDuration() { // Expected duration of video medium.mp4 is 60 sec let expectedVastDuration = 10.0 setupVideoCreative(videoFileURL: "http://get_video/medium.mp4", localVideoFileName: "medium.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVastDuration as NSNumber // VAST Duration setupVideoDurationTest(expectedDuration: expectedVastDuration) } func testVideoDuration() { // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = 10 // VAST Duration setupVideoDurationTest(expectedDuration: expectedVideoDuration) } func testPauseVideo() { // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVideoDuration as NSNumber //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 10, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) guard let videoView = self.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.videoViewDelegate = self self.expectationVideoViewCompletedDisplay = expectation(description: "expectationVideoViewCompletedDisplay") self.expectationVideoViewCompletedDisplay?.isInverted = true DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute:{ XCTAssertFalse(self.isVideoViewCompletedDisplay) videoView.pause() }) waitForExpectations(timeout: 8, handler:nil) } func testUnpauseVideo() { // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 let expectedPausedTime = 3.0 setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVideoDuration as NSNumber //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 10, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) guard let videoView = self.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.videoViewDelegate = self self.expectationVideoViewCompletedDisplay = expectation(description: "expectationVideoViewCompletedDisplay") // Pause video DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute:{ XCTAssertFalse(self.isVideoViewCompletedDisplay) videoView.pause() // Unpause video DispatchQueue.main.asyncAfter(deadline: .now() + expectedPausedTime, execute:{ XCTAssertFalse(self.isVideoViewCompletedDisplay) videoView.resume() }) }) waitForExpectations(timeout: expectedVideoDuration + expectedPausedTime + 0.5, handler:nil) } func testStopVideo() { // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 let expectedStoppedDely = 3.0 setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVideoDuration as NSNumber //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 10, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) guard let videoView = self.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.videoViewDelegate = self self.expectationVideoViewCompletedDisplay = expectation(description: "expectationVideoViewCompletedDisplay") DispatchQueue.main.asyncAfter(deadline: .now() + expectedStoppedDely, execute:{ XCTAssertFalse(self.isVideoViewCompletedDisplay) videoView.stop() }) waitForExpectations(timeout: expectedVideoDuration + expectedStoppedDely + 0.5, handler:nil) } func testStopOnCloseButton() { // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 let expectedStoppedDely = 1.0 let event = PBMTrackingEvent.closeLinear setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVideoDuration as NSNumber //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 10, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) guard let videoView = self.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.videoViewDelegate = self self.expectationVideoViewCompletedDisplay = expectation(description: "expectationVideoViewCompletedDisplay") self.expectationVideoViewCompletedDisplay?.isInverted = true DispatchQueue.main.asyncAfter(deadline: .now() + expectedStoppedDely, execute:{ videoView.stop(onCloseButton: event) XCTAssertFalse(self.isVideoViewCompletedDisplay) }) waitForExpectations(timeout: expectedVideoDuration + expectedStoppedDely + 0.5, handler:nil) } func testIsMuted() { let adConfig = AdConfiguration() XCTAssertTrue(adConfig.videoControlsConfig.isMuted == false) // Expected duration of video small.mp4 is 6 sec let expectedVideoDuration = 6.0 setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") self.videoCreative.creativeModel!.displayDurationInSeconds = expectedVideoDuration as NSNumber //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 10, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) XCTAssertTrue(self.videoCreative.videoView.avPlayer.isMuted == false) } func testSetupSkipButton() { setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") guard let videoView = self.videoCreative.videoView else { XCTFail() return } XCTAssertEqual(videoView.skipButtonDecorator.buttonArea, 0.1) XCTAssertEqual(videoView.skipButtonDecorator.buttonPosition, .topLeft) XCTAssertEqual(videoView.skipButtonDecorator.button.image(for: .normal), UIImage(named: "PBM_skipButton", in: PBMFunctions.bundleForSDK(), compatibleWith: nil)) XCTAssertEqual(videoView.skipButtonDecorator.button.isHidden, true) } func testHandleSkipDelay() { let expectation = expectation(description: "Test Skip Button Active") setupVideoCreative(videoFileURL: "http://get_video/small.mp4", localVideoFileName: "small.mp4") guard let videoView = self.videoCreative.videoView else { XCTFail() return } self.videoCreative.creativeModel = PBMCreativeModel() self.videoCreative.creativeModel?.adConfiguration = AdConfiguration() self.videoCreative.creativeModel?.adConfiguration?.videoControlsConfig.skipDelay = 1 self.videoCreative.creativeModel?.displayDurationInSeconds = 10 self.videoCreative.creativeModel?.hasCompanionAd = true videoView.handleSkipDelay(0, videoDuration: 10) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { if !videoView.skipButtonDecorator.button.isHidden { expectation.fulfill() } } waitForExpectations(timeout: 2, handler: nil) } // MARK: - PBMCreativeDownloadDelegate func creativeReady(_ creative: PBMAbstractCreative) { self.expectationCreativeReady?.fulfill() } func creativeFailed(_ error:Error) {} // MARK: - PBMVideoViewDelegate func videoViewFailedWithError(_ error: Error) {} func videoViewReadyToDisplay() {} func videoViewCompletedDisplay() { isVideoViewCompletedDisplay = true self.expectationVideoViewCompletedDisplay?.fulfill() } func videoWasClicked() {} func videoClickthroughBrowserClosed() { self.expectationClickthroughBrowserClosed?.fulfill() } func trackEvent(_ trackingEvent: PBMTrackingEvent) {} // MARK: - CreativeViewDelegate func creativeDidComplete(_ creative: PBMAbstractCreative) { self.expectationCreativeDidComplete?.fulfill() } func creativeWasClicked(_ creative: PBMAbstractCreative) { self.expectationCreativeWasClicked?.fulfill() } func videoCreativeDidComplete(_ creative: PBMAbstractCreative) {} func creativeClickthroughDidClose(_ creative: PBMAbstractCreative) {} func creativeInterstitialDidClose(_ creative: PBMAbstractCreative) {} func creativeInterstitialDidLeaveApp(_ creative: PBMAbstractCreative) {} func creativeReady(toReimplant creative: PBMAbstractCreative) {} func creativeMraidDidCollapse(_ creative: PBMAbstractCreative) {} func creativeMraidDidExpand(_ creative: PBMAbstractCreative) {} func creativeDidDisplay(_ creative: PBMAbstractCreative) {} func videoViewWasTapped() {} func learnMoreWasClicked() {} func creativeViewWasClicked(_ creative: PBMAbstractCreative) {} func creativeFullScreenDidFinish(_ creative: PBMAbstractCreative) {} // MARK: - Helper Methods private func setupVideoCreative(videoFileURL:String = "http://get_video/small.mp4", localVideoFileName:String = "small.mp4", adConfiguration: AdConfiguration = AdConfiguration()) { let rule = MockServerRule(urlNeedle: videoFileURL, mimeType: MockServerMimeType.MP4.rawValue, connectionID: connection.internalID, fileName: localVideoFileName) MockServer.shared.resetRules([rule]) //Create model let model = PBMCreativeModel(adConfiguration:adConfiguration) model.videoFileURL = videoFileURL self.expectationDownloadCompleted = self.expectation(description: "expectationDownloadCompleted") let url = URL(string: model.videoFileURL!) let downloader = PBMDownloadDataHelper(serverConnection: connection) downloader.downloadData(for: url, maxSize: PBMVideoCreative.maxSizeForPreRenderContent, completionClosure: { (data:Data?, error:Error?) in DispatchQueue.main.async { //Create and start creative self.videoCreative = PBMVideoCreative(creativeModel:model, transaction:UtilitiesForTesting.createEmptyTransaction(), videoData: data!) self.videoCreative.creativeResolutionDelegate = self self.videoCreative.creativeViewDelegate = self self.expectationDownloadCompleted?.fulfill() } }) wait(for: [self.expectationDownloadCompleted!], timeout: 15) } private func setupVideoDurationTest(expectedDuration: Double) { //Wait for creativeReady self.expectationCreativeReady = self.expectation(description: "expectationCreativeReady") DispatchQueue.main.async { self.videoCreative?.setupView() } self.waitForExpectations(timeout: 15, handler:nil) self.videoCreative?.display(withRootViewController: UIViewController()) guard let videoView = self.videoCreative.view as? PBMVideoView else { XCTFail("Couldn't get Video View") return } videoView.videoViewDelegate = self self.expectationVideoViewCompletedDisplay = expectation(description: "expectationVideoViewCompletedDisplay") waitForExpectations(timeout: expectedDuration + 5, handler:nil) XCTAssertTrue(self.isVideoViewCompletedDisplay) } }
apache-2.0
4d02bb255efdb238fc5784dc67ddb2a1
39.207547
184
0.671574
5.952514
false
true
false
false
iOSDevLog/InkChat
InkChat/Pods/IBAnimatable/IBAnimatable/PlaceholderDesignable.swift
1
2868
// // Created by Jake Lin on 11/19/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public protocol PlaceholderDesignable: class { /** `color` within `::-webkit-input-placeholder`, `::-moz-placeholder` or `:-ms-input-placeholder` */ var placeholderColor: UIColor? { get set } var placeholderText: String? { get set } } public extension PlaceholderDesignable where Self: UITextField { var placeholderText: String? { get { return "" } set {} } public func configurePlaceholderColor() { let text = placeholderText ?? placeholder if let placeholderColor = placeholderColor, let placeholder = text { attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: placeholderColor]) } } } public extension PlaceholderDesignable where Self: UITextView { public func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) { placeholderLabel.font = font placeholderLabel.textColor = placeholderColor placeholderLabel.textAlignment = textAlignment placeholderLabel.text = placeholderText placeholderLabel.numberOfLines = 0 placeholderLabel.backgroundColor = .clear placeholderLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(placeholderLabel) update(placeholderLabel, using: &placeholderLabelConstraints) } public func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) { var format = "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]" var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: ["placeholder": placeholderLabel]) format = "V:|-(\(textContainerInset.top))-[placeholder]" newConstraints += NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: ["placeholder": placeholderLabel]) let constant = -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0) newConstraints.append(NSLayoutConstraint(item: placeholderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: constant)) removeConstraints(constraints) addConstraints(newConstraints) constraints = newConstraints } }
apache-2.0
46d005ff439deee0d287c3fb29a3894c
41.791045
133
0.628532
6.457207
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/PRODUCTNAME/Application/Debug/DebugMenuViewController.swift
1
2013
// // DebugMenuViewController.swift // PRODUCTNAME // // Created by LEADDEVELOPER on TODAYSDATE. // Copyright © THISYEAR ORGANIZATION. All rights reserved. // import Foundation import Services import Crashlytics class DebugMenuViewController: UITableViewController { lazy var dataSource: TableDataSource = { [weak self] in let dataSource = TableDataSource(rows: [ SimpleTableCellItem(text: "Text Styles") { self?.navigationController?.pushViewController(DebugTextStyleViewController(), animated: true) }, SimpleTableCellItem(text: "Invalidate Refresh Token") { APIClient.shared.oauthClient.credentials?.refreshToken = "BAD REFRESH TOKEN" }, SimpleTableCellItem(text: "Invalidate Access Token") { APIClient.shared.oauthClient.credentials?.accessToken = "BAD ACCESS TOKEN" }, SimpleTableCellItem(text: "Crash") { Crashlytics.sharedInstance().crash() }, SimpleTableCellItem(text: "Logout") { APIClient.shared.oauthClient.logout(completion: { (error) in NSLog("Logout: \(String(describing: error))") }) }, ]) return dataSource }() override func viewDidLoad() { super.viewDidLoad() SimpleTableCellItem.register(tableView) tableView.dataSource = dataSource addBehaviors([ModalDismissBehavior()]) var title = "Debug Menu" if let dictionary = Bundle.main.infoDictionary, let version = dictionary["CFBundleShortVersionString"] as? String, let build = dictionary["CFBundleVersion"] as? String { title.append(" \(version) (\(build))") } self.title = title } } extension DebugMenuViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { dataSource[indexPath].performSelection() tableView.deselectRow(at: indexPath, animated: true) } }
mit
0a4081eedc140da726a5ea72445bc7ec
34.298246
106
0.651093
5.379679
false
false
false
false
kostiakoval/SwiftAddressBook
Example/SwiftAddressBookTests/SwiftAddressBookGroupTests.swift
5
1556
// // SwiftAddressBookTests.swift // SwiftAddressBookTests // // Created by Albert Bori on 2/23/15. // Copyright (c) 2015 socialbit. All rights reserved. // import UIKit import XCTest import SwiftAddressBook import AddressBook //**** Run the example project first, to accept address book access **** class SwiftAddressBookGroupTests: XCTestCase { let waitTime = 3.0 let accessError = "Address book access was not granted. Run the main application and grant access to the address book." let accessErrorNil = "Failed to get address book access denial error" override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } //TODO: test group related methods from swiftaddressbook //TODO: test creating, modifying, and deleting group //MARK: - Helper funtions func getDateTimestamp() -> String { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ" return formatter.stringFromDate(NSDate()) } func getDate(year: Int,_ month: Int,_ day: Int) -> NSDate { var components = NSDateComponents() components.year = year components.month = month components.day = day return NSCalendar.currentCalendar().dateFromComponents(components)! } }
apache-2.0
39d5fd444f2c315816f4e9e9bb372bcb
29.509804
123
0.681877
4.536443
false
true
false
false
aleufms/JeraUtils
JeraUtils/Base/JeraBaseNavigationController.swift
1
2984
// // BaseNavigationController.swift // Jera // // Created by Alessandro Nakamuta on 10/29/15. // Copyright © 2015 Jera. All rights reserved. // import UIKit import Cartography public class JeraBaseNavigationController: UINavigationController { private weak var backgroundImageView: UIImageView? private var shadow: UIImage? private var backgroundImage: UIImage? private var isTranslucent: Bool? public var defaultStatusBarStyle = UIStatusBarStyle.Default{ didSet{ setNeedsStatusBarAppearanceUpdate() } } override public func viewDidLoad() { super.viewDidLoad() shadow = navigationBar.shadowImage backgroundImage = navigationBar.backgroundImageForBarMetrics(.Default) isTranslucent = navigationBar.translucent } //MARK: NavigationBar Helpers public func showNavigationBar(show: Bool) { if show { navigationBar.hidden = false navigationBar.shadowImage = shadow } else { navigationBar.hidden = true navigationBar.shadowImage = UIImage() } } public func showNavigationBarTransparent(transparent: Bool) { navigationBar.hidden = false if transparent { navigationBar.shadowImage = UIImage() navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) navigationBar.translucent = true } else { navigationBar.shadowImage = shadow navigationBar.setBackgroundImage(backgroundImage, forBarMetrics: .Default) if let isTranslucent = isTranslucent { navigationBar.translucent = isTranslucent } } } public func setupBackgroundImage(image: UIImage) { self.backgroundImageView?.removeFromSuperview() self.backgroundImageView = nil let backgroundImageView = UIImageView(image: image) backgroundImageView.contentMode = .ScaleToFill view.insertSubview(backgroundImageView, atIndex: 0) constrain(view, backgroundImageView, block: { (view, backgroundImageView) -> () in backgroundImageView.edges == view.edges }) self.backgroundImageView = backgroundImageView } //MARK: Appearence override public func preferredStatusBarStyle() -> UIStatusBarStyle { return defaultStatusBarStyle } //MARK: Dealloc deinit { self.removeListeners() self.cancelAsynchronousTasks() self.deallocOtherObjects() #if DEBUG print("Dealloc: \(NSStringFromClass(self.dynamicType))") #endif } public func removeListeners() { NSNotificationCenter.defaultCenter().removeObserver(self) } //This method needs to be implemented by the subclass public func cancelAsynchronousTasks() { } //This method needs to be implemented by the subclass public func deallocOtherObjects() { } }
mit
c898104160a2861df6a500a6ee1ce16e
27.141509
90
0.662085
5.837573
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/enum-extradata-no_payload_size-trailing_flags.swift
3
3417
// RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant { i64 } zeroinitializer, align [[ALIGNMENT]] // CHECK: @"$s4main6EitherOMP" = internal constant <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16 // : }> <{ // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.type* ( // : %swift.type_descriptor*, // : i8**, // : i8* // : )* @"$s4main6EitherOMi" to i64 // : ), // : i64 ptrtoint ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main6EitherOMP" to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.metadata_response ( // : %swift.type*, // : i8*, // : i8** // : )* @"$s4main6EitherOMr" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main6EitherOMP", // : i32 0, // : i32 1 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 1075838979, // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.enum_vwtable* @"$s4main6EitherOWV" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main6EitherOMP", // : i32 0, // : i32 3 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // CHECK-SAME: [[INT]] sub ( // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: { // CHECK-SAME: i64 // CHECK-SAME: }* [[EXTRA_DATA_PATTERN]] to [[INT]] // CHECK-SAME: ), // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: i32* getelementptr inbounds ( // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main6EitherOMP", // CHECK-SAME: i32 0, // CHECK-SAME: i32 4 // CHECK-SAME: ) to [[INT]] // CHECK-SAME: ) // CHECK-SAME: ) // : ), // : i16 4, // : i16 1 // : }>, align 8 enum Either<First, Second, Third> { case first(Int) case second(String) }
apache-2.0
1ed99914323db3d471825c41a7fe72b1
35.741935
173
0.366403
3.117701
false
false
false
false
mkauppila/AdventOfCode-Swift
AdventOfCode/Common/Common.swift
1
934
// // Common.swift // AdventOfCode // import Foundation func readInputFile(fileName: String) -> String { let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") return try! String(contentsOfFile: path!) } extension String { func isEmpty() -> Bool { return self.characters.count == 0 } func lengthWithUTF8Encoding() -> Int { return lengthOfBytesUsingEncoding(NSUTF8StringEncoding) } } extension Array { func filterWithIndex(includeElement: (Element, Index) -> Bool) -> [Element] { var results: [Element] = [] var index = 0 for x in self { if includeElement(x, index) { results.append(x) } index++ } return results } func any(filter: (Element) -> Bool) -> Bool { for x in self where filter(x) { return true } return false } }
mit
7d7e5caf53dc109b6908a1deb0f2a63d
21.238095
81
0.571734
4.284404
false
false
false
false
joalbright/Gameboard
Gameboards.playground/Sources/Boards/Dots.swift
1
3271
import UIKit public struct Dots { public static var board: Grid { return Grid(17 ✕ (17 ✕ ("●" %% "0") %% 17 ✕ ("0" %% EmptyPiece))) } // public static var board: Grid { return Grid(8 ✕ (8 ✕ "00000")) } public static let playerPieces = ["1","2"] public static func validateMove(_ s1: Square, _ p1: Piece, _ grid: Grid, _ player: Int) throws { guard p1 == "0" else { throw MoveError.invalidmove } grid[s1.0,s1.1] = playerPieces[player] checkSpaces(s1, grid, player: player) } public static func checkSpaces(_ s1: Square, _ grid: Grid, player: Int) { let adjacent2 = [ (-1,0),(0,1),(1,0),(0,-1) ] for a in adjacent2 { let s = (s1.0 + a.0, s1.1 + a.1) guard grid.onBoard(s) else { continue } guard grid[s.0,s.1] == EmptyPiece, checkClosed(s, grid) else { continue } grid[s.0,s.1] = playerPieces[player] } } public static func checkClosed(_ s1: Square, _ grid: Grid) -> Bool { var count = 0 let adjacent2 = [ (-1,0),(0,1),(1,0),(0,-1) ] for a in adjacent2 { let s = (s1.0 + a.0, s1.1 + a.1) guard grid.onBoard(s) else { continue } if grid[s.0,s.1] != "0" { count += 1 } } return count == 4 } } extension Grid { public func dots(_ rect: CGRect) -> UIView { let view = DotsView(frame: rect) view.p = padding view.backgroundColor = colors.background view.lineColor = colors.foreground view.layer.cornerRadius = 10 view.layer.masksToBounds = true let w = rect.width / 17 let h = rect.height / 17 for (r,row) in content.enumerated() { for (c,item) in row.enumerated() { let player = "\(item)" guard ["1","2"].contains(player) else { continue } if (r + c) % 2 == 0 { /// Space let dotView = DotsSquareView(frame: CGRect(x: c * w - padding / 2, y: r * h - padding / 2, width: w, height: h).insetBy(dx: -5, dy: -5)) dotView.backgroundColor = .clear dotView.playerColor = player == "1" ? colors.player1 : colors.player2 view.addSubview(dotView) } else { /// Line // let (dx,dy) = sp[s] // // let width = dx == 0 ? w + 14 : 14 // let height = dy == 0 ? h + 14 : 14 // let x = c * w + padding + w / 2 + (dx * w / 2) // let y = r * h + padding + w / 2 + (dy * h / 2) // // let lineView = DotsLineView(frame: CGRect(x: 0, y: 0, width: width, height: height)) // // lineView.backgroundColor = .clear // lineView.center = CGPoint(x: x, y: y) // lineView.playerColor = side == "1" ? colors.player1 : colors.player2 // lineView.lineColor = colors.foreground // // view.addSubview(lineView) } } } return view } }
apache-2.0
6187b2d49f0e1f3b53b75bca85cb4d4b
25.713115
156
0.462412
3.763279
false
false
false
false
hugweb/StackBox
Example/StackBox/HorizontalSnapController.swift
1
2986
// // HorizontalSnapController.swift // PopStackView // // Created by Hugues Blocher on 02/06/2017. // Copyright © 2017 Hugues Blocher. All rights reserved. // import UIKit import SnapKit import StackBox class HorizontalSnapController: UIViewController { let stack = StackBoxView() var views: [StackBoxItem] = [] override func viewDidLoad() { super.viewDidLoad() stack.axis = .horizontal view.backgroundColor = UIColor.white view.addSubview(stack) self.navigationItem.rightBarButtonItems = [UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(HorizontalSnapController.randomRemove)), UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil), UIBarButtonItem(title: "Reset", style: .plain, target: self, action: #selector(HorizontalSnapController.reset))] reset() } func reset() { stack.delete(views: views) views = [] let header = UIView() header.backgroundColor = UIColor.random header.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width / 2) make.height.equalTo(40) } let footer = UIView() footer.backgroundColor = UIColor.random footer.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width) make.height.equalTo(100) } let topContent = UIView() topContent.backgroundColor = UIColor.random topContent.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width / 3) make.height.equalTo(150) } let bottomContent = UIView() bottomContent.backgroundColor = UIColor.random bottomContent.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width / 1.2) make.height.equalTo(50) } let extraContent = UIView() extraContent.backgroundColor = UIColor.random extraContent.snp.makeConstraints { (make) in make.width.equalTo(UIScreen.main.bounds.width / 4) make.height.equalTo(50) } var items = [StackBoxItem(view: header, alignment: .leading), StackBoxItem(view: topContent), StackBoxItem(view: bottomContent, alignment: .trailing), StackBoxItem(view: footer)] items.shuffle().forEach { views.append($0) } stack.pop(views: items) } func randomRemove() { let index = Int(arc4random_uniform(UInt32(views.count))) if views.count > 0 && index >= 0 { let view = views[index] stack.delete(views: [view]) views.remove(at: index) } } }
mit
73c5d6e66fa7588f8caea30b785a6d55
33.310345
171
0.58191
4.649533
false
false
false
false
PanPanayotov/ios-boilerplate
FireAppBoilerplate/Console.swift
1
961
// // Console.swift // FireAppBoilerplate // // Created by Panayot Panayotov on 31/01/2017. // Copyright © 2017 Panayot Panayotov. All rights reserved. // import UIKit class Console: NSObject { static func log(_ items: Any..., separator: String = " ", terminator: String = "\n", line:Int = #line, file:NSString = #file) { #if DEBUG // remove .swift from file name var fileName = file.lastPathComponent fileName = fileName.substring(to: fileName.index(fileName.endIndex, offsetBy: -6)) Swift.print("<<< \(fileName):\(line) >>> \(items[0])" , separator:separator, terminator: terminator) #endif } static func debug(_ items: Any..., separator: String = " ", terminator: String = "\n") { #if DEBUG // only print if in debug build Swift.debugPrint(items[0], separator: separator, terminator: terminator) #endif } }
mit
118b2795fe8902149af6391ba062b8cd
32.103448
131
0.592708
4.085106
false
false
false
false
TonnyTao/HowSwift
Funny Swift.playground/Pages/elimnate if.xcplaygroundpage/Contents.swift
1
322
//: [Previous](@previous) import Foundation var city: String? = "Auckland" var para = [String: Any]() if city != nil { para["city"] = city } // elimnate if with flatMap city.flatMap { para["city"] = $0 } // it is same as city.flatMap { c -> Void? in para["city"] = c return () } //: [Next](@next)
mit
c5356f088b9bc8e299de71418c192191
12.416667
34
0.565217
2.954128
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleCell.swift
1
14952
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import UIKit; /** Bubble types */ enum BubbleType { // Outcome text bubble case TextOut // Income text bubble case TextIn // Outcome media bubble case MediaOut // Income media bubble case MediaIn // Service bubbl case Service } /** Root class for bubble layouter. Used for preprocessing bubble layout in background. */ protocol AABubbleLayouter { func isSuitable(message: ACMessage) -> Bool func buildLayout(peer: ACPeer, message: ACMessage) -> CellLayout func cellClass() -> AnyClass } // Extension for automatically building reuse ids extension AABubbleLayouter { var reuseId: String { get { return "\(self.dynamicType)" } } } /** Root class for bubble cells */ class AABubbleCell: UICollectionViewCell { // MARK: - // MARK: Private static vars static let bubbleContentTop: CGFloat = 6 static let bubbleContentBottom: CGFloat = 6 static let bubbleTop: CGFloat = 3 static let bubbleTopCompact: CGFloat = 1 static let bubbleBottom: CGFloat = 3 static let bubbleBottomCompact: CGFloat = 1 static let avatarPadding: CGFloat = 39 static let dateSize: CGFloat = 30 static let newMessageSize: CGFloat = 30 // Cached bubble images private static var cachedOutTextBg:UIImage = UIImage(named: "BubbleOutgoingFull")!.tintImage(MainAppTheme.bubbles.textBgOut) private static var cachedOutTextBgBorder:UIImage = UIImage(named: "BubbleOutgoingFullBorder")!.tintImage(MainAppTheme.bubbles.textBgOutBorder) private static var cachedInTextBg:UIImage = UIImage(named: "BubbleIncomingFull")!.tintImage(MainAppTheme.bubbles.textBgIn) private static var cachedInTextBgBorder:UIImage = UIImage(named: "BubbleIncomingFullBorder")!.tintImage(MainAppTheme.bubbles.textBgInBorder) private static var cachedOutTextCompactBg:UIImage = UIImage(named: "BubbleOutgoingPartial")!.tintImage(MainAppTheme.bubbles.textBgOut) private static var cachedOutTextCompactBgBorder:UIImage = UIImage(named: "BubbleOutgoingPartialBorder")!.tintImage(MainAppTheme.bubbles.textBgOutBorder) private static var cachedInTextCompactBg:UIImage = UIImage(named: "BubbleIncomingPartial")!.tintImage(MainAppTheme.bubbles.textBgIn) private static var cachedInTextCompactBgBorder:UIImage = UIImage(named: "BubbleIncomingPartialBorder")!.tintImage(MainAppTheme.bubbles.textBgInBorder) private static let cachedOutMediaBg:UIImage = UIImage(named: "BubbleOutgoingPartial")!.tintImage(MainAppTheme.bubbles.mediaBgOut) private static var cachedOutMediaBgBorder:UIImage = UIImage(named: "BubbleIncomingPartialBorder")!.tintImage(MainAppTheme.bubbles.mediaBgInBorder) private static var cachedInMediaBg:UIImage? = nil; private static var cachedInMediaBgBorder:UIImage? = nil; private static var cachedServiceBg:UIImage = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) private static var dateBgImage = Imaging.roundedImage(MainAppTheme.bubbles.serviceBg, size: CGSizeMake(18, 18), radius: 9) // MARK: - // MARK: Public vars // Views let mainView = UIView() let avatarView = AvatarView(frameSize: 39) var avatarAdded: Bool = false let bubble = UIImageView() let bubbleBorder = UIImageView() private let dateText = UILabel() private let dateBg = UIImageView() private let newMessage = UILabel() // Layout var contentInsets : UIEdgeInsets = UIEdgeInsets() var bubbleInsets : UIEdgeInsets = UIEdgeInsets() var fullContentInsets : UIEdgeInsets { get { return UIEdgeInsets( top: contentInsets.top + bubbleInsets.top + (isShowDate ? AABubbleCell.dateSize : 0) + (isShowNewMessages ? AABubbleCell.newMessageSize : 0), left: contentInsets.left + bubbleInsets.left + (isGroup && !isOut ? AABubbleCell.avatarPadding : 0), bottom: contentInsets.bottom + bubbleInsets.bottom, right: contentInsets.right + bubbleInsets.right) } } var needLayout: Bool = true let groupContentInsetY = 20.0 let groupContentInsetX = 40.0 var bubbleVerticalSpacing: CGFloat = 6.0 let bubblePadding: CGFloat = 6; let bubbleMediaPadding: CGFloat = 10; // Binded data var peer: ACPeer! var controller: ConversationBaseViewController! var isGroup: Bool = false var isFullSize: Bool! var bindedSetting: CellSetting? var bindedMessage: ACMessage? = nil var bubbleType:BubbleType? = nil var isOut: Bool = false var isShowDate: Bool = false var isShowNewMessages: Bool = false // MARK: - // MARK: Constructors init(frame: CGRect, isFullSize: Bool) { super.init(frame: frame) self.isFullSize = isFullSize dateBg.image = AABubbleCell.dateBgImage dateText.font = UIFont.mediumSystemFontOfSize(12) dateText.textColor = UIColor.whiteColor() dateText.contentMode = UIViewContentMode.Center dateText.textAlignment = NSTextAlignment.Center newMessage.font = UIFont.mediumSystemFontOfSize(14) newMessage.textColor = UIColor.whiteColor() newMessage.contentMode = UIViewContentMode.Center newMessage.textAlignment = NSTextAlignment.Center newMessage.backgroundColor = UIColor.alphaBlack(0.3) newMessage.text = "New Messages" // bubble.userInteractionEnabled = true mainView.transform = CGAffineTransformMake(1, 0, 0, -1, 0, 0) mainView.addSubview(bubble) mainView.addSubview(bubbleBorder) mainView.addSubview(newMessage) mainView.addSubview(dateBg) mainView.addSubview(dateText) contentView.addSubview(mainView) avatarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "avatarDidTap")) avatarView.userInteractionEnabled = true backgroundColor = UIColor.clearColor() // Speed up animations self.layer.speed = 1.5 self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setConfig(peer: ACPeer, controller: ConversationBaseViewController) { self.peer = peer self.controller = controller if (peer.isGroup && !isFullSize) { self.isGroup = true } } override func canBecomeFirstResponder() -> Bool { return false } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "delete:" { return true } return false } override func delete(sender: AnyObject?) { let rids = IOSLongArray(length: 1) rids.replaceLongAtIndex(0, withLong: bindedMessage!.rid) Actor.deleteMessagesWithPeer(self.peer, withRids: rids) } func avatarDidTap() { if bindedMessage != nil { controller.onBubbleAvatarTap(self.avatarView, uid: bindedMessage!.senderId) } } func performBind(message: ACMessage, setting: CellSetting, isShowNewMessages: Bool, layout: CellLayout) { self.clipsToBounds = false self.contentView.clipsToBounds = false var reuse = false if (bindedMessage != nil && bindedMessage?.rid == message.rid) { reuse = true } isOut = message.senderId == Actor.myUid(); bindedMessage = message self.isShowNewMessages = isShowNewMessages if (!reuse) { if (!isFullSize) { if (!isOut && isGroup) { if let user = Actor.getUserWithUid(message.senderId) { let avatar: ACAvatar? = user.getAvatarModel().get() let name = user.getNameModel().get() avatarView.bind(name, id: user.getId(), avatar: avatar) } if !avatarAdded { mainView.addSubview(avatarView) avatarAdded = true } } else { if avatarAdded { avatarView.removeFromSuperview() avatarAdded = false } } } } self.isShowDate = setting.showDate if (isShowDate) { self.dateText.text = Actor.getFormatter().formatDate(message.date) } self.bindedSetting = setting bind(message, reuse: reuse, cellLayout: layout, setting: setting) if (!reuse) { needLayout = true super.setNeedsLayout() } } func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) { fatalError("bind(message:) has not been implemented") } func bindBubbleType(type: BubbleType, isCompact: Bool) { self.bubbleType = type // Update Bubble background images switch(type) { case BubbleType.TextIn: if (isCompact) { bubble.image = AABubbleCell.cachedInTextCompactBg bubbleBorder.image = AABubbleCell.cachedInTextCompactBgBorder } else { bubble.image = AABubbleCell.cachedInTextBg bubbleBorder.image = AABubbleCell.cachedInTextBgBorder } break case BubbleType.TextOut: if (isCompact) { bubble.image = AABubbleCell.cachedOutTextCompactBg bubbleBorder.image = AABubbleCell.cachedOutTextCompactBgBorder } else { bubble.image = AABubbleCell.cachedOutTextBg bubbleBorder.image = AABubbleCell.cachedOutTextBgBorder } break case BubbleType.MediaIn: bubble.image = AABubbleCell.cachedOutMediaBg bubbleBorder.image = AABubbleCell.cachedOutMediaBgBorder break case BubbleType.MediaOut: bubble.image = AABubbleCell.cachedOutMediaBg bubbleBorder.image = AABubbleCell.cachedOutMediaBgBorder break case BubbleType.Service: bubble.image = AABubbleCell.cachedServiceBg bubbleBorder.image = nil break } } // MARK: - // MARK: Layout override func layoutSubviews() { super.layoutSubviews() mainView.frame = CGRectMake(0, 0, contentView.bounds.width, contentView.bounds.height) // if (!needLayout) { // return // } // needLayout = false UIView.performWithoutAnimation { () -> Void in let endPadding: CGFloat = 32 let startPadding: CGFloat = (!self.isOut && self.isGroup) ? AABubbleCell.avatarPadding : 0 let cellMaxWidth = self.contentView.frame.size.width - endPadding - startPadding self.layoutContent(cellMaxWidth, offsetX: startPadding) self.layoutAnchor() if (!self.isOut && self.isGroup && !self.isFullSize) { self.layoutAvatar() } } } func layoutAnchor() { if (isShowDate) { dateText.frame = CGRectMake(0, 0, 1000, 1000) dateText.sizeToFit() dateText.frame = CGRectMake( (self.contentView.frame.size.width-dateText.frame.width)/2, 8, dateText.frame.width, 18) dateBg.frame = CGRectMake(dateText.frame.minX - 8, dateText.frame.minY, dateText.frame.width + 16, 18) dateText.hidden = false dateBg.hidden = false } else { dateText.hidden = true dateBg.hidden = true } if (isShowNewMessages) { var top = CGFloat(0) if (isShowDate) { top += AABubbleCell.dateSize } newMessage.hidden = false newMessage.frame = CGRectMake(0, top + CGFloat(2), self.contentView.frame.width, AABubbleCell.newMessageSize - CGFloat(4)) } else { newMessage.hidden = true } } func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { } func layoutAvatar() { let avatarSize = CGFloat(self.avatarView.frameSize) avatarView.frame = CGRect(x: 5 + (isIPad ? 16 : 0), y: self.contentView.frame.size.height - avatarSize - 2 - bubbleInsets.bottom, width: avatarSize, height: avatarSize) } // Need to be called in child cells func layoutBubble(contentWidth: CGFloat, contentHeight: CGFloat) { let fullWidth = contentView.bounds.width let bubbleW = contentWidth + contentInsets.left + contentInsets.right let bubbleH = contentHeight + contentInsets.top + contentInsets.bottom var topOffset = CGFloat(0) if (isShowDate) { topOffset += AABubbleCell.dateSize } if (isShowNewMessages) { topOffset += AABubbleCell.newMessageSize } var bubbleFrame : CGRect! if (!isFullSize) { if (isOut) { bubbleFrame = CGRect( x: fullWidth - contentWidth - contentInsets.left - contentInsets.right - bubbleInsets.right, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } else { let padding : CGFloat = isGroup ? AABubbleCell.avatarPadding : 0 bubbleFrame = CGRect( x: bubbleInsets.left + padding, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } } else { bubbleFrame = CGRect( x: (fullWidth - contentWidth - contentInsets.left - contentInsets.right)/2, y: bubbleInsets.top + topOffset, width: bubbleW, height: bubbleH) } bubble.frame = bubbleFrame bubbleBorder.frame = bubbleFrame } func layoutBubble(frame: CGRect) { bubble.frame = frame bubbleBorder.frame = frame } override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { return layoutAttributes } }
mit
b2a294b6695d41cf12b04b4735ce1c52
35.293689
176
0.612226
5.35914
false
false
false
false
silt-lang/silt
Sources/Seismography/Graph.swift
1
2297
/// Graph.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation /// Represents an abstraction over graph-like objects. public protocol GraphNode: AnyObject, Hashable { /// The successor sequence type for this node. associatedtype Successors: Sequence where Successors.Element == Self associatedtype Predecessors: Sequence where Predecessors.Element == Self /// A sequence of this node's successors. var successors: Successors { get } /// A sequence of this node's predecessors. var predecessors: Predecessors { get } } /// A sequence that computes the reverse post-order traversal of a given graph. public struct ReversePostOrderSequence<Node: GraphNode>: Sequence { public struct Iterator: IteratorProtocol { let mayVisit: Set<Node> var visited = Set<Node>() var postorder = [Node]() fileprivate var nodeIndices = [Node: Int]() init(start: Node, mayVisit: Set<Node>) { self.mayVisit = mayVisit traverse(start) } /// Traverses the tree and builds a post-order traversal, which will be /// reversed on iteration. mutating func traverse(_ node: Node) { visited.insert(node) for child in node.successors { guard mayVisit.contains(child) && !visited.contains(child) else { continue } traverse(child) } nodeIndices[node] = postorder.count postorder.append(node) } public mutating func next() -> Node? { return postorder.popLast() } } public struct Indexer { var indices: [Node: Int] public func index(of node: Node) -> Int { guard let index = indices[node] else { fatalError("Requested index of node outside of this CFG") } return index } } let root: Node let mayVisit: Set<Node> public init(root: Node, mayVisit: Set<Node>) { self.root = root self.mayVisit = mayVisit } public func makeIterator() -> ReversePostOrderSequence<Node>.Iterator { return Iterator(start: root, mayVisit: mayVisit) } public func makeIndexer() -> Indexer { let it = Iterator(start: root, mayVisit: mayVisit) return Indexer(indices: it.nodeIndices) } }
mit
d10a9bdb6e1f839363c3838b8d7df191
27.012195
79
0.673052
4.3258
false
false
false
false
dataich/TypetalkSwift
TypetalkSwift/Request.swift
1
1530
// // Request.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire public protocol Request { associatedtype Response: Codable var method: HTTPMethod { get } var path: String { get } var version: Int { get } var parameters: Parameters? { get } var bodyParameter: BodyParameter? { get } func asURLRequest(_ baseURL: String) throws -> URLRequest } extension Request { public var version: Int { return 1 } public var method: HTTPMethod { return .get } public var parameters: Parameters? { return nil } public var bodyParameter: BodyParameter? { return nil } public func asURLRequest(_ baseURL: String) throws -> URLRequest { let url = URL(string: "\(baseURL)/api/v\(version)") let urlRequest = try URLRequest(url: url!.appendingPathComponent(path), method: method) return try NoBracketsURLEncoding().encode(urlRequest, with: parameters) } } public struct NoBracketsURLEncoding: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try URLEncoding().encode(urlRequest, with: parameters) request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "=")) return request } } public struct BodyParameter { public let data: Data public let withName: String public let fileName: String public let mimeType: String }
mit
d951895567d45fd20ea6cbba26b9d8c0
25.362069
110
0.70569
4.307042
false
false
false
false
ccqpein/Arithmetic-Exercises
Dijkstra-algorithm/DA.swift
1
2786
let example1:[[Int?]] = [ [0, 6, 3, nil, nil, nil,], [6, 0, 2, 5, nil, nil,], [3, 2, 0, 3, 4, nil,], [nil, 5, 3, 0, 2, 3,], [nil, nil, 4, 2, 0, 5], [nil, nil, nil, 3, 5, 0,], ] let example2:[[Int?]] = [ [0, 7, 9, nil, nil, 14,], [7, 0, 10, 15, nil, nil,], [9, 10, 0, 11, nil, 2], [nil, 15, 11, 0, 6, nil,], [nil, nil, nil, 6, 0, 9,], [14, nil, 2, nil, 9, 0,], ] struct PathResult { var val:Int var pathList:Array<Int> } enum GetValError:Error{ case noVal } func delete(_ ele:Int, _ array: inout [Int]){ var removeL = [Int]() for i in (0..<array.count) { if array[i] == ele{ removeL.append(i) } } removeL = removeL.reversed() for i in removeL { array.remove(at:i) } } func getVal(pathRoot:[Int], pathP:Int, m:[[Int?]] = example1) throws -> PathResult{ var pathTemp = pathRoot pathTemp.append(pathP) var pathVal = 0 let valTest = m[pathRoot.last!][pathP] guard valTest != nil else{ throw GetValError.noVal } for i in (1..<pathTemp.count) { pathVal = pathVal + m[pathTemp[i-1]][pathTemp[i]]! } return PathResult(val:pathVal, pathList:pathTemp) } func dijkstra(start:Int, matrix m:[[Int?]] = example1) -> [PathResult]{ // initialize var s:[Int] = [start] var u:[Int] = [] for i in 0..<m.count where i != start { u.append(i) } // make a temp list for result let startResult = PathResult(val:0, pathList:[start]) var smallL:[PathResult] = [startResult] var largeL:[PathResult] = [] // core code for _ in 0..<u.count { var tempResultList:[PathResult] = [] for e in u { var thisPath:PathResult? // get the val, maybe can use {get} in future do{ thisPath = try getVal(pathRoot:smallL.last!.pathList, pathP:e, m:m) //be careful for errer handler }catch { continue } var tempOldVal:[PathResult] = [] for oldP in largeL where oldP.pathList.last! == e && oldP.val < thisPath!.val { tempOldVal.append(oldP) } tempOldVal.sort{ $0.val < $1.val } if tempOldVal.first == nil { tempResultList.append(thisPath!) }else { tempResultList.append(tempOldVal.first!) } } tempResultList.sort{ $0.val < $1.val } s.append(tempResultList.first!.pathList.last!) delete(tempResultList.first!.pathList.last!, &u) smallL.append(tempResultList.first!) largeL = largeL + tempResultList.dropFirst() // may issues } return smallL } print(dijkstra(start:0))
apache-2.0
9aca47411d2c3a3d1ed1e9db797022b4
25.533333
114
0.525485
3.293144
false
false
false
false
andreaperizzato/CoreStore
CoreStore/Internal/NSManagedObjectContext+Transaction.swift
2
5213
// // NSManagedObjectContext+Transaction.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData import GCDKit // MARK: - NSManagedObjectContext internal extension NSManagedObjectContext { // MARK: Internal internal weak var parentTransaction: BaseDataTransaction? { get { return getAssociatedObjectForKey( &PropertyKeys.parentTransaction, inObject: self ) } set { setAssociatedWeakObject( newValue, forKey: &PropertyKeys.parentTransaction, inObject: self ) } } internal func temporaryContextInTransactionWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.parentContext = self context.parentStack = self.parentStack context.setupForCoreStoreWithContextName("com.corestore.temporarycontext") context.shouldCascadeSavesToParent = (self.parentStack?.rootSavingContext == self) context.retainsRegisteredObjects = true return context } internal func saveSynchronously() -> SaveResult { var result = SaveResult(hasChanges: false) self.performBlockAndWait { [unowned self] () -> Void in guard self.hasChanges else { return } do { try self.save() } catch { let saveError = error as NSError CoreStore.handleError( saveError, "Failed to save \(typeName(NSManagedObjectContext))." ) result = SaveResult(saveError) return } if let parentContext = self.parentContext where self.shouldCascadeSavesToParent { switch parentContext.saveSynchronously() { case .Success: result = SaveResult(hasChanges: true) case .Failure(let error): result = SaveResult(error) } } else { result = SaveResult(hasChanges: true) } } return result } internal func saveAsynchronouslyWithCompletion(completion: ((result: SaveResult) -> Void) = { _ in }) { self.performBlock { () -> Void in guard self.hasChanges else { GCDQueue.Main.async { completion(result: SaveResult(hasChanges: false)) } return } do { try self.save() } catch { let saveError = error as NSError CoreStore.handleError( saveError, "Failed to save \(typeName(NSManagedObjectContext))." ) GCDQueue.Main.async { completion(result: SaveResult(saveError)) } return } if let parentContext = self.parentContext where self.shouldCascadeSavesToParent { parentContext.saveAsynchronouslyWithCompletion(completion) } else { GCDQueue.Main.async { completion(result: SaveResult(hasChanges: true)) } } } } // MARK: Private private struct PropertyKeys { static var parentTransaction: Void? } }
mit
effd21d3e5e523e4b893cb7d94cd1cab
30.403614
150
0.536927
6.396319
false
false
false
false
JetBrains/kotlin-native
performance/swiftinterop/swiftSrc/main.swift
2
3694
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Foundation import benchmark var runner = BenchmarksRunner() let args = KotlinArray<NSString>(size: Int32(CommandLine.arguments.count - 1), init: {index in CommandLine.arguments[Int(truncating: index) + 1] as NSString }) let companion = BenchmarkEntryWithInit.Companion() var swiftLauncher = SwiftLauncher() swiftLauncher.add(name: "createMultigraphOfInt", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).createMultigraphOfInt() })) swiftLauncher.add(name: "fillCityMap", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).fillCityMap() })) swiftLauncher.add(name: "searchRoutesInSwiftMultigraph", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).searchRoutesInSwiftMultigraph () })) swiftLauncher.add(name: "searchTravelRoutes", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).searchTravelRoutes() })) swiftLauncher.add(name: "availableTransportOnMap", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).availableTransportOnMap() })) swiftLauncher.add(name: "allPlacesMapedByInterests", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).allPlacesMapedByInterests() })) swiftLauncher.add(name: "getAllPlacesWithStraightRoutesTo", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).getAllPlacesWithStraightRoutesTo() })) swiftLauncher.add(name: "goToAllAvailablePlaces", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).goToAllAvailablePlaces() })) swiftLauncher.add(name: "removeVertexAndEdgesSwiftMultigraph", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).removeVertexAndEdgesSwiftMultigraph() })) swiftLauncher.add(name: "stringInterop", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).stringInterop() })) swiftLauncher.add(name: "simpleFunction", benchmark: companion.create(ctor: { return SwiftInteropBenchmarks() }, lambda: { ($0 as! SwiftInteropBenchmarks).simpleFunction() })) runner.runBenchmarks(args: args, run: { (arguments: BenchmarkArguments) -> [BenchmarkResult] in if arguments is BaseBenchmarkArguments { let argumentsList: BaseBenchmarkArguments = arguments as! BaseBenchmarkArguments return swiftLauncher.launch(numWarmIterations: argumentsList.warmup, numberOfAttempts: argumentsList.repeat, prefix: argumentsList.prefix, filters: argumentsList.filter, filterRegexes: argumentsList.filterRegex, verbose: argumentsList.verbose) } return [BenchmarkResult]() }, parseArgs: { (args: KotlinArray, benchmarksListAction: (() -> KotlinUnit)) -> BenchmarkArguments? in return runner.parse(args: args, benchmarksListAction: swiftLauncher.benchmarksListAction) }, collect: { (benchmarks: [BenchmarkResult], arguments: BenchmarkArguments) -> Void in runner.collect(results: benchmarks, arguments: arguments) }, benchmarksListAction: swiftLauncher.benchmarksListAction)
apache-2.0
b299c6ee76de8fb0ded5764b0490a4f6
68.716981
137
0.74445
4.723785
false
false
false
false
bizz84/MVMediaSlider
MVMediaSliderDemo/ViewController.swift
1
3944
/* MVMediaSlider - Copyright (c) 2016 Andrea Bizzotto [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import MVMediaSlider class ViewController: UIViewController { private let SeekTimeStep = 10.0 private var timer: Timer? private var audioPlayer: AudioPlayer? @IBOutlet private var mediaSlider: MVMediaSlider! @IBOutlet private var playButton: UIButton! var playing: Bool = false { didSet { playButton.isSelected = playing if (playing) { let _ = audioPlayer?.play() timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(ViewController.updateViews(_:)), userInfo: nil, repeats: true) } else { audioPlayer?.pause() timer?.invalidate() } } } override func viewDidLoad() { super.viewDidLoad() self.title = "PLAYING" loadAudio(false) } private func loadAudio(_ realPlayer: Bool) { if realPlayer { do { let audioPlayer = try RealAudioPlayer.load("SampleAudioFile", type: "mp3", playImmediately: false) mediaSlider.totalTime = audioPlayer.duration mediaSlider.currentTime = 0 self.audioPlayer = audioPlayer } catch { print("Error loading: \(error)") } } else { let audioPlayer = FakeAudioPlayer() mediaSlider.totalTime = audioPlayer.duration mediaSlider.currentTime = 0 self.audioPlayer = audioPlayer } } // MARK: IBActions @IBAction private func sliderValueChanged(_ sender: MVMediaSlider) { updatePlayer(currentTime: sender.currentTime ?? 0) } @IBAction private func backTapped(_ sender: UIButton) { let newTime = _currentTime - SeekTimeStep > 0 ? _currentTime - SeekTimeStep : 0 updatePlayer(currentTime: newTime) } @IBAction private func forwardTapped(_ sender: UIButton) { let newTime = _currentTime + SeekTimeStep < _totalTime ? _currentTime + SeekTimeStep : 0 updatePlayer(currentTime: newTime) } @IBAction private func playTapped(_ sender: UIButton) { playing = !playing } @objc private func updateViews(_ sender: AnyObject) { updateMediaSlider(currentTime: _currentTime) } private func updateMediaSlider(currentTime: TimeInterval) { mediaSlider.currentTime = currentTime } private func updatePlayer(currentTime: TimeInterval) { audioPlayer?.currentTime = currentTime } private var _currentTime: TimeInterval { return audioPlayer?.currentTime ?? 0 } private var _totalTime: TimeInterval { return audioPlayer?.duration ?? 0 } }
mit
457d1ce385ffd85b4962a6241f25ff89
34.214286
460
0.648834
5.344173
false
false
false
false
studyYF/SingleSugar
SingleSugar/SingleSugar/Classes/SingleProduct(单品)/View/YFDetailCommentCell.swift
1
2591
// // YFDetailCommentCell.swift // SingleSugar // // Created by YangFan on 2017/4/26. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit import SnapKit class YFDetailCommentCell: UITableViewCell { //MARK: 属性 ///评论数组 var commentItems: [YFCommentItem]? ///图文详情 var detail: String? lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: kWidth, height:kHeight - 40 - kNavigationH)) scrollView.isScrollEnabled = false return scrollView }() lazy var contentScrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: kWidth, height:kHeight - 40 - kNavigationH)) scrollView.backgroundColor = UIColor.green return scrollView }() lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRect(x: kWidth, y: 40, width: kWidth, height: kHeight - kNavigationH - 40)) tableView.backgroundColor = UIColor.white tableView.register(UINib.init(nibName: "YFCommentCell", bundle: nil), forCellReuseIdentifier: "YFCommentCell") tableView.estimatedRowHeight = 80 tableView.rowHeight = UITableViewAutomaticDimension return tableView }() override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none setUI() } } extension YFDetailCommentCell { fileprivate func setUI() { contentView.addSubview(scrollView) tableView.delegate = self tableView.dataSource = self scrollView.addSubview(tableView) scrollView.addSubview(contentScrollView) scrollView.contentSize = CGSize(width: kWidth * 2, height: tableView.contentSize.height) tableView.snp.makeConstraints { (make) in make.height.equalTo(kHeight - 40 - kNavigationH) make.edges.equalTo(contentView).inset(UIEdgeInsetsMake(0, 0, 0, 0)) } } } //MARK: tableView 代理方法 extension YFDetailCommentCell: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (commentItems?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YFCommentCell", for: indexPath) as! YFCommentCell cell.item = commentItems?[indexPath.row] return cell } }
apache-2.0
95cf9b1f5e8582c6f80a547e44027b23
31
120
0.663672
4.913628
false
false
false
false
ParadropLabs/riffle-swift
Example/Riffle/ViewController.swift
1
1385
// // ViewController.swift // Riffle // // Created by Mickey Barboi on 09/25/2015. // Copyright (c) 2015 Mickey Barboi. All rights reserved. // import UIKit import Riffle class ViewController: UIViewController { var isBlinking = false // let blinkingLabel = BlinkingLabel(frame: CGRectMake(10, 20, 200, 30)) override func viewDidLoad() { super.viewDidLoad() // Setup the BlinkingLabel // blinkingLabel.text = "I blink!" // blinkingLabel.font = UIFont.systemFontOfSize(20) // view.addSubview(blinkingLabel) // blinkingLabel.startBlinking() // isBlinking = true // // // Create a UIButton to toggle the blinking // let toggleButton = UIButton(frame: CGRectMake(10, 60, 125, 30)) // toggleButton.setTitle("Toggle Blinking", forState: .Normal) // toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal) // toggleButton.addTarget(self, action: "toggleBlinking", forControlEvents: .TouchUpInside) // view.addSubview(toggleButton) } // func toggleBlinking() { // if (isBlinking) { // blinkingLabel.stopBlinking() // } else { // blinkingLabel.startBlinking() // } // isBlinking = !isBlinking // blinkingLabel.doSomething() // } // blinkingLabel.doSomething() }
mit
1430daedae4163249e72fb29d4f07733
27.875
98
0.617329
4.274691
false
false
false
false
sebastienh/SwiftFlux
SwiftFluxTests/DispatcherSpec.swift
1
4849
// // DispatcherSpec.swift // SwiftFlux // // Created by Kenichi Yonekawa on 8/2/15. // Copyright (c) 2015 mog2dev. All rights reserved. // import Quick import Nimble import Result import SwiftFlux class DispatcherSpec: QuickSpec { struct DispatcherTestModel { let name: String } struct DispatcherTestAction: Action { typealias Payload = DispatcherTestModel func invoke(dispatcher: Dispatcher) {} } override func spec() { let dispatcher = DefaultDispatcher() describe("dispatch") { var results = [String]() var fails = [String]() var callbacks = [DispatchToken]() beforeEach { () in results = [] fails = [] callbacks = [] let id1 = dispatcher.register(type: DispatcherTestAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)1") case .failure(_): fails.append("fail") } } let id2 = dispatcher.register(type: DispatcherTestAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)2") case .failure(_): fails.append("fail") } } callbacks.append(id1) callbacks.append(id2) } afterEach { () in for id in callbacks { dispatcher.unregister(dispatchToken: id) } } context("when action succeeded") { it("should dispatch to registered callback handlers") { dispatcher.dispatch(action: DispatcherTestAction(), result: Result(value: DispatcherTestModel(name: "test"))) expect(results.count).to(equal(2)) expect(fails.isEmpty).to(beTruthy()) expect(results).to(contain("test1", "test2")) } } context("when action failed") { it("should dispatch to registered callback handlers") { dispatcher.dispatch(action: DispatcherTestAction(), result: Result(error: NSError(domain: "TEST0000", code: -1, userInfo: [:]))) expect(fails.count).to(equal(2)) expect(results.isEmpty).to(beTruthy()) } } } describe("waitFor") { var results = [String]() var callbacks = [DispatchToken]() var id1 = ""; var id2 = ""; var id3 = ""; beforeEach { () in results = [] callbacks = [] id1 = dispatcher.register(type: DispatcherTestAction.self) { (result) in switch result { case .success(let box): dispatcher.waitFor(dispatchTokens: [id2], type: DispatcherTestAction.self, result: result) results.append("\(box.name)1") default: break } } id2 = dispatcher.register(type: DispatcherTestAction.self) { (result) in switch result { case .success(let box): dispatcher.waitFor(dispatchTokens: [id3], type: DispatcherTestAction.self, result: result) results.append("\(box.name)2") default: break } } id3 = dispatcher.register(type: DispatcherTestAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)3") default: break } } callbacks.append(id1) callbacks.append(id2) callbacks.append(id3) } afterEach { () in for id in callbacks { dispatcher.unregister(dispatchToken: id) } } it("should wait for invoke callback") { dispatcher.dispatch(action: DispatcherTestAction(), result: Result(value: DispatcherTestModel(name: "test"))) expect(results.count).to(equal(3)) expect(results[0]).to(equal("test3")) expect(results[1]).to(equal("test2")) expect(results[2]).to(equal("test1")) } } } }
mit
ac485cc3d831ffd127cce675bf3a2fd4
34.137681
148
0.460507
5.454443
false
true
false
false