repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
smart23033/boostcamp_iOS_bipeople
Bipeople/Bipeople/HistoryDetailViewController.swift
1
8635
// // HistoryDetailViewController.swift // Bipeople // // Created by 김성준 on 2017. 8. 8.. // Copyright © 2017년 BluePotato. All rights reserved. // import UIKit import RealmSwift import GoogleMaps import MarqueeLabel enum PolyLineType: String { case altitude = "고도" case speed = "속도" } class HistoryDetailViewController: UIViewController { //MARK: Outlets @IBOutlet weak var titleLabel: UINavigationItem! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var ridingTimeLabel: UILabel! @IBOutlet weak var restTimeLabel: UILabel! @IBOutlet weak var averageSpeedLabel: UILabel! @IBOutlet weak var maximumSpeedLabel: UILabel! @IBOutlet weak var caloriesLabel: UILabel! @IBOutlet weak var createdAt: UILabel! @IBOutlet weak var mapView: GMSMapView! @IBOutlet weak var filterLabel: UILabel! { didSet { filterLabel.text = selectedValue.rawValue } } //MARK: Properties var record: Record? var traces: [Trace]? var navigationRoute: GMSPolyline? var marqueeTitle : MarqueeLabel? var redValue = Double() var greenValue = Double() var maxAltitude = Double() var maxSpeed = Double() var pickerData: [PolyLineType] = [.altitude,.speed] var selectedValue: PolyLineType = .altitude //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() guard let recordID = record?._id else { return } let predicate = NSPredicate(format: "recordID = %d", recordID) traces = Array(RealmHelper.fetch(from: Trace.self, with: predicate)) if let width = self.navigationController?.navigationBar.frame.width, let height = self.navigationController?.navigationBar.frame.height { marqueeTitle = MarqueeLabel(frame: CGRect(x: 0, y: 0, width: width * 0.7, height: height * 0.9)) } marqueeTitle?.text = "\(record?.departure ?? "unknown") - \(record?.arrival ?? "unknown")" marqueeTitle?.textColor = UIColor.white marqueeTitle?.textAlignment = .center titleLabel.titleView = marqueeTitle distanceLabel.text = "\(record?.distance.roundTo(places: 1) ?? 0) km" ridingTimeLabel.text = record?.ridingTime.hmsFormat restTimeLabel.text = record?.restTime.hmsFormat averageSpeedLabel.text = "\(record?.averageSpeed.roundTo(places: 1) ?? 0) m/s" maximumSpeedLabel.text = "\(record?.maximumSpeed.roundTo(places: 1) ?? 0) m/s" caloriesLabel.text = "\(record?.calories.roundTo(places: 1) ?? 0) kcal" createdAt.text = record?.createdAt.toString() drawRoute(type: PolyLineType.altitude) } //MARK: Actions @IBAction func didTapFilterLabel(_ sender: UITapGestureRecognizer) { let alertView = UIAlertController( title: "원하는 정렬을 선택하세요", message: "\n\n\n\n\n\n\n", preferredStyle: .actionSheet) let pickerView = UIPickerView(frame: CGRect(x: 0, y: 50, width: self.view.bounds.width, height: 130)) pickerView.dataSource = self pickerView.delegate = self alertView.view.addSubview(pickerView) let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { _ in self.filterLabel.text = self.selectedValue.rawValue self.drawRoute(type: self.selectedValue) }) alertView.addAction(action) present(alertView, animated: true, completion: { () -> Void in pickerView.frame.size.width = alertView.view.frame.size.width self.selectedValue = self.pickerData[pickerView.selectedRow(inComponent: 0)] }) } //MARK: Functions func drawRoute(type: PolyLineType) { mapView.clear() var colorsAtCoordinate = [UIColor]() let navigationPath = GMSMutablePath() //패스 설정 및 최대 고도 구함 traces?.forEach({ (trace) in navigationPath.add(CLLocationCoordinate2D(latitude: trace.latitude, longitude: trace.longitude)) switch type { case .speed: if trace.speed > maxSpeed { maxSpeed = trace.speed } case .altitude: if trace.altitude > maxAltitude { maxAltitude = trace.altitude } } }) // red = (현재고도/최대고도), green = 1.0 - red traces?.forEach({ (trace) in switch type { case .speed: if maxSpeed == 0 { redValue = 0.0 } else { redValue = (trace.speed / maxSpeed) } case .altitude: if maxAltitude == 0 { redValue = 0.0 } else { redValue = (trace.altitude / maxAltitude) } } greenValue = 1.0 - redValue colorsAtCoordinate.append(UIColor(red: CGFloat(redValue), green: CGFloat(greenValue), blue: 0, alpha: 1.0)) }) navigationRoute = GMSPolyline(path: navigationPath) var currentColor = UIColor() var spans = [GMSStyleSpan]() var isFirstIndex = true colorsAtCoordinate.forEach { (color) in guard !isFirstIndex else { currentColor = color isFirstIndex = !isFirstIndex return } spans.append(GMSStyleSpan(style: GMSStrokeStyle.gradient(from: currentColor, to: color))) currentColor = color } //경로 생성 guard let route = navigationRoute else { return } route.strokeWidth = 5 // route.strokeColor = UIColor.primary route.spans = spans DispatchQueue.main.async { route.map = self.mapView } //카메라 설정 guard let firstTrace = traces?.first, let traceCount = traces?.count, let middleTrace = traces?[traceCount/2], let lastTrace = traces?.last else { return } mapView.camera = GMSCameraPosition.camera( withLatitude: middleTrace.latitude, longitude: middleTrace.longitude, zoom: 13 ) //출발 마커 생성 let departureMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: firstTrace.latitude, longitude: firstTrace.longitude)) let departureIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) let departureIcon = UIImage(named: "departure") departureIconView.image = departureIcon departureMarker.iconView = departureIconView departureMarker.map = mapView //도착 마커 생성 let arrivalMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: lastTrace.latitude, longitude: lastTrace.longitude)) let arrivalIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) let arrivalIcon = UIImage(named: "arrival") arrivalIconView.image = arrivalIcon arrivalMarker.iconView = arrivalIconView arrivalMarker.map = mapView } } //MARK: UIPickerViewDelegate extension HistoryDetailViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row].rawValue } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectedValue = pickerData[pickerView.selectedRow(inComponent: 0)] } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 35 } }
mit
627981d764f3f265560db0837d01c551
31.380228
137
0.576797
4.835889
false
false
false
false
danielpi/Swift-Playgrounds
Swift-Playgrounds/The Swift Programming Language/LanguageGuide/10-Properties.playground/Contents.swift
1
5489
// Properties // Stored Properties struct FixedLengthRange { var firstValue: Int let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 // Stored Properties of Constant Structure Instances // If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties: let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) //rangeOfFourItems.firstValue = 6 // The above line will report and error, even though firstValue is a variable property // Lazy Stored Properties class DataImporter { /* DataImporter is a class to import data from an external file. The class is assumed to take a non-trivial amount of time to initialize */ var fileName = "data.txt" // the Data Importer class would provide data importing functionality here } class DataManager { lazy var importer = DataImporter() var data = [String]() // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data += ["Some data"] manager.data += ["Some more data"] // the DataImporter instance for the importer property has not yet been created print(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // Computed Properties struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") // Shorthand Setter Declaration // If no name is given for the new value a variable of name newValue is autogenerated struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } } // Read only Computed Properties struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // Property Observers class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896 // Type Properties // Type properties are useful for defining values that are universal to all instances of a particular type, such as a constant property that all instances can use (like a static constant in C), or a variable property that stores a value that is global to all instances of that type (like a static variable in C). // Type Property Syntax struct SomeStructure { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } } // Querying and setting Type Properties print(SomeStructure.storedTypeProperty) // prints "Some value." SomeStructure.storedTypeProperty = "Another value." print(SomeStructure.storedTypeProperty) // prints "Another value." print(SomeEnumeration.computedTypeProperty) // prints "6" print(SomeClass.computedTypeProperty) // prints "27" struct AudioChannel { static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { // cap the new audio level to the threshold level currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputLevelForAllChannels { // store this as the new overall maximum input level AudioChannel.maxInputLevelForAllChannels = currentLevel } } } } var leftChannel = AudioChannel() var rightChannel = AudioChannel() leftChannel.currentLevel = 7 print(leftChannel.currentLevel) print(AudioChannel.maxInputLevelForAllChannels) rightChannel.currentLevel = 11 print(rightChannel.currentLevel) print(AudioChannel.maxInputLevelForAllChannels)
mit
34307888962737803661f6697dad8c8d
29.483333
313
0.681429
4.15053
false
false
false
false
attackFromCat/LivingTVDemo
LivingTVDemo/LivingTVDemo/Classes/Main/Controller/BaseAnchorViewController.swift
1
4908
// // BaseAnchorViewController.swift // LivingTVDemo // // Created by 李翔 on 2017/1/20. // Copyright © 2017年 Lee Xiang. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kHeaderViewH : CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" let kPrettyCellID = "kPrettyCellID" let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 class BaseAnchorViewController: LoadingViewController { // MARK: 定义属性 var baseVM : BaseViewModel! lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPretyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK:- 设置UI界面 extension BaseAnchorViewController { override func setupUI() { // 1.给父类中内容View的引用进行赋值 contentView = collectionView // 2.添加collectionView view.addSubview(collectionView) // 3.调用super.setupUI() super.setupUI() } } // MARK:- 请求数据 extension BaseAnchorViewController { func loadData() { } } // MARK:- 遵守UICollectionView的数据源 extension BaseAnchorViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell // 2.给cell设置数据 cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给HeaderView设置数据 headerView.group = baseVM.anchorGroups[indexPath.section] return headerView } } // MARK:- 遵守UICollectionView的代理协议 extension BaseAnchorViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.取出对应的主播信息 let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] // 2.判断是秀场房间&普通房间 anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc() } private func presentShowRoomVc() { // 1.创建ShowRoomVc let showRoomVc = RoomShowViewController() // 2.以Modal方式弹出 present(showRoomVc, animated: true, completion: nil) } private func pushNormalRoomVc() { // 1.创建NormalRoomVc let normalRoomVc = RoomNormalViewController() // 2.以Push方式弹出 navigationController?.pushViewController(normalRoomVc, animated: true) } }
mit
16df289811d57134bd9723f6d76b7ca4
33.065217
186
0.69113
5.677536
false
false
false
false
mobilegirls/MRTSwift
MRT/DepartureManager.swift
1
5132
// // DepartureManager.swift // MRT // // Created by evan3rd on 2015/5/14. // Copyright (c) 2015年 evan3rd. All rights reserved. // import Foundation private let _SomeManagerSharedInstance = DepartureManager() class DepartureManager { static let sharedInstance = DepartureManager() var stations: Array<Station> = Array() var syncIndex = 0 var _completionBlock: (() -> Void)? var _errorBlock: ((error: NSError) -> Void)? func syncStationData(completionBlock completion:(() -> Void)?, errorBlock: ((error: NSError) -> Void)?) { let urlPath = "http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AP&CaseNo2=17&FileType=2&Lang=C&FolderType=O" let url = NSURL(string: urlPath)! let request = NSURLRequest(URL: url) URLConnection.sharedInstance.asyncConnectionWithRequest(request, completion: { (data, response) -> Void in //let s = NSString(data: data, encoding: NSUTF8StringEncoding) //print(s) let json = JSON(data: data) for (_, subJson): (String, JSON) in json { let st = Station() if let mrtId = subJson["ODMRT_MrtId"].string { st.mrtId = mrtId } if let name = subJson["ODMRT_Name"].string { st.name = name } if let cname = subJson["ODMRT_CName"].string { st.cname = cname } if let code = subJson["ODMRT_Code"].string { st.code = code } if st.mrtId != "9" && st.mrtId != "28" { self.stations.append(st) } } if let block = completion { block() } }) { (error) -> Void in print(error) if let block = errorBlock { block(error: error) } } } func syncDepartureTime(station: Station, completionBlock completion:(() -> Void)?, errorBlock: ((error: NSError) -> Void)?) { let urlPath: String = String(format: "http://data.kaohsiung.gov.tw/Opendata/MrtJsonGet.aspx?site=%@", station.code) let url: NSURL = NSURL(string: urlPath)! let request: NSURLRequest = NSURLRequest(URL: url) URLConnection.sharedInstance.asyncConnectionWithRequest(request, completion: { (data, response) -> Void in let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String //print(responseString) var range = responseString.rangeOfString("<!DOCTYPE html>") if responseString.rangeOfString("<!DOCTYPE html>") != nil { let s = responseString.substringWithRange(Range<String.Index>(start: responseString.startIndex, end: advance(range!.startIndex, -2))) //print(s) let d = (s as NSString).dataUsingEncoding(NSUTF8StringEncoding) let json = JSON(data: d!) for (index, subJson): (String, JSON) in json["MRT"] { let p = Platform() if let arrival = subJson["arrival"].string { p.arrivalTime = arrival } if let nextArrival = subJson["next_arrival"].string { p.nextArrivalTime = nextArrival } if let name = subJson["descr"].string { p.destination = name } if Int(station.code) < 200 { if station.redLine.count > 1 { station.redLine[Int(index)!] = p } else { station.redLine.append(p) } } else if Int(station.code) < 999 { if station.orangeLine.count > 1 { station.orangeLine[Int(index)!] = p } else { station.orangeLine.append(p) } } else { switch index { case "0", "1" : if station.orangeLine.count > 1 { station.orangeLine[Int(index)!] = p } else { station.orangeLine.append(p) } case "2", "3" : if station.redLine.count > 1 { station.redLine[Int(index)! - 2] = p } else { station.redLine.append(p) } default: () } } } } if let block = completion { block() } }) { (error) -> Void in print(error) if let block = errorBlock { block(error: error) } } } func syncMRTDepartureTime(completionBlock completion:(() -> Void)?, errorBlock: ((error: NSError) -> Void)?) { if let block = completion { _completionBlock = block } if let block = errorBlock { _errorBlock = block } syncDepartureTime(stations[syncIndex], completionBlock: { () -> Void in ++self.syncIndex if self.syncIndex < self.stations.count { self.syncMRTDepartureTime(completionBlock: nil, errorBlock: nil) } else { self.syncIndex = 0 if let block = self._completionBlock { block() } } }) { (error) -> Void in print(error) if let block = self._errorBlock { block(error: error) } } } }
mit
51cb6c12fbb0af4366a619d780e8982e
29.182353
141
0.545809
4.170732
false
false
false
false
freshOS/Komponents
Source/Switch.swift
1
2087
// // Switch.swift // Komponents // // Created by Sacha Durand Saint Omer on 12/05/2017. // Copyright © 2017 freshOS. All rights reserved. // import Foundation public struct Switch: Node, Equatable { public var uniqueIdentifier: Int = generateUniqueId() public var propsHash: Int { return props.hashValue } public var children = [IsNode]() let props: SwitchProps public var layout: Layout public let ref: UnsafeMutablePointer<UISwitch>? var registerValueChanged: ((UISwitch) -> Void)? public init(_ on: Bool = false, changed: ((Bool) -> Void)? = nil, props:((inout SwitchProps) -> Void)? = nil, _ layout: Layout? = nil, ref: UnsafeMutablePointer<UISwitch>? = nil) { var defaultProps = SwitchProps() defaultProps.isOn = on if let p = props { var prop = defaultProps p(&prop) self.props = prop } else { self.props = defaultProps } self.layout = layout ?? Layout() self.ref = ref registerValueChanged = { aSwitch in if let aSwitch = aSwitch as? BlockBasedUISwitch, let changed = changed { aSwitch.setCallback(changed) } } } } public func == (lhs: Switch, rhs: Switch) -> Bool { return lhs.props == rhs.props && lhs.layout == rhs.layout } public struct SwitchProps: HasViewProps, Equatable, Hashable { // HasViewProps public var backgroundColor = UIColor.white public var borderColor = UIColor.clear public var borderWidth: CGFloat = 0 public var cornerRadius: CGFloat = 0 public var isHidden = false public var alpha: CGFloat = 1 public var clipsToBounds = false public var isUserInteractionEnabled = true public var isOn = false public var hashValue: Int { return viewPropsHash ^ isOn.hashValue } } public func == (lhs: SwitchProps, rhs: SwitchProps) -> Bool { return lhs.hashValue == rhs.hashValue }
mit
484fb136ef00d59beeaba1febd661d15
27.575342
84
0.601151
4.574561
false
false
false
false
aipeople/PokeIV
Pods/PGoApi/PGoApi/Classes/Unknown6/PGoEncryptHelper.swift
1
1077
// // PGoEncryptHelper.swift // Pods // // Created by PokemonGoSucks on 2016-08-09. // // import Foundation public class PGoEncryptHelper { public func encryptUInt32(input_: Array<UInt32>) -> Array<UInt32> { var output = Array<UInt32>(count: 64, repeatedValue: 0) if (output.count != 64) { return [] } var input = Array<UInt32>(count: 203, repeatedValue: 0) input = subFuncA().subFuncA(input, data_: input_) input = subFuncB().subFuncB(input) input = subFuncC().subFuncC(input) input = subFuncD().subFuncD(input) input = subFuncE().subFuncE(input) input = subFuncF().subFuncF(input) input = subFuncG().subFuncG(input) input = subFuncH().subFuncH(input) input = subFuncI().subFuncI(input) input = subFuncJ().subFuncJ(input) input = subFuncK().subFuncK(input) input = subFuncL().subFuncL(input) output = subFuncM().subFuncM(input, output_: output) return output } }
gpl-3.0
cc5fe715402359c40a61c7c892e63cfa
27.368421
71
0.581244
3.578073
false
false
false
false
nonoesp/iOS-Examples
Swift/SampleProtocol/SampleProtocol/ViewController.swift
1
1495
// // ViewController.swift // SampleProtocol // // Created by Nono Martínez Alonso on 9/7/15. // Copyright (c) 2015 Nono Martínez Alonso. All rights reserved. // import UIKit class ViewController: UIViewController, CustomViewDataSource /* ★ ViewController adopts the CustomViewDataSource protocol*/ { var myView : CustomView! var x : CGFloat = 2.0 override func viewDidLoad() { super.viewDidLoad() // View Setup let screenSize: CGRect = UIScreen.mainScreen().bounds let margin: CGFloat = 15 // CustomView Setup myView = CustomView() myView.frame = CGRectMake(margin, margin, screenSize.width - margin*2, screenSize.height - margin*2) myView.backgroundColor = UIColor.clearColor() myView.dataSource = self; // ★ Define ViewController (self) as CustomView's dataSource self.view.addSubview(myView) } // ★ Implementation of protocol's method func thicknessForCustomView(sender: CustomView) -> CGFloat? { return x } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { let touchPoint = (touches.first as! UITouch).locationInView(self.view) x = touchPoint.x * 0.01 myView.setNeedsDisplay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
604d7ca37075fda76d2e3c4558ca2d03
28.74
125
0.642233
4.827922
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
03-YFPageViewExtensionDemo/YFPageViewExtensionDemo/YFPageView/YFPageCollectionView.swift
1
6633
// // YFPageCollectionView.swift // YFPageViewExtensionDemo // // Created by Allison on 2017/5/21. // Copyright © 2017年 Allison. All rights reserved. // import UIKit protocol YFPageCollectionViewDataSource : class { func numberOfSections(in pageCollectionView : YFPageCollectionView) -> Int func pageCollectionView(_ collectionView: YFPageCollectionView, numberOfItemsInSection section: Int) -> Int func pageCollectionView(_ pageCollectionView : YFPageCollectionView ,_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell } //private let kCollectionViewCell = "kCollectionViewCell" class YFPageCollectionView: UIView { weak var dataSource : YFPageCollectionViewDataSource? fileprivate var titlesArr:[String] fileprivate var isTitleInTop: Bool fileprivate var layout: YFPageCollectionViewLayout fileprivate var style: YFPageStyle fileprivate var collectionView : UICollectionView! fileprivate var pageControl : UIPageControl! fileprivate var titleView : YFTitleView! fileprivate var sourceIndexPath : IndexPath = IndexPath(item: 0, section: 0) init(frame: CGRect,titles:[String],isTitleInTop :Bool,layout:YFPageCollectionViewLayout,style:YFPageStyle) { self.titlesArr = titles self.isTitleInTop = isTitleInTop self.layout = layout self.style = style super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension YFPageCollectionView{ fileprivate func setupUI(){ //创建titleView let titleY = isTitleInTop ? 0 :bounds.height - style.titleHeight let titleFrame = CGRect(x: 0, y: titleY, width: bounds.width, height: style.titleHeight) titleView = YFTitleView(frame: titleFrame, titles: titlesArr, style: style) addSubview(titleView) titleView.delegate = self titleView.backgroundColor = UIColor.randomColor() //2.创建UIPageControl let pageControlHeight :CGFloat = 20 let pageControlY = isTitleInTop ? (bounds.height - pageControlHeight) : (bounds.height - pageControlHeight - style.titleHeight) let pageControlFrame = CGRect(x: 0, y: pageControlY, width: bounds.width, height: pageControlHeight) pageControl = UIPageControl(frame: pageControlFrame) pageControl.numberOfPages = 4 pageControl.isEnabled = false addSubview(pageControl) pageControl.backgroundColor = UIColor.red //3.创建UICollectionView let collectionViewY = isTitleInTop ? style.titleHeight : 0 let collectionViewFrame = CGRect(x: 0, y: collectionViewY, width: bounds.width, height: bounds.height - style.titleHeight - pageControlHeight) collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self addSubview(collectionView) collectionView.backgroundColor = UIColor.randomColor() } } // MARK:- 对外暴露的方法 extension YFPageCollectionView { //swift中允许方法重载 OC中没有 // func register(_ cell AnyClass?) // func register(_ nib : UINib) // 有_会报错 去掉_不会报错(有外部参数,作为方法的一部分) func register(cell : AnyClass?, identifier : String) { collectionView.register(cell, forCellWithReuseIdentifier: identifier) } func register(nib : UINib, identifier : String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } } // MARK:- UICollectionViewDataSource extension YFPageCollectionView:UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSections(in: self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 } return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.pageCollectionView(self, collectionView, cellForItemAt: indexPath) } } //MARK:-UICollectionViewDelegate extension YFPageCollectionView : UICollectionViewDelegate{ //停止减速 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewEndScroll() } //2.没有减速 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollViewEndScroll() } } fileprivate func scrollViewEndScroll() { // 1.取出在屏幕中显示的Cell let point = CGPoint(x: layout.sectionInset.left + 1 + collectionView.contentOffset.x, y: layout.sectionInset.top + 1) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } // 2.判断分组是否有发生改变 if sourceIndexPath.section != indexPath.section { // 3.1.修改pageControl的个数 let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 // 3.2.设置titleView位置 titleView.setTitleWithProgress(1.0, sourceIndex: sourceIndexPath.section, targetIndex: indexPath.section) // 3.3.记录最新indexPath sourceIndexPath = indexPath } // 3.根据indexPath设置pageControl pageControl.currentPage = indexPath.item / (layout.cols * layout.rows) } } // MARK:- YFTitleViewDelegate extension YFPageCollectionView : YFTitleViewDelegate { func titleView(_ titleView: YFTitleView, targetIndex: Int) { let indexPath = IndexPath(item: 0, section: targetIndex) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) collectionView.contentOffset.x -= layout.sectionInset.left scrollViewEndScroll() } }
mit
06bd63a7b7d1d143ae25bcf540131d07
34.428571
168
0.687345
5.216828
false
false
false
false
lwluck/PasswordKeyboard
Keyboard/KeyboardViewController.swift
1
5402
// // KeyboardViewController.swift // Keyboard // // Created by Lloyd Luck on 11/20/16. // Copyright © 2016 Lloyd Luck. All rights reserved. // import UIKit class KeyboardViewController: UIInputViewController, AuthenticationDelegate { var authenticationLabel: UILabel? var authenticationView: AuthenticationView? @IBOutlet var nextKeyboardButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupKeyboardForAuthentication() } func didPressNextKeyboard(_ sender: UIView) { advanceToNextInputMode() } func authenticationSuccessful() { print("Authentication Successful") updateKeyboardAfterAuthentication() } func setupKeyboardForAuthentication() { let nib = UINib(nibName: "AuthenticationView", bundle: nil) let objects = nib.instantiate(withOwner: self, options: nil) let authenticationView = objects[0] as! AuthenticationView self.authenticationView = authenticationView authenticationView.translatesAutoresizingMaskIntoConstraints = false authenticationView.delegate = self view.addSubview(authenticationView) authenticationView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true authenticationView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true authenticationView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true authenticationView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } func updateKeyboardAfterAuthentication() { authenticationView?.removeFromSuperview() // Perform custom UI setup here self.nextKeyboardButton = UIButton(type: .system) self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: []) self.nextKeyboardButton.sizeToFit() self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) self.view.addSubview(self.nextKeyboardButton) self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true let defaults = UserDefaults(suiteName: "group.com.lwluck.passwordkeyboard") var buttons: [UIButton] = [] if let logins = defaults?.dictionary(forKey: "logins") { let usernames: [String] = Array(logins.keys) buttons = createButtons(titles: usernames) } let firstButton = buttons.removeFirst() view.addSubview(firstButton) firstButton.topAnchor.constraint(equalTo: view.topAnchor).isActive = true firstButton.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true firstButton.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true var currentTopView: UIView = firstButton for button in buttons { view.addSubview(button) button.topAnchor.constraint(equalTo: currentTopView.bottomAnchor).isActive = true button.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true button.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true currentTopView = button } } override func textWillChange(_ textInput: UITextInput?) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(_ textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { textColor = UIColor.white } else { textColor = UIColor.black } // self.nextKeyboardButton.setTitleColor(textColor, for: []) } func didPressKeyboardButton(_ button: UIButton) { guard let defaults = UserDefaults(suiteName: "group.com.lwluck.passwordkeyboard"), let logins = defaults.dictionary(forKey: "logins"), let username = button.title(for: .normal), let password = logins[username] as? String else { return } (textDocumentProxy as UIKeyInput).insertText(username) print("Username: \(username)") print("Password: \(password)") print("Saving password to pasteboard") print() let pasteboard = UIPasteboard.general pasteboard.string = password } func createButtons(titles: [String], selector: Selector = #selector(didPressKeyboardButton(_:))) -> [UIButton] { return titles.map { (title) -> UIButton in let button = UIButton(type: .system) button.setTitle(title, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor(white: 1.0, alpha: 1.0) button.setTitleColor(UIColor.darkGray, for: .normal) button.addTarget(self, action: selector, for: .touchUpInside) return button } } }
mit
a95423e0a4361fe457a4c2e6fe844554
37.578571
130
0.678578
5.248785
false
false
false
false
FotiosTragopoulos/Core-Geometry
Core Geometry/Ana3ViewCoordinates_X.swift
1
1626
// // Ana3ViewCoordinates_X.swift // Core Geometry // // Created by Fotios Tragopoulos on 22/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Ana3ViewCoordinates_X: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() context?.setLineWidth(5.0) context?.setStrokeColor(UIColor.black.cgColor) let xView = viewWithTag(51)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(51)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(51)?.frame.size.width let height = self.viewWithTag(51)?.frame.size.height let size = CGSize(width: width! * 0.6, height: height! * 0.5) let linePlacementX = CGFloat(size.width/2) let linePlacementY = CGFloat(size.height/2) context?.move(to: CGPoint(x: (xView! - linePlacementX), y: (yView! + linePlacementY))) context?.addLine(to: CGPoint(x: (xView! - linePlacementX), y: (yView! - linePlacementY))) context?.strokePath() context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
apache-2.0
2ae19c0d8296e0a98e306af6607ae9f8
36.790698
219
0.64
3.992629
false
false
false
false
cocoascientist/Playgrounds
BouncingBall.playground/Contents.swift
1
2140
//: # Bouncing Ball Animation //: //: This playground examines how to build an bouncing animation //: //: The examples are based on [this stackoverflow post](http://stackoverflow.com/a/25931981) by [@BCBlanka](http://stackoverflow.com/users/2768282/bcblanka). import UIKit import XCPlayground //: Define three animations let translation = CAKeyframeAnimation(keyPath: "transform.translation.y") translation.values = [-600, 20, 0] translation.keyTimes = [0.0, 0.85, 1.0] translation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) translation.autoreverses = true translation.duration = 1.0 translation.repeatCount = Float.infinity let scaleX = CAKeyframeAnimation(keyPath: "transform.scale.x") scaleX.values = [0.75, 0.75, 1.0] scaleX.keyTimes = [0.0, 0.85, 1.0] scaleX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) scaleX.autoreverses = true scaleX.duration = 1.0 scaleX.repeatCount = Float.infinity let scaleY = CAKeyframeAnimation(keyPath: "transform.scale.y") scaleY.values = [0.75, 1.0, 0.85] scaleY.keyTimes = [0.1, 0.5, 1.0] scaleY.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) scaleY.autoreverses = true scaleY.duration = 1.0 scaleY.repeatCount = Float.infinity //: Create container view and ball view let containerView = UIView(frame: CGRectMake(0, 0, 150.0, 760.0)) let ballView = UIView(frame: CGRectMake(0, 0, 50, 50)) containerView.addSubview(ballView) containerView.backgroundColor = UIColor.blackColor() ballView.backgroundColor = UIColor.redColor() ballView.center = CGPointMake(CGRectGetMidX(containerView.frame), CGRectGetMaxY(containerView.frame) - CGRectGetHeight(ballView.frame)) ballView.layer.cornerRadius = 25.0 ballView.layer.addAnimation(translation, forKey: "translation") ballView.layer.addAnimation(scaleX, forKey: "scaleX") ballView.layer.addAnimation(scaleY, forKey: "scaleY") //: Mark the `containerView` as the `liveView` for the current playground page and `needsIndefiniteExecution` to `true. XCPlaygroundPage.currentPage.liveView = containerView XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
16f5d708e8eb3bea9afe448a17ee94e0
37.214286
157
0.786916
3.962963
false
false
false
false
wdkk/CAIM
Basic/answer/caim05_2eftouch_A/basic/ImageToolBox.swift
1
10845
// // ImageToolBox.swift // CAIM Project // https://kengolab.net/CreApp/wiki/ // // Copyright (c) Watanabe-DENKI Inc. // https://wdkk.co.jp/ // // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php // import Foundation // 画像処理ツールクラス class ImageToolBox { // 四角を描く関数(透明度つき) static func fillRect(_ img:CAIMImage, x1:Int, y1:Int, x2:Int, y2:Int, color:CAIMColor, opacity:Float=1.0) { // 画像のデータを取得 let mat = img.matrix // 画像のピクセルデータ let wid = img.width // 画像の横幅 let hgt = img.height // 画像の縦幅 // 2点の座標値の小さい方、大きい方を判別して別の変数に入れる let min_x:Int = min(x1, x2) let min_y:Int = min(y1, y2) let max_x:Int = max(x1, x2) let max_y:Int = max(y1, y2) // min_x~max_x, min_y~max_yまでの範囲を塗る for y in min_y ... max_y { for x in min_x ... max_x { // x,yが画像外にはみだしたら、エラー防止のためcontinueで処理をスキップする if(x < 0 || y < 0 || x >= wid || y >= hgt) { continue } mat[y][x].R = color.R * opacity + mat[y][x].R * (1.0-opacity) mat[y][x].G = color.G * opacity + mat[y][x].G * (1.0-opacity) mat[y][x].B = color.B * opacity + mat[y][x].B * (1.0-opacity) mat[y][x].A = color.A * opacity + mat[y][x].A * (1.0-opacity) } } } // 丸を描く関数(透明度付き) static func fillCircle(_ img:CAIMImage, cx:Int, cy:Int, radius:Int, color:CAIMColor, opacity:Float=1.0) { // 画像のデータを取得 let mat = img.matrix // 画像のピクセルデータ let wid = img.width // 画像の横幅 let hgt = img.height // 画像の縦幅 // 処理の範囲を決める let min_x:Int = cx - radius let min_y:Int = cy - radius let max_x:Int = cx + radius let max_y:Int = cy + radius // min_x~max_x, min_y~max_yまでの範囲を塗る for y in min_y ... max_y { for x in min_x ... max_x { // x,yが画像外にはみだしたら、エラー防止のためcontinueで処理をスキップする if(x < 0 || y < 0 || x >= wid || y >= hgt) { continue } // 中心点からの距離 let dist:Float = sqrt(Float((x-cx)*(x-cx)) + Float((y-cy)*(y-cy))) // 中心点(cx, cy)からの距離が半径radius以内なら塗る if( dist <= Float(radius) ) { mat[y][x].R = color.R * opacity + mat[y][x].R * (1.0-opacity) mat[y][x].G = color.G * opacity + mat[y][x].G * (1.0-opacity) mat[y][x].B = color.B * opacity + mat[y][x].B * (1.0-opacity) mat[y][x].A = color.A * opacity + mat[y][x].A * (1.0-opacity) } } } } // Cosドーム上の円を描く static func fillDome(_ img:CAIMImage, cx:Int, cy:Int, radius:Int, color:CAIMColor, opacity:Float) { // 画像のデータを取得 let mat = img.matrix // 画像のピクセルデータ let wid = img.width // 画像の横幅 let hgt = img.height // 画像の縦幅 // 処理の範囲を決める let min_x:Int = cx - radius let min_y:Int = cy - radius let max_x:Int = cx + radius let max_y:Int = cy + radius // min_x~max_x, min_y~max_yまでの範囲を塗る for y in min_y ... max_y { for x in min_x ... max_x { // x,yが画像外にはみだしたら、エラー防止のためcontinueで処理をスキップする if(x < 0 || y < 0 || x >= wid || y >= hgt) { continue } // 中心点からの距離 let dist:Float = sqrt(Float((x-cx)*(x-cx)) + Float((y-cy)*(y-cy))) // 中心点(cx, cy)からの距離が半径radius以内なら塗る if( dist <= Float(radius) ) { // 中心からの距離でcosを計算してαとして用いる var alpha = Float(cos(Double(dist) / Double(radius) * Double.pi / 2.0)) // αに不透明度opacityを掛ける alpha *= opacity mat[y][x].R = color.R * alpha + mat[y][x].R * (1.0-alpha) mat[y][x].G = color.G * alpha + mat[y][x].G * (1.0-alpha) mat[y][x].B = color.B * alpha + mat[y][x].B * (1.0-alpha) mat[y][x].A = color.A * alpha + mat[y][x].A * (1.0-alpha) } } } } // Cosドーム上の円を描く static func fillDomeFast(_ img:CAIMImage, cx:Int, cy:Int, radius:Int, color:CAIMColor, opacity:Float) { // 画像のデータを取得 let mat = img.matrix // 画像のピクセルデータ let wid = img.width // 画像の横幅 let hgt = img.height // 画像の縦幅 // 処理の範囲を決める(はみ出し処理込み) let min_x:Int = max(cx - radius, 0) let min_y:Int = max(cy - radius, 0) let max_x:Int = min(cx + radius, wid-1) let max_y:Int = min(cy + radius, hgt-1) let r2:Int = radius * radius let k:Float = 1.0 / Float(r2) * Float.pi / 2.0 // min_x~max_x, min_y~max_yまでの範囲を塗る for y in min_y ... max_y { let dy2:Int = (y-cy)*(y-cy) for x in min_x ... max_x { // 中心点からの距離 let dx2:Int = (x-cx)*(x-cx) let dist2:Int = dx2 + dy2 // 中心点(cx, cy)からの距離が半径radius以内なら塗る if( dist2 <= r2 ) { // 中心からの距離でcosを計算してαとして用いる let alpha:Float = cos(Float(dist2) * k) * opacity let beta:Float = 1.0-alpha mat[y][x].R = color.R * alpha + mat[y][x].R * beta mat[y][x].G = color.G * alpha + mat[y][x].G * beta mat[y][x].B = color.B * alpha + mat[y][x].B * beta mat[y][x].A = color.A * alpha + mat[y][x].A * beta } } } } // 直線を引く static func drawLine(_ img:CAIMImage, x1:Int, y1:Int, x2:Int, y2:Int, color:CAIMColor, opacity:Float) { // 画像のデータを取得 let mat = img.matrix // 画像のピクセルデータ let wid = img.width // 画像の横幅 let hgt = img.height // 画像の縦幅 let dx:Int = x2 - x1 // xの移動量(マイナス含む) let dy:Int = y2 - y1 // yの移動量(マイナス含む) var px:Int = x1 var py:Int = y1 var next_step_f:Float = 0.0 // x方向の1ステップの移動量(正負方向の判定) var step_x:Int = 1 if(dx < 0) { step_x = -1 } // y方向の1ステップの移動量(正負方向の判定) var step_y:Int = 1 if(dy < 0) { step_y = -1 } // 移動量の絶対値 let absdx:Int = abs(dx) let absdy:Int = abs(dy) // 指定した最初の1点を、はみ出していなければ描画する if(px >= 0 && py >= 0 && px < wid && py < hgt) { mat[py][px].R = color.R * opacity + mat[py][px].R * (1.0-opacity) mat[py][px].G = color.G * opacity + mat[py][px].G * (1.0-opacity) mat[py][px].B = color.B * opacity + mat[py][px].B * (1.0-opacity) mat[py][px].A = color.A * opacity + mat[py][px].A * (1.0-opacity) } // 横方向移動量が多い時,xを1ずつ移動させながら、y方向はどこで1移動させるかをnext_step_fで判断しながら処理する if(absdx > absdy) { let sf:Float = Float(absdy) / Float(absdx) next_step_f = sf // x方向移動を1ピクセルずつ行っていく while(px != x2) { // next_step_fが0.5を超えたらy方向にも1ピクセル移動する if(next_step_f >= 0.5) { py += step_y next_step_f -= 1.0 // 1.0減らして改めて計算し直す } // x方向に1ピクセル移動する px += step_x next_step_f += sf // ステップの値をsf増やす // はみ出し防止(はみ出していたらcontinueで処理をスキップ) if(px < 0 || py < 0 || px >= wid || py >= hgt) { continue } // ピクセルの色を塗る。opacityの値で mat[py][px].R = color.R * opacity + mat[py][px].R * (1.0-opacity) mat[py][px].G = color.G * opacity + mat[py][px].G * (1.0-opacity) mat[py][px].B = color.B * opacity + mat[py][px].B * (1.0-opacity) mat[py][px].A = color.A * opacity + mat[py][px].A * (1.0-opacity) } } // 縦方向移動量が多い場合、yを1ずつ移動させながら、x方向はどこで1移動させるかをnext_step_fで判断しながら処理する else { let sf:Float = Float(absdx) / Float(absdy) next_step_f = sf // 終了点にたどり着くまで続ける while(py != y2) { // next_step_fが0.5を超えたらx方向にも1ピクセル移動する if(next_step_f >= 0.5) { px += step_x next_step_f -= 1.0 // 1.0減らして改めて計算し直す } // y方向に1ピクセル移動する py += step_y next_step_f += sf // ステップの値をsf増やす if(px < 0 || py < 0 || px >= wid || py >= hgt) { continue } mat[py][px].R = color.R * opacity + mat[py][px].R * (1.0-opacity) mat[py][px].G = color.G * opacity + mat[py][px].G * (1.0-opacity) mat[py][px].B = color.B * opacity + mat[py][px].B * (1.0-opacity) mat[py][px].A = color.A * opacity + mat[py][px].A * (1.0-opacity) } } } }
mit
ff3c49660f9df80df0c383ea6649f955
37.058333
111
0.447011
2.933205
false
false
false
false
acastano/swift-bootstrap
userinterfacekit/Sources/Classes/Utils/Extensions/UIImage+Utils.swift
1
4703
import UIKit public extension UIImage { public func croppedImage(_ bounds:CGRect) -> UIImage? { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale) let point = CGPoint(x:bounds.origin.x, y:bounds.origin.y) draw(at: point) let croppedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return croppedImage } public func resizeWith(_ percentage: CGFloat) -> UIImage? { let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage))) imageView.contentMode = .scaleAspectFit imageView.image = self UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.render(in: context) guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return result } public class func mergeBundleImagesUsingTopAndBottomAsTringles(_ topImageName:String?, bottomImageName:String?) -> UIImage? { var mergedImage: UIImage? if let topImageName = topImageName, let topImage = UIImage(named:topImageName), let bottomImageName = bottomImageName, let bottomImage = UIImage(named:bottomImageName) { mergedImage = mergeImagesUsingTopAndBottomAsTringles(topImage, bottomImage: bottomImage) } return mergedImage } public class func mergeImagesUsingTopAndBottomAsTringles(_ topImage:UIImage?, bottomImage:UIImage?) -> UIImage? { var mergedImage: UIImage? if let topImage = topImage, let bottomImage = bottomImage { let scale = UIScreen.main.scale let size = CGSize(width: topImage.size.width, height: topImage.size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.beginPath () context?.move(to: CGPoint(x: 0, y: 0)) context?.addLine(to: CGPoint(x: size.width, y: 0)) context?.addLine(to: CGPoint(x: size.width, y: size.height)) context?.addLine(to: CGPoint(x: 0, y: size.height)) context?.addLine(to: CGPoint(x: size.width, y: 0)) topImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) context?.closePath() context?.clip() bottomImage.draw(in: CGRect(x: 0,y: 0, width: size.width, height: size.height)) mergedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } return mergedImage } public func aspectFillImage(_ bounds:CGRect) -> UIImage? { let newSize = sizeWithContentMode(.scaleAspectFill, bounds:bounds) UIGraphicsBeginImageContextWithOptions(newSize, false, scale) let x = (newSize.width - bounds.width) / 2 let y = (newSize.height - bounds.height) / 2 let rect = CGRect(x: -x, y: -y, width: newSize.width, height: newSize.height) draw(in: rect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } fileprivate func sizeWithContentMode(_ contentMode:UIViewContentMode, bounds:CGRect) -> CGSize { let hRatio = bounds.width / size.width let vRatio = bounds.height / size.height var ratio = CGFloat(0) switch (contentMode) { case .scaleAspectFill: ratio = max(hRatio, vRatio) case .scaleAspectFit: ratio = min(hRatio, vRatio) default: ratio = 1 } let newSize = CGSize(width: size.width * ratio, height: size.height * ratio) return newSize } }
apache-2.0
400fdf1417dba4d5c54f79f3aa2cdb5b
28.955414
145
0.549862
5.59881
false
false
false
false
soffes/X
Sources/X/CGRect.swift
1
2841
import Foundation import CoreGraphics #if os(macOS) public func NSStringFromCGRect(_ rect: CGRect) -> String! { return NSStringFromRect(rect) } public func CGRectFromString(_ string: String!) -> CGRect { return NSRectFromString(string) as CGRect } #else import UIKit #endif extension CGRect { public var stringRepresentation: String { #if os(macOS) return NSStringFromCGRect(self) #else return NSCoder.string(for: self) #endif } public init(string: String) { #if os(macOS) self = CGRectFromString(string) #else self = NSCoder.cgRect(for: string) #endif } public func aspectFit(_ boundingRect: CGRect) -> CGRect { let size = self.size.aspectFit(boundingRect.size) var origin = boundingRect.origin origin.x += (boundingRect.size.width - size.width) / 2.0 origin.y += (boundingRect.size.height - size.height) / 2.0 return CGRect(origin: origin, size: size) } func aspectFill(_ minimumRect: CGRect) -> CGRect { let size = self.size.aspectFill(minimumRect.size) return CGRect( x: (minimumRect.size.width - size.width) / 2.0, y: (minimumRect.size.height - size.height) / 2.0, width: size.width, height: size.height ) } public func apply(contentMode: ContentMode, bounds: CGRect) -> CGRect { var rect = self switch contentMode { case .scaleToFill: return bounds case .scaleAspectFit: return aspectFit(bounds) case .scaleAspectFill: return aspectFill(bounds) case .redraw: return rect case .center: rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .top: rect.origin.y = 0 rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 return rect case .bottom: rect.origin.x = (bounds.size.width - rect.size.width) / 2.0 rect.origin.y = bounds.size.height - rect.size.height return rect case .left: rect.origin.x = 0 rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .right: rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = (bounds.size.height - rect.size.height) / 2.0 return rect case .topLeft: rect.origin = CGPoint.zero return rect case .topRight: rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = 0 return rect case .bottomLeft: rect.origin.x = 0 rect.origin.y = bounds.size.height - rect.size.height return rect case .bottomRight: rect.origin.x = bounds.size.width - rect.size.width rect.origin.y = bounds.size.height - rect.size.height return rect #if os(iOS) || os(tvOS) @unknown default: assertionFailure("Unknown content mode") return rect #endif } } }
mit
8fe69f33ecc10d382ad6774da0f43675
26.057143
72
0.657163
3.265517
false
false
false
false
Obisoft2017/BeautyTeamiOS
BeautyTeam/BeautyTeam/GU_RelationR.swift
1
1713
// // GU_RelationR.swift // BeautyTeam // // Created by Carl Lee on 5/22/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import UIKit class GU_RelationR: InitialProtocol { var GU_RelationId: Int! var ObisoftUserId: String! var ObisoftUsr: ObisoftUser! var groupId: Int! var group: Group! var relationType: GroupUserRelationType! var createrName: String! var createrID: String! required init(rawData: [String : AnyObject?]) { guard let GU_RelationId = rawData["GU_RelationId"] as? Int else { fatalError() } guard let ObisoftUserId = rawData["ObisoftUserId"] as? String else { fatalError() } guard let groupId = rawData["GroupId"] as? Int else { fatalError() } guard let group_raw = rawData["Group"] as? Dictionary<String, AnyObject> else { fatalError() } guard let relationType_raw = rawData["RelationType"] as? Int else { fatalError() } guard let createrName = rawData["CreaterName"] as? String else { fatalError() } guard let createrID = rawData["CreaterID"] as? String else { fatalError() } guard let relationType = GroupUserRelationType(rawValue: relationType_raw) else { fatalError() } self.GU_RelationId = GU_RelationId self.ObisoftUserId = ObisoftUserId self.groupId = groupId self.group = Group(rawData: group_raw) self.createrName = createrName self.createrID = createrID self.relationType = relationType } }
apache-2.0
3a7e4a6881352a79a067a15363321af3
28.517241
89
0.596379
4.125301
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/Message+BinaryAdditions.swift
8
5244
// Sources/SwiftProtobuf/Message+BinaryAdditions.swift - Per-type binary coding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Extensions to `Message` to provide binary coding and decoding. /// // ----------------------------------------------------------------------------- import Foundation /// Binary encoding and decoding methods for messages. public extension Message { /// Returns a `Data` value containing the Protocol Buffer binary format /// serialization of the message. /// /// - Parameters: /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - Returns: A `Data` value containing the binary serialization of the /// message. /// - Throws: `BinaryEncodingError` if encoding fails. func serializedData(partial: Bool = false) throws -> Data { if !partial && !isInitialized { throw BinaryEncodingError.missingRequiredFields } let requiredSize = try serializedDataSize() var data = Data(count: requiredSize) try data.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) in var visitor = BinaryEncodingVisitor(forWritingInto: pointer) try traverse(visitor: &visitor) // Currently not exposing this from the api because it really would be // an internal error in the library and should never happen. assert(requiredSize == visitor.encoder.distance(pointer: pointer)) } return data } /// Returns the size in bytes required to encode the message in binary format. /// This is used by `serializedData()` to precalculate the size of the buffer /// so that encoding can proceed without bounds checks or reallocation. internal func serializedDataSize() throws -> Int { // Note: since this api is internal, it doesn't currently worry about // needing a partial argument to handle proto2 syntax required fields. // If this become public, it will need that added. var visitor = BinaryEncodingSizeVisitor() try traverse(visitor: &visitor) return visitor.serializedSize } /// Creates a new message by decoding the given `Data` value containing a /// serialized message in Protocol Buffer binary format. /// /// - Parameters: /// - serializedData: The binary-encoded message data to decode. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Throws: `BinaryDecodingError` if decoding fails. init( serializedData data: Data, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws { self.init() try merge(serializedData: data, extensions: extensions, partial: partial, options: options) } /// Updates the message by decoding the given `Data` value containing a /// serialized message in Protocol Buffer binary format into the receiver. /// /// - Note: If this method throws an error, the message may still have been /// partially mutated by the binary data that was decoded before the error /// occurred. /// /// - Parameters: /// - serializedData: The binary-encoded message data to decode. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Throws: `BinaryDecodingError` if decoding fails. mutating func merge( serializedData data: Data, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws { if !data.isEmpty { try data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in var decoder = BinaryDecoder(forReadingFrom: pointer, count: data.count, options: options, extensions: extensions) try decoder.decodeFullMessage(message: &self) } } if !partial && !isInitialized { throw BinaryDecodingError.missingRequiredFields } } }
gpl-3.0
88ee12bb2186f81aad09827a0e44dd1e
43.067227
95
0.667048
4.965909
false
false
false
false
edouardjamin/30daysSwift
Day 15 - TwitterSplash/Day 15 - TwitterSplash/AppDelegate.swift
1
3874
// // AppDelegate.swift // Day 15 - TwitterSplash // // Created by Edouard Jamin on 06/03/16. // Copyright © 2016 Edouard Jamin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var mask :CALayer? var imageView :UIImageView? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. print("Starting") self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = UIViewController() // Twitter Screen imageView = UIImageView(frame: self.window!.frame) imageView!.image = UIImage(named: "twitterscreen") self.window!.addSubview(imageView!) // Logo Mask self.mask = CALayer() self.mask!.contents = UIImage(named: "twitter logo mask")!.CGImage self.mask!.bounds = CGRect(x: 0, y: 0, width: 100, height: 100) self.mask!.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.mask!.position = CGPoint(x: imageView!.frame.size.width/2, y: imageView!.frame.size.height/2) imageView!.layer.mask = mask animateSplashScreen() self.window!.backgroundColor = UIColor(red:0.117, green:0.631, blue:0.949, alpha:1) self.window!.makeKeyAndVisible() UIApplication.sharedApplication().statusBarHidden = true print("Running") return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func animateSplashScreen() { let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 0.6 keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)] let initialBounds = NSValue(CGRect: mask!.bounds) let secondBounds = NSValue(CGRect: CGRect(x: 0, y: 0, width: 90, height: 90)) let finalBounds = NSValue(CGRect: CGRect(x: 0, y: 0, width: 1500, height: 1500)) keyFrameAnimation.values = [initialBounds, secondBounds, finalBounds] keyFrameAnimation.keyTimes = [0, 0.3, 1] self.mask!.addAnimation(keyFrameAnimation, forKey: "bounds") } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.imageView!.layer.mask = nil } }
mit
83ddf1a9bd6594d97898f1306ed36f05
41.097826
279
0.762716
4.312918
false
false
false
false
IvanVorobei/Sparrow
sparrow/extension/SPUIImageExtension.swift
2
2337
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public extension UIImage { public func resize(newWidth: CGFloat) -> UIImage { let scale = newWidth / self.size.width let newHeight = self.size.height * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func resize(to size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0); self.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: size.width, height: size.height))) let resizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resizeImage } public class func drawFromView(view: UIView) -> UIImage { UIGraphicsBeginImageContext(view.frame.size) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
9ead03415f491a46c0bc02a1df7b32d4
44.803922
105
0.723031
4.970213
false
false
false
false
arietis/codility-swift
8.1.swift
1
519
public func solution(inout A : [Int]) -> Int { // write your code in Swift 2.2 if A.count == 0 { return -1 } var a: [Int : Int] = [:] for i in 0..<A.count { if a[A[i]] != nil { a[A[i]]? += 1 } else { a[A[i]] = 1 } } var domValue = Int(Double(A.count) * 0.5) var dom = -1 for i in a.keys { if a[i] > domValue { dom = i domValue = a[i]! } } return A.indexOf(dom) ?? -1 }
mit
67d493412b46266d583f224ab5c2df08
16.896552
46
0.387283
3.107784
false
false
false
false
haawa799/WaniKani-iOS
WaniKani/Model/LevelProgression.swift
1
1084
// // swift // WaniKani // // Created by Andriy K. on 9/30/15. // Copyright © 2015 Andriy K. All rights reserved. // import RealmSwift import WaniKit public class LevelProgression: Object { // Dictionary keys private static let keyRadicalsProgress = "radicals_progress" private static let keyRadicalsTotal = "radicals_total" private static let keyKanjiProgress = "kanji_progress" private static let keyKanjiTotal = "kanji_total" // public dynamic var radicalsProgress: Int = 0 public dynamic var radicalsTotal: Int = 0 public dynamic var kanjiProgress: Int = 0 public dynamic var kanjiTotal: Int = 0 } extension LevelProgression { func updateWith(levelProgressInfo: LevelProgressionInfo) { radicalsProgress = levelProgressInfo.radicalsProgress ?? 0 radicalsTotal = levelProgressInfo.radicalsTotal ?? 0 kanjiProgress = levelProgressInfo.kanjiProgress ?? 0 kanjiTotal = levelProgressInfo.kanjiTotal ?? 0 } convenience init(levelProgressInfo: LevelProgressionInfo) { self.init() updateWith(levelProgressInfo) } }
gpl-3.0
296e5933b29ac903d855d521cfb1d426
25.439024
62
0.738689
3.938182
false
false
false
false
almas73/Voucher
Voucher iOS App/ViewController.swift
1
2622
// // ViewController.swift // Voucher iOS App // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // import UIKit import Voucher class ViewController: UIViewController, VoucherServerDelegate { var server: VoucherServer? @IBOutlet var serverStatusLabel: UILabel! @IBOutlet var connectionStatusLabel: UILabel! deinit { self.server?.stop() self.server?.delegate = nil self.server = nil } override func viewDidLoad() { super.viewDidLoad() let uniqueId = "VoucherTest" self.server = VoucherServer(uniqueSharedId: uniqueId) self.server?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.server?.startAdvertisingWithRequestHandler { (displayName, responseHandler) -> Void in let alertController = UIAlertController(title: "Allow Auth?", message: "Allow \"\(displayName)\" access to your login?", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Not Now", style: .Cancel, handler: { action in responseHandler(nil, nil) })) alertController.addAction(UIAlertAction(title: "Allow", style: .Default, handler: { action in // For our authData, use a token string (to simulate an OAuth token, for example) let authData = "THIS IS AN AUTH TOKEN".dataUsingEncoding(NSUTF8StringEncoding)! responseHandler(authData, nil) })) self.presentViewController(alertController, animated: true, completion: nil) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.server?.stop() } // MARK: - VoucherServerDelegate func voucherServer(server: VoucherServer, didUpdateAdvertising isAdvertising: Bool) { var text = "❌ Server Offline." if (isAdvertising) { text = "✅ Server Online." } self.serverStatusLabel.text = text self.connectionStatusLabel.hidden = !isAdvertising } func voucherServer(server: VoucherServer, didUpdateConnectionToClient isConnectedToClient: Bool) { var text = "📡 Waiting for Connection..." if (isConnectedToClient) { text = "✅ Connected." } self.connectionStatusLabel.text = text } }
mit
c8d2b01848b7b3b3c8ebb3a8a123d1df
30.095238
156
0.643951
5.032755
false
false
false
false
flowsprenger/RxLifx-Swift
RxLifxExample/RxLifxExample/DetailViewController.swift
1
5989
/* Copyright 2017 Florian Sprenger 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 LifxDomain import RxLifxApi class DetailViewController: UIViewController { @IBOutlet var background: UIView! @IBOutlet weak var powerSwitch: UISwitch! @IBOutlet weak var labelTextField: UITextField! @IBOutlet weak var hueSlider: UISlider! @IBOutlet weak var saturationSlider: UISlider! @IBOutlet weak var brightnessSlider: UISlider! @IBOutlet weak var tileColorButton: UIButton! @IBOutlet weak var groupNameLabel: UILabel! @IBOutlet weak var locationNameLabel: UILabel! private var viewHasInitialized: Bool = false @objc func configureView() { if let detail = self.detailItem, viewHasInitialized { title = detail.label.value ?? detail.id labelTextField.text = detail.label.value ?? detail.id powerSwitch.setOn(detail.powerState, animated: false) if let color = detail.color.value { hueSlider.value = Float(color.hue) / Float(UInt16.max) saturationSlider.value = Float(color.saturation) / Float(UInt16.max) brightnessSlider.value = Float(color.brightness) / Float(UInt16.max) background.backgroundColor = UIColor(cgColor: color.toCGColor()) } if (detail.supportsTile) { tileColorButton.isHidden = false } else { tileColorButton.isHidden = true } if let groupService: LightsGroupLocationService = detail.lightSource.extensionOf(){ locationNameLabel.text = groupService.locationOf(light: detail)?.label groupNameLabel.text = groupService.groupOf(light: detail)?.label }else{ locationNameLabel.text = "???" groupNameLabel.text = "???" } } } override func viewDidLoad() { super.viewDidLoad() viewHasInitialized = true self.configureView() } var detailItem: Light? { willSet { if let _ = detailItem { NotificationCenter.default.removeObserver(self) } } didSet { if let light = detailItem { NotificationCenter.default.addObserver(self, selector: #selector(configureView), name: LightsChangeNotificationDispatcher.LightChangedNotification, object: light) } self.configureView() } } func hsbkChanged() { if let light = detailItem { let _ = LightSetColorCommand.create(light: light, color: HSBK(hue: UInt16(hueSlider.value * Float(UInt16.max)), saturation: UInt16(saturationSlider.value * Float(UInt16.max)), brightness: UInt16(brightnessSlider.value * Float(UInt16.max)), kelvin: 0), duration: 0).fireAndForget() } } @IBAction func hueChanged(_ sender: Any) { hsbkChanged() } @IBAction func saturationChanged(_ sender: Any) { hsbkChanged() } @IBAction func brightnessChanged(_ sender: Any) { hsbkChanged() } @IBAction func powerStateChanged(_ sender: Any) { if let light = detailItem { LightSetPowerCommand.create(light: light, status: powerSwitch.isOn, duration: 0).fireAndForget() } } @IBAction func blinkRed(_ sender: Any) { if let light = detailItem { LightSetWaveformCommand.create(light: light, transient: true, color: HSBK(hue: UInt16(0 * Float(UInt16.max)), saturation: UInt16(1 * Float(UInt16.max)), brightness: UInt16(1 * Float(UInt16.max)), kelvin: 0), period: 1000, cycles: 1, skew_ratio: Int16(0.5 * Double(Int16.max)), waveform: WaveformType.SINE).fireAndForget() } } @IBAction func blinkBrightness(_ sender: Any) { if let light = detailItem { LightSetWaveformOptionalCommand.create(light: light, transient: true, color: HSBK(hue: UInt16(1 * Float(UInt16.max)), saturation: UInt16(0.23 * Float(UInt16.max)), brightness: UInt16(1 * Float(UInt16.max)), kelvin: 0), period: 1000, cycles: 1, skew_ratio: Int16(0.5 * Double(Int16.max)), waveform: WaveformType.SAW, set_hue: false, set_saturation: false, set_brightness: true, set_kelvin: false).fireAndForget() } } @IBAction func colorTile(_ sender: Any) { if let light = detailItem, let tileService:LightTileService = light.lightSource.extensionOf(), let tile = tileService.tileOf(light: light) { let colors = stride(from: 0, to: 64, by: 1).map{ it in HSBK(hue: UInt16(it * Int(UInt16.max) / 64), saturation: UInt16.max, brightness: UInt16.max / 2, kelvin: 0) } TileSetTileState64Command.create( tileService: tileService, light: tile.light, startIndex: 0, duration: 1, colors: colors ).fireAndForget() } } }
mit
fd84c49d8f6dacdf5345ae79a9e1096d
38.143791
423
0.651027
4.482784
false
false
false
false
abraaoan/utils
utils/UtilsExample/UtilsExample/ViewController.swift
1
2756
// // ViewController.swift // UtilsExample // // Created by Abraao Nascimento on 13/06/16. // Copyright © 2016 Abraao Nascimento. All rights reserved. // import UIKit import Utils class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //Delay Example: Util.delay(0.5) { //Do something } //ImageColorOverlay let image = UIImage(named: "backWhite") let backBlack = Util.imageColorOverlay(image!, color: .blackColor()) //imageFromView let printScreen = Util.imageFromView(self.view) let backButton = UIButton(frame: CGRectMake(15,15, 44, 44)) backButton.setImage(backBlack, forState: .Normal) self.view.addSubview(backButton) let modalView = UIImageView(frame: CGRectMake(0, 0, 0, 0)) modalView.image = printScreen self.view.addSubview(modalView) //DonwloadImage Util.downloadImage("image_url") { (sucess, image, error) in if sucess { }else{ print(error?.description) } } //Simple request Util.request("url_request") { (data) in //String response print(String(data: data, encoding: NSUTF8StringEncoding)) //Json response do{ let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) print(json) }catch let error as NSError{ print(error.description) } } //Send a post Util.sendPost("url_post", dados: ["paramName":"paramValue"]) { (result) in //String response print(String(data: result!, encoding: NSUTF8StringEncoding)) //Json response do{ let json = try NSJSONSerialization.JSONObjectWithData(result!, options: []) print(json) }catch let error as NSError{ print(error.description) } } let title = UITextField(frame: CGRectMake(100, 100, 200, 20)) title.backgroundColor = .clearColor() title.text = "TESTE" self.view.addSubview(title) //Change border animated Util.changeBorderAnimate(title, color: .redColor()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
711752b11541936aec9683bb46fd9dbe
26.55
91
0.521234
5.188324
false
false
false
false
jeevanRao7/Swift_Playgrounds
Swift Playgrounds/Algorithms/Sorting/Insertion Sort.playground/Contents.swift
1
1155
/************************ Insertion Sort : The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. ************************/ import Foundation //Unsorted Array input var arr = [5, 8, 1, 9, 10, 2, 6]; let n = arr.count var key:Int; for i in 0..<n { key = arr[i] //Iterate backwards through he stored position for j in (0..<i).reversed() { //Compare all other items for smaller than key if key < arr[j] { //remove item from from original position arr.remove(at: j+1) //insert the number at key position arr.insert(key, at: j) } } } /* //Alternative way: for index in 1..<arr.count { var currentIndex = index while currentIndex > 0 && arr[currentIndex] < arr[currentIndex - 1] { arr.swapAt(currentIndex - 1, currentIndex) currentIndex -= 1 } } */ //Sorted Array - Ascending order. print(arr)
mit
bb235751852cabeb52d301b34df24050
19.625
107
0.519481
4.325843
false
false
false
false
Conaaando/swift-hacker-rank
01.Implementation/08-chocolate-feast.swift
1
1839
#!/usr/bin/swift /* https://github.com/singledev/swift-hacker-rank 08-chocolate-feast.swift https://www.hackerrank.com/challenges/chocolate-feast Created by Fernando Fernandes on 06/02/16. Copyright © 2016 SINGLEDEV. All rights reserved. http://stackoverflow.com/users/584548/singledev Instructions: $ chmod a+x 08-chocolate-feast.swift $ ./08-chocolate-feast.swift */ import Foundation // MARK: - Properties var moneyPriceWrappers: [Int] = [Int]() var results: [Int] = [Int]() // MARK: - Logic func chocolateFeast() { let moneyInPocket = moneyPriceWrappers[0] // "n" let chocolatePrice = moneyPriceWrappers[1] // "c" let wrappersPromotion = moneyPriceWrappers[2] // "m" var chocolates = moneyInPocket / chocolatePrice var wrappers = chocolates while wrappers >= wrappersPromotion { let moreChocolate = wrappers / wrappersPromotion chocolates += moreChocolate // Wrappers are the result of "more chocolate" we got // in exchange + the remainder of the exchange itself. // // Example: Had 144 wrappers, exchanged for 28 chocolates. // 144 / 5 (wrapper promotion) = 28. 4 wrappers left. // 28 + 4 = 32 (wrappers that I now hold). wrappers = moreChocolate + (wrappers % wrappersPromotion) } results.append(chocolates) } // MARK: - Input print("Type the number of test cases, then press ENTER") let testCases = Int(readLine()!)! for _ in 1...testCases { print("Type 3 integers (N, C and M) separated by space, then press ENTER") let input: [String] = readLine()!.characters.split(" ").map(String.init) moneyPriceWrappers = input.map{ Int($0)! } chocolateFeast() } // MARK: - Output for result in results { print(result) }
mit
27018fdc663733f70f8ed7a7feb838fa
24.191781
78
0.646899
3.821206
false
false
false
false
SoneeJohn/WWDC
WWDC/TabItemView.swift
1
3942
// // TabItemView.swift // WWDC // // Created by Guilherme Rambo on 22/04/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa extension NSStackView { var computedContentSize: CGSize { switch orientation { case .horizontal: let height = arrangedSubviews.map({ $0.bounds.height }).max() ?? CGFloat(0) let width = arrangedSubviews.reduce(CGFloat(0), { $0 + $1.intrinsicContentSize.width + spacing }) return CGSize(width: width - spacing, height: height) case .vertical: let width = arrangedSubviews.map({ $0.bounds.width }).max() ?? CGFloat(0) let height = arrangedSubviews.reduce(CGFloat(0), { $0 + $1.intrinsicContentSize.height + spacing }) return CGSize(width: width, height: height - spacing) } } } final class TabItemView: NSView { @objc var target: Any? @objc var action: Selector? var controllerIdentifier: String = "" var title: String? { didSet { titleLabel.stringValue = title ?? "" titleLabel.sizeToFit() sizeToFit() } } var image: NSImage? { didSet { if state == .off { imageView.image = image sizeToFit() } } } var alternateImage: NSImage? { didSet { if state == .on { imageView.image = alternateImage sizeToFit() } } } var state: NSControl.StateValue = .off { didSet { if state == .on { imageView.tintColor = .toolbarTintActive imageView.image = alternateImage ?? image titleLabel.textColor = .toolbarTintActive titleLabel.font = .systemFont(ofSize: 14, weight: NSFont.Weight.medium) } else { imageView.tintColor = .toolbarTint imageView.image = image titleLabel.textColor = .toolbarTint titleLabel.font = .systemFont(ofSize: 14) } } } lazy var imageView: MaskImageView = { let v = MaskImageView() v.tintColor = .toolbarTint v.widthAnchor.constraint(equalToConstant: 20).isActive = true v.heightAnchor.constraint(equalToConstant: 15).isActive = true return v }() lazy var titleLabel: NSTextField = { let l = NSTextField(labelWithString: "") l.font = .systemFont(ofSize: 14) l.textColor = .toolbarTint l.cell?.backgroundStyle = .dark return l }() lazy var stackView: NSStackView = { let v = NSStackView(views: [self.imageView, self.titleLabel]) v.orientation = .horizontal v.spacing = 10 v.alignment = .centerY v.distribution = .equalCentering return v }() override var intrinsicContentSize: NSSize { get { var s = stackView.computedContentSize s.width += 29 return s } set { } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true addSubview(stackView) stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: stackView.centerYAnchor, constant: -1).isActive = true } required init?(coder: NSCoder) { fatalError() } func sizeToFit() { frame = NSRect(x: frame.origin.x, y: frame.origin.y, width: intrinsicContentSize.width, height: intrinsicContentSize.height) } override func mouseDown(with event: NSEvent) { if let target = target, let action = action { NSApp.sendAction(action, to: target, from: self) } } }
bsd-2-clause
22ded78d6de35d7ae6c59f29154f3d66
25.809524
132
0.572444
4.788578
false
false
false
false
dkarsh/SwiftGoal
Carthage/Checkouts/Argo/ArgoTests/Tests/SwiftDictionaryDecodingTests.swift
3
1758
import XCTest import Argo class SwiftDictionaryDecodingTests: XCTestCase { func testDecodingAllTypesFromSwiftDictionary() { let typesDict = [ "numerics": [ "int": 5, "int64": 900719,//9254740992, Dictionaries can't handle 64bit ints (iOS only, Mac works) "int64_string": "1076543210012345678", "double": 3.4, "float": 1.1, "int_opt": 4, "uint": 500, "uint64": 1039288, "uint64_string": "18446744073709551614" ], "bool": false, "string_array": ["hello", "world"], "embedded": [ "string_array": ["hello", "world"], "string_array_opt": [] ], "user_opt": [ "id": 6, "name": "Cooler User" ], "dict": [ "foo": "bar" ] ] let model: TestModel? = decode(typesDict) XCTAssert(model != nil) XCTAssert(model?.numerics.int == 5) XCTAssert(model?.numerics.int64 == 900719)//9254740992) XCTAssert(model?.numerics.uint == 500) XCTAssert(model?.numerics.uint64 == 1039288) XCTAssert(model?.numerics.uint64String == 18446744073709551614) XCTAssert(model?.numerics.double == 3.4) XCTAssert(model?.numerics.float == 1.1) XCTAssert(model?.numerics.intOpt != nil) XCTAssert(model?.numerics.intOpt! == 4) XCTAssert(model?.string == "Cooler User") XCTAssert(model?.bool == false) XCTAssert(model?.stringArray.count == 2) XCTAssert(model?.stringArrayOpt == nil) XCTAssert(model?.eStringArray.count == 2) XCTAssert(model?.eStringArrayOpt != nil) XCTAssert(model?.eStringArrayOpt?.count == 0) XCTAssert(model?.userOpt != nil) XCTAssert(model?.userOpt?.id == 6) XCTAssert(model?.dict ?? [:] == ["foo": "bar"]) } }
mit
d316f38e3c8921dcd6aa6d154cf1b048
30.392857
96
0.597838
3.602459
false
true
false
false
humeng12/DouYuZB
DouYuZB/DouYuZB/Classes/Home/View/AmuseMenuViewCell.swift
1
1694
// // AmuseMenuViewCell.swift // DouYuZB // // Created by 胡猛 on 2016/12/3. // Copyright © 2016年 HuMeng. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" class AmuseMenuViewCell: UICollectionViewCell { var groups : [AnchorGroup]? { didSet { collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let itemW = collectionView.bounds.width / 4 let itemH = collectionView.bounds.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) } } extension AmuseMenuViewCell : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.clipsToBounds = true cell.gameModel = groups![indexPath.item] return cell } }
mit
128279063600699405213a48db3fe9be
24.560606
126
0.653823
5.64214
false
false
false
false
amujic5/AFEA
AFEA-StarterProject/AFEA-StarterProject/Views/CircleView.swift
1
1512
import UIKit class CircleView: UIView { private var foregroundCircle: CAShapeLayer! private var backgroundCircle: CAShapeLayer! required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, lineWidth: CGFloat = 6, backgroundColor: UIColor = .coolGrey, frontgroundColor: UIColor) { super.init(frame: frame) backgroundCircle = CAShapeLayer.circle(frame: bounds, strokeColor: backgroundColor, lineWidth: lineWidth) backgroundCircle.strokeEnd = 1 foregroundCircle = CAShapeLayer.circle(frame: bounds, strokeColor: frontgroundColor, lineWidth: lineWidth) foregroundCircle.strokeEnd = 0.0 self.backgroundColor = UIColor.clear layer.addSublayer(backgroundCircle) layer.addSublayer(foregroundCircle) } func animateFill(over duration: TimeInterval, to percentage: Double) { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = duration // Animate from 0 (no circle) to percentage animation.fromValue = 0 animation.toValue = percentage // Set the circleLayer's strokeEnd property to 1.0 now so that it's the // right value when the animation ends. foregroundCircle.strokeEnd = CGFloat(percentage) foregroundCircle.add(animation, forKey: "animateCircle") } }
mit
3e388390f6d36ac057e0db0519b2acf9
35.878049
114
0.707672
5.213793
false
false
false
false
ahoppen/swift
test/Generics/associated_type_where_clause.swift
6
5995
// RUN: %target-typecheck-verify-swift -swift-version 4 -warn-redundant-requirements func needsSameType<T>(_: T.Type, _: T.Type) {} protocol Foo {} func needsFoo<T: Foo>(_: T.Type) {} protocol Foo2 {} func needsFoo2<T: Foo2>(_: T.Type) {} extension Int: Foo, Foo2 {} extension Float: Foo {} protocol Conforms { associatedtype T where T: Foo } func needsConforms<X: Conforms>(_: X.Type) { needsFoo(X.T.self) } struct ConcreteConforms: Conforms { typealias T = Int } struct ConcreteConforms2: Conforms { typealias T = Int } struct ConcreteConformsNonFoo2: Conforms { typealias T = Float } protocol NestedConforms { associatedtype U where U: Conforms, U.T: Foo2 // expected-note{{protocol requires nested type 'U'; do you want to add it?}} func foo(_: U) } extension NestedConforms { func foo(_: U) {} } func needsNestedConforms<X: NestedConforms>(_: X.Type) { needsConforms(X.U.self) needsFoo(X.U.T.self) needsFoo2(X.U.T.self) } struct ConcreteNestedConforms: NestedConforms { typealias U = ConcreteConforms } struct ConcreteNestedConformsInfer: NestedConforms { func foo(_: ConcreteConforms) {} } struct BadConcreteNestedConforms: NestedConforms { // expected-error@-1 {{type 'BadConcreteNestedConforms' does not conform to protocol 'NestedConforms'}} // expected-error@-2 {{type 'ConcreteConformsNonFoo2.T' (aka 'Float') does not conform to protocol 'Foo2'}} typealias U = ConcreteConformsNonFoo2 } struct BadConcreteNestedConformsInfer: NestedConforms { // expected-error@-1 {{type 'BadConcreteNestedConformsInfer' does not conform to protocol 'NestedConforms'}} func foo(_: ConcreteConformsNonFoo2) {} } protocol NestedConformsDefault { associatedtype U = ConcreteConforms where U: Conforms, U.T: Foo2 } struct ConcreteNestedConformsDefaultDefaulted: NestedConformsDefault {} struct ConcreteNestedConformsDefault: NestedConformsDefault { typealias U = ConcreteConforms2 } func needsNestedConformsDefault<X: NestedConformsDefault>(_: X.Type) { needsConforms(X.U.self) needsFoo(X.U.T.self) needsFoo2(X.U.T.self) } protocol NestedSameType { associatedtype U: Conforms where U.T == Int // expected-note{{protocol requires nested type 'U'; do you want to add it?}} func foo(_: U) } extension NestedSameType { func foo(_: U) {} } func needsNestedSameType<X: NestedSameType>(_: X.Type) { needsConforms(X.U.self) needsSameType(X.U.T.self, Int.self) } struct BadConcreteNestedSameType: NestedSameType { // expected-error@-1 {{type 'BadConcreteNestedSameType' does not conform to protocol 'NestedSameType'}} // expected-error@-2 {{'NestedSameType' requires the types 'ConcreteConformsNonFoo2.T' (aka 'Float') and 'Int' be equivalent}} // expected-note@-3 {{requirement specified as 'Self.U.T' == 'Int' [with Self = BadConcreteNestedSameType]}} typealias U = ConcreteConformsNonFoo2 } struct BadConcreteNestedSameTypeInfer: NestedSameType { // expected-error@-1 {{type 'BadConcreteNestedSameTypeInfer' does not conform to protocol 'NestedSameType'}} func foo(_: ConcreteConformsNonFoo2) {} } protocol NestedSameTypeDefault { associatedtype U: Conforms = ConcreteConforms where U.T == Int func foo(_: U) } extension NestedSameTypeDefault { func foo(_: U) {} } func needsNestedSameTypeDefault<X: NestedSameTypeDefault>(_: X.Type) { needsConforms(X.U.self) needsSameType(X.U.T.self, Int.self) } struct ConcreteNestedSameTypeDefaultDefaulted: NestedSameTypeDefault {} struct ConcreteNestedSameTypeDefault: NestedSameTypeDefault { typealias U = ConcreteConforms2 } struct ConcreteNestedSameTypeDefaultInfer: NestedSameTypeDefault { func foo(_: ConcreteConforms2) {} } protocol Inherits: NestedConforms { associatedtype X: Conforms where X.T == U.T func bar(_: X) } extension Inherits { func bar(_: X) {} } func needsInherits<X: Inherits>(_: X.Type) { needsConforms(X.U.self) needsConforms(X.X.self) needsSameType(X.U.T.self, X.X.T.self) } struct ConcreteInherits: Inherits { typealias U = ConcreteConforms typealias X = ConcreteConforms } struct ConcreteInheritsDiffer: Inherits { typealias U = ConcreteConforms typealias X = ConcreteConforms2 } /* FIXME: the sametype requirement gets dropped from the requirement signature (enumerateRequirements doesn't yield it), so this doesn't error as it should. struct BadConcreteInherits: Inherits { typealias U = ConcreteConforms typealias X = ConcreteConformsNonFoo2 } */ struct X { } protocol P { associatedtype P1 where P1 == X associatedtype P2 where P2 == P1, P2 == X // expected-warning@-1{{redundant same-type constraint 'Self.P2' == 'X'}} } // Lookup of same-named associated types aren't ambiguous in this context. protocol P1 { associatedtype A } protocol P2: P1 { associatedtype A associatedtype B where A == B } protocol P3: P1 { associatedtype A } protocol P4 { associatedtype A } protocol P5: P3, P4 { associatedtype B where B == A? } // Associated type inference should account for where clauses. protocol P6 { associatedtype A } struct X1 { } struct X2 { } struct Y1 : P6 { typealias A = X1 } struct Y2 : P6 { typealias A = X2 } protocol P7 { associatedtype B: P6 // expected-note{{ambiguous inference of associated type 'B': 'Y1' vs. 'Y2'}} associatedtype C: P6 where B.A == C.A func getB() -> B func getC() -> C } struct Z1 : P7 { func getB() -> Y1 { return Y1() } func getB() -> Y2 { return Y2() } func getC() -> Y1 { return Y1() } } func testZ1(z1: Z1) { let _: Z1.C = Y1() } struct Z2 : P7 { // expected-error{{type 'Z2' does not conform to protocol 'P7'}} func getB() -> Y1 { return Y1() } // expected-note{{matching requirement 'getB()' to this declaration inferred associated type to 'Y1'}} func getB() -> Y2 { return Y2() } // expected-note{{matching requirement 'getB()' to this declaration inferred associated type to 'Y2'}} func getC() -> Y1 { return Y1() } func getC() -> Y2 { return Y2() } }
apache-2.0
c7a558e1584a7668d6bfa8574b53fb49
28.243902
138
0.714595
3.570578
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/Operation.swift
1
50021
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import Dispatch internal let _NSOperationIsFinished = "isFinished" internal let _NSOperationIsFinishedAlternate = "finished" internal let _NSOperationIsExecuting = "isExecuting" internal let _NSOperationIsExecutingAlternate = "executing" internal let _NSOperationIsReady = "isReady" internal let _NSOperationIsReadyAlternate = "ready" internal let _NSOperationIsCancelled = "isCancelled" internal let _NSOperationIsCancelledAlternate = "cancelled" internal let _NSOperationIsAsynchronous = "isAsynchronous" internal let _NSOperationQueuePriority = "queuePriority" internal let _NSOperationThreadPriority = "threadPriority" internal let _NSOperationCompletionBlock = "completionBlock" internal let _NSOperationName = "name" internal let _NSOperationDependencies = "dependencies" internal let _NSOperationQualityOfService = "qualityOfService" internal let _NSOperationQueueOperationsKeyPath = "operations" internal let _NSOperationQueueOperationCountKeyPath = "operationCount" internal let _NSOperationQueueSuspendedKeyPath = "suspended" extension QualityOfService { #if canImport(Darwin) internal init(_ qos: qos_class_t) { switch qos { case QOS_CLASS_DEFAULT: self = .default case QOS_CLASS_USER_INTERACTIVE: self = .userInteractive case QOS_CLASS_USER_INITIATED: self = .userInitiated case QOS_CLASS_UTILITY: self = .utility case QOS_CLASS_BACKGROUND: self = .background default: fatalError("Unsupported qos") } } #endif internal var qosClass: DispatchQoS { switch self { case .userInteractive: return .userInteractive case .userInitiated: return .userInitiated case .utility: return .utility case .background: return .background case .default: return .default } } } open class Operation : NSObject { struct PointerHashedUnmanagedBox<T: AnyObject>: Hashable { var contents: Unmanaged<T> func hash(into hasher: inout Hasher) { hasher.combine(contents.toOpaque()) } static func == (_ lhs: PointerHashedUnmanagedBox, _ rhs: PointerHashedUnmanagedBox) -> Bool { return lhs.contents.toOpaque() == rhs.contents.toOpaque() } } enum __NSOperationState : UInt8 { case initialized = 0x00 case enqueuing = 0x48 case enqueued = 0x50 case dispatching = 0x88 case starting = 0xD8 case executing = 0xE0 case finishing = 0xF0 case finished = 0xF4 } internal var __previousOperation: Unmanaged<Operation>? internal var __nextOperation: Unmanaged<Operation>? internal var __nextPriorityOperation: Unmanaged<Operation>? internal var __queue: Unmanaged<OperationQueue>? internal var __dependencies = [Operation]() internal var __downDependencies = Set<PointerHashedUnmanagedBox<Operation>>() internal var __unfinishedDependencyCount: Int = 0 internal var __completion: (() -> Void)? internal var __name: String? internal var __schedule: DispatchWorkItem? internal var __state: __NSOperationState = .initialized internal var __priorityValue: Operation.QueuePriority.RawValue? internal var __cachedIsReady: Bool = true internal var __isCancelled: Bool = false internal var __propertyQoS: QualityOfService? var __waitCondition = NSCondition() var __lock = NSLock() var __atomicLoad = NSLock() internal var _state: __NSOperationState { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __state } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __state = newValue } } internal func _compareAndSwapState(_ old: __NSOperationState, _ new: __NSOperationState) -> Bool { __atomicLoad.lock() defer { __atomicLoad.unlock() } if __state != old { return false } __state = new return true } internal func _lock() { __lock.lock() } internal func _unlock() { __lock.unlock() } internal var _queue: OperationQueue? { _lock() defer { _unlock() } return __queue?.takeRetainedValue() } internal func _adopt(queue: OperationQueue, schedule: DispatchWorkItem) { _lock() defer { _unlock() } __queue = Unmanaged.passRetained(queue) __schedule = schedule } internal var _isCancelled: Bool { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __isCancelled } internal var _unfinishedDependencyCount: Int { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __unfinishedDependencyCount } } internal func _incrementUnfinishedDependencyCount(by amount: Int = 1) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __unfinishedDependencyCount += amount } internal func _decrementUnfinishedDependencyCount(by amount: Int = 1) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __unfinishedDependencyCount -= amount } internal func _addParent(_ parent: Operation) { __downDependencies.insert(PointerHashedUnmanagedBox(contents: .passUnretained(parent))) } internal func _removeParent(_ parent: Operation) { __downDependencies.remove(PointerHashedUnmanagedBox(contents: .passUnretained(parent))) } internal var _cachedIsReady: Bool { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __cachedIsReady } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __cachedIsReady = newValue } } internal func _fetchCachedIsReady(_ retest: inout Bool) -> Bool { let setting = _cachedIsReady if !setting { _lock() retest = __unfinishedDependencyCount == 0 _unlock() } return setting } internal func _invalidateQueue() { _lock() __schedule = nil let queue = __queue __queue = nil _unlock() queue?.release() } internal func _removeAllDependencies() { _lock() let deps = __dependencies __dependencies.removeAll() _unlock() for dep in deps { dep._lock() _lock() let upIsFinished = dep._state == .finished if !upIsFinished && !_isCancelled { _decrementUnfinishedDependencyCount() } dep._removeParent(self) _unlock() dep._unlock() } } internal static func observeValue(forKeyPath keyPath: String, ofObject op: Operation) { enum Transition { case toFinished case toExecuting case toReady } let kind: Transition? if keyPath == _NSOperationIsFinished || keyPath == _NSOperationIsFinishedAlternate { kind = .toFinished } else if keyPath == _NSOperationIsExecuting || keyPath == _NSOperationIsReadyAlternate { kind = .toExecuting } else if keyPath == _NSOperationIsReady || keyPath == _NSOperationIsReadyAlternate { kind = .toReady } else { kind = nil } if let transition = kind { switch transition { case .toFinished: // we only care about NO -> YES if !op.isFinished { return } var ready_deps = [Operation]() op._lock() let state = op._state if op.__queue != nil && state.rawValue < __NSOperationState.starting.rawValue { print("*** \(type(of: op)) \(Unmanaged.passUnretained(op).toOpaque()) went isFinished=YES without being started by the queue it is in") } if state.rawValue < __NSOperationState.finishing.rawValue { op._state = .finishing } else if state == .finished { op._unlock() return } let down_deps = op.__downDependencies op.__downDependencies.removeAll() if 0 < down_deps.count { for down in down_deps { let idown = down.contents.takeUnretainedValue() idown._lock() if idown._unfinishedDependencyCount == 1 { ready_deps.append(idown) } else if idown._unfinishedDependencyCount > 1 { idown._decrementUnfinishedDependencyCount() } else { assert(idown._unfinishedDependencyCount == 0) assert(idown._isCancelled == true) } idown._unlock() } } op._state = .finished let oq = op.__queue op.__queue = nil op._unlock() if 0 < ready_deps.count { for down in ready_deps { down._lock() if down._unfinishedDependencyCount >= 1 { down._decrementUnfinishedDependencyCount() } down._unlock() Operation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: down) } } op.__waitCondition.lock() op.__waitCondition.broadcast() op.__waitCondition.unlock() if let complete = op.__completion { let held = Unmanaged.passRetained(op) DispatchQueue.global(qos: .default).async { complete() held.release() } } if let queue = oq { queue.takeUnretainedValue()._operationFinished(op, state) queue.release() } case .toExecuting: let isExecuting = op.isExecuting op._lock() if op._state.rawValue < __NSOperationState.executing.rawValue && isExecuting { op._state = .executing } op._unlock() case .toReady: let r = op.isReady op._cachedIsReady = r let q = op._queue if r { q?._schedule() } } } } public override init() { } open func start() { let state = _state if __NSOperationState.finished == state { return } if !_compareAndSwapState(__NSOperationState.initialized, __NSOperationState.starting) && !(__NSOperationState.starting == state && __queue != nil) { switch state { case .executing: fallthrough case .finishing: fatalError("\(self): receiver is already executing") default: fatalError("\(self): something is trying to start the receiver simultaneously from more than one thread") } } if state.rawValue < __NSOperationState.enqueued.rawValue && !isReady { _state = state fatalError("\(self): receiver is not yet ready to execute") } let isCanc = _isCancelled if !isCanc { _state = .executing Operation.observeValue(forKeyPath: _NSOperationIsExecuting, ofObject: self) _queue?._execute(self) } if __NSOperationState.executing == _state { _state = .finishing Operation.observeValue(forKeyPath: _NSOperationIsExecuting, ofObject: self) Operation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: self) } else { _state = .finishing Operation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: self) } } open func main() { } open var isCancelled: Bool { return _isCancelled } open func cancel() { if isFinished { return } __atomicLoad.lock() __isCancelled = true __atomicLoad.unlock() if __NSOperationState.executing.rawValue <= _state.rawValue { return } _lock() __unfinishedDependencyCount = 0 _unlock() Operation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self) } open var isExecuting: Bool { return __NSOperationState.executing == _state } open var isFinished: Bool { return __NSOperationState.finishing.rawValue <= _state.rawValue } open var isAsynchronous: Bool { return false } open var isReady: Bool { _lock() defer { _unlock() } return __unfinishedDependencyCount == 0 } internal func _addDependency(_ op: Operation) { withExtendedLifetime(self) { withExtendedLifetime(op) { var up: Operation? _lock() if __dependencies.first(where: { $0 === op }) != nil { __dependencies.append(op) up = op } _unlock() if let upwards = up { upwards._lock() _lock() let upIsFinished = upwards._state == __NSOperationState.finished if !upIsFinished && !_isCancelled { assert(_unfinishedDependencyCount >= 0) _incrementUnfinishedDependencyCount() upwards._addParent(self) } _unlock() upwards._unlock() } Operation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self) } } } open func addDependency(_ op: Operation) { _addDependency(op) } open func removeDependency(_ op: Operation) { withExtendedLifetime(self) { withExtendedLifetime(op) { var up_canidate: Operation? _lock() let idxCanidate = __dependencies.firstIndex { $0 === op } if idxCanidate != nil { up_canidate = op } _unlock() if let canidate = up_canidate { canidate._lock() _lock() if let idx = __dependencies.firstIndex(where: { $0 === op }) { if canidate._state == .finished && _isCancelled { _decrementUnfinishedDependencyCount() } canidate._removeParent(self) __dependencies.remove(at: idx) } _unlock() canidate._unlock() } Operation.observeValue(forKeyPath: _NSOperationIsReady, ofObject: self) } } } open var dependencies: [Operation] { get { _lock() defer { _unlock() } return __dependencies.filter { !($0 is _BarrierOperation) } } } internal func changePriority(_ newPri: Operation.QueuePriority.RawValue) { _lock() guard let oq = __queue?.takeRetainedValue() else { __priorityValue = newPri _unlock() return } _unlock() oq._lock() var oldPri = __priorityValue if oldPri == nil { if let v = (0 == oq.__actualMaxNumOps) ? nil : __propertyQoS { switch v { case .default: oldPri = Operation.QueuePriority.normal.rawValue case .userInteractive: oldPri = Operation.QueuePriority.veryHigh.rawValue case .userInitiated: oldPri = Operation.QueuePriority.high.rawValue case .utility: oldPri = Operation.QueuePriority.low.rawValue case .background: oldPri = Operation.QueuePriority.veryLow.rawValue } } else { oldPri = Operation.QueuePriority.normal.rawValue } } if oldPri == newPri { oq._unlock() return } __priorityValue = newPri var op = oq._firstPriorityOperation(oldPri) var prev: Unmanaged<Operation>? while let operation = op?.takeUnretainedValue() { let nextOp = operation.__nextPriorityOperation if operation === self { // Remove from old list if let previous = prev?.takeUnretainedValue() { previous.__nextPriorityOperation = nextOp } else { oq._setFirstPriorityOperation(oldPri!, nextOp) } if nextOp == nil { oq._setlastPriorityOperation(oldPri!, prev) } __nextPriorityOperation = nil // Append to new list if let oldLast = oq._lastPriorityOperation(newPri)?.takeUnretainedValue() { oldLast.__nextPriorityOperation = Unmanaged.passUnretained(self) } else { oq._setFirstPriorityOperation(newPri, Unmanaged.passUnretained(self)) } oq._setlastPriorityOperation(newPri, Unmanaged.passUnretained(self)) break } prev = op op = nextOp } oq._unlock() } open var queuePriority: Operation.QueuePriority { get { guard let prioValue = __priorityValue else { return Operation.QueuePriority.normal } return Operation.QueuePriority(rawValue: prioValue) ?? .veryHigh } set(newValue) { let newPri: Operation.QueuePriority.RawValue if Operation.QueuePriority.veryHigh.rawValue <= newValue.rawValue { newPri = Operation.QueuePriority.veryHigh.rawValue } else if Operation.QueuePriority.high.rawValue <= newValue.rawValue { newPri = Operation.QueuePriority.high.rawValue } else if Operation.QueuePriority.normal.rawValue <= newValue.rawValue { newPri = Operation.QueuePriority.normal.rawValue } else if Operation.QueuePriority.low.rawValue < newValue.rawValue { newPri = Operation.QueuePriority.normal.rawValue } else if Operation.QueuePriority.veryLow.rawValue < newValue.rawValue { newPri = Operation.QueuePriority.low.rawValue } else { newPri = Operation.QueuePriority.veryLow.rawValue } if __priorityValue != newPri { changePriority(newPri) } } } open var completionBlock: (() -> Void)? { get { _lock() defer { _unlock() } return __completion } set(newValue) { _lock() defer { _unlock() } __completion = newValue } } open func waitUntilFinished() { __waitCondition.lock() while !isFinished { __waitCondition.wait() } __waitCondition.unlock() } open var qualityOfService: QualityOfService { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __propertyQoS ?? QualityOfService.default } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __propertyQoS = newValue } } open var name: String? { get { return __name } set(newValue) { __name = newValue } } } extension Operation { public func willChangeValue(forKey key: String) { // do nothing } public func didChangeValue(forKey key: String) { Operation.observeValue(forKeyPath: key, ofObject: self) } public func willChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) { // do nothing } public func didChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) { switch keyPath { case \Operation.isFinished: didChangeValue(forKey: _NSOperationIsFinished) case \Operation.isReady: didChangeValue(forKey: _NSOperationIsReady) case \Operation.isCancelled: didChangeValue(forKey: _NSOperationIsCancelled) case \Operation.isExecuting: didChangeValue(forKey: _NSOperationIsExecuting) default: break } } } extension Operation { public enum QueuePriority : Int { case veryLow = -8 case low = -4 case normal = 0 case high = 4 case veryHigh = 8 internal static var barrier = 12 internal static let priorities = [ Operation.QueuePriority.barrier, Operation.QueuePriority.veryHigh.rawValue, Operation.QueuePriority.high.rawValue, Operation.QueuePriority.normal.rawValue, Operation.QueuePriority.low.rawValue, Operation.QueuePriority.veryLow.rawValue ] } } open class BlockOperation : Operation { var _block: (() -> Void)? var _executionBlocks: [() -> Void]? public override init() { } public convenience init(block: @escaping () -> Void) { self.init() _block = block } open func addExecutionBlock(_ block: @escaping () -> Void) { if isExecuting || isFinished { fatalError("blocks cannot be added after the operation has started executing or finished") } _lock() defer { _unlock() } if _block == nil && _executionBlocks == nil { _block = block } else { if _executionBlocks == nil { if let existing = _block { _executionBlocks = [existing, block] } else { _executionBlocks = [block] } } else { _executionBlocks?.append(block) } } } open var executionBlocks: [@convention(block) () -> Void] { get { _lock() defer { _unlock() } var blocks = [() -> Void]() if let existing = _block { blocks.append(existing) } if let existing = _executionBlocks { blocks.append(contentsOf: existing) } return blocks } } open override func main() { var blocks = [() -> Void]() _lock() if let existing = _block { blocks.append(existing) } if let existing = _executionBlocks { blocks.append(contentsOf: existing) } _unlock() for block in blocks { block() } } } internal final class _BarrierOperation : Operation { var _block: (() -> Void)? init(_ block: @escaping () -> Void) { _block = block } override func main() { _lock() let block = _block _block = nil _unlock() block?() _removeAllDependencies() } } internal final class _OperationQueueProgress : Progress { var queue: Unmanaged<OperationQueue>? let lock = NSLock() init(_ queue: OperationQueue) { self.queue = Unmanaged.passUnretained(queue) super.init(parent: nil, userInfo: nil) } func invalidateQueue() { lock.lock() queue = nil lock.unlock() } override var totalUnitCount: Int64 { get { return super.totalUnitCount } set(newValue) { super.totalUnitCount = newValue lock.lock() queue?.takeUnretainedValue().__progressReporting = true lock.unlock() } } } extension OperationQueue { public static let defaultMaxConcurrentOperationCount: Int = -1 } @available(OSX 10.5, *) open class OperationQueue : NSObject, ProgressReporting { let __queueLock = NSLock() let __atomicLoad = NSLock() var __firstOperation: Unmanaged<Operation>? var __lastOperation: Unmanaged<Operation>? var __firstPriorityOperation: (barrier: Unmanaged<Operation>?, veryHigh: Unmanaged<Operation>?, high: Unmanaged<Operation>?, normal: Unmanaged<Operation>?, low: Unmanaged<Operation>?, veryLow: Unmanaged<Operation>?) var __lastPriorityOperation: (barrier: Unmanaged<Operation>?, veryHigh: Unmanaged<Operation>?, high: Unmanaged<Operation>?, normal: Unmanaged<Operation>?, low: Unmanaged<Operation>?, veryLow: Unmanaged<Operation>?) var _barriers = [_BarrierOperation]() var _progress: _OperationQueueProgress? var __operationCount: Int = 0 var __maxNumOps: Int = OperationQueue.defaultMaxConcurrentOperationCount var __actualMaxNumOps: Int32 = .max var __numExecOps: Int32 = 0 var __dispatch_queue: DispatchQueue? var __backingQueue: DispatchQueue? var __name: String? var __suspended: Bool = false var __overcommit: Bool = false var __propertyQoS: QualityOfService? var __mainQ: Bool = false var __progressReporting: Bool = false internal func _lock() { __queueLock.lock() } internal func _unlock() { __queueLock.unlock() } internal var _suspended: Bool { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __suspended } internal func _incrementExecutingOperations() { __atomicLoad.lock() defer { __atomicLoad.unlock() } __numExecOps += 1 } internal func _decrementExecutingOperations() { __atomicLoad.lock() defer { __atomicLoad.unlock() } if __numExecOps > 0 { __numExecOps -= 1 } } internal func _incrementOperationCount(by amount: Int = 1) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __operationCount += amount } internal func _decrementOperationCount(by amount: Int = 1) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __operationCount -= amount } internal func _firstPriorityOperation(_ prio: Operation.QueuePriority.RawValue?) -> Unmanaged<Operation>? { guard let priority = prio else { return nil } switch priority { case Operation.QueuePriority.barrier: return __firstPriorityOperation.barrier case Operation.QueuePriority.veryHigh.rawValue: return __firstPriorityOperation.veryHigh case Operation.QueuePriority.high.rawValue: return __firstPriorityOperation.high case Operation.QueuePriority.normal.rawValue: return __firstPriorityOperation.normal case Operation.QueuePriority.low.rawValue: return __firstPriorityOperation.low case Operation.QueuePriority.veryLow.rawValue: return __firstPriorityOperation.veryLow default: fatalError("unsupported priority") } } internal func _setFirstPriorityOperation(_ prio: Operation.QueuePriority.RawValue, _ operation: Unmanaged<Operation>?) { switch prio { case Operation.QueuePriority.barrier: __firstPriorityOperation.barrier = operation case Operation.QueuePriority.veryHigh.rawValue: __firstPriorityOperation.veryHigh = operation case Operation.QueuePriority.high.rawValue: __firstPriorityOperation.high = operation case Operation.QueuePriority.normal.rawValue: __firstPriorityOperation.normal = operation case Operation.QueuePriority.low.rawValue: __firstPriorityOperation.low = operation case Operation.QueuePriority.veryLow.rawValue: __firstPriorityOperation.veryLow = operation default: fatalError("unsupported priority") } } internal func _lastPriorityOperation(_ prio: Operation.QueuePriority.RawValue?) -> Unmanaged<Operation>? { guard let priority = prio else { return nil } switch priority { case Operation.QueuePriority.barrier: return __lastPriorityOperation.barrier case Operation.QueuePriority.veryHigh.rawValue: return __lastPriorityOperation.veryHigh case Operation.QueuePriority.high.rawValue: return __lastPriorityOperation.high case Operation.QueuePriority.normal.rawValue: return __lastPriorityOperation.normal case Operation.QueuePriority.low.rawValue: return __lastPriorityOperation.low case Operation.QueuePriority.veryLow.rawValue: return __lastPriorityOperation.veryLow default: fatalError("unsupported priority") } } internal func _setlastPriorityOperation(_ prio: Operation.QueuePriority.RawValue, _ operation: Unmanaged<Operation>?) { if let op = operation?.takeUnretainedValue() { assert(op.queuePriority.rawValue == prio) } switch prio { case Operation.QueuePriority.barrier: __lastPriorityOperation.barrier = operation case Operation.QueuePriority.veryHigh.rawValue: __lastPriorityOperation.veryHigh = operation case Operation.QueuePriority.high.rawValue: __lastPriorityOperation.high = operation case Operation.QueuePriority.normal.rawValue: __lastPriorityOperation.normal = operation case Operation.QueuePriority.low.rawValue: __lastPriorityOperation.low = operation case Operation.QueuePriority.veryLow.rawValue: __lastPriorityOperation.veryLow = operation default: fatalError("unsupported priority") } } internal func _operationFinished(_ op: Operation, _ previousState: Operation.__NSOperationState) { // There are only three cases where an operation might have a nil queue // A) The operation was never added to a queue and we got here by a normal KVO change // B) The operation was somehow already finished // C) the operation was attempted to be added to a queue but an exception occured and was ignored... // Option C is NOT supported! let isBarrier = op is _BarrierOperation _lock() let nextOp = op.__nextOperation if Operation.__NSOperationState.finished == op._state { let prevOp = op.__previousOperation if let prev = prevOp { prev.takeUnretainedValue().__nextOperation = nextOp } else { __firstOperation = nextOp } if let next = nextOp { next.takeUnretainedValue().__previousOperation = prevOp } else { __lastOperation = prevOp } // only decrement execution count on operations that were executing! (the execution was initially set to __NSOperationStateDispatching so we must compare from that or later) // else the number of executing operations might underflow if previousState.rawValue >= Operation.__NSOperationState.dispatching.rawValue { _decrementExecutingOperations() } op.__previousOperation = nil op.__nextOperation = nil op._invalidateQueue() } if !isBarrier { _decrementOperationCount() } _unlock() _schedule() if previousState.rawValue >= Operation.__NSOperationState.enqueuing.rawValue { Unmanaged.passUnretained(op).release() } } internal var _propertyQoS: QualityOfService? { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __propertyQoS } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __propertyQoS = newValue } } internal func _synthesizeBackingQueue() -> DispatchQueue { guard let queue = __backingQueue else { let queue: DispatchQueue if let qos = _propertyQoS { if let name = __name { queue = DispatchQueue(label: name, qos: qos.qosClass) } else { queue = DispatchQueue(label: "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())", qos: qos.qosClass) } } else { if let name = __name { queue = DispatchQueue(label: name) } else { queue = DispatchQueue(label: "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())") } } __backingQueue = queue return queue } return queue } static internal var _currentQueue = NSThreadSpecific<OperationQueue>() internal func _schedule(_ op: Operation) { op._state = .starting // set current tsd OperationQueue._currentQueue.set(self) op.start() OperationQueue._currentQueue.clear() // unset current tsd if op.isFinished && op._state.rawValue < Operation.__NSOperationState.finishing.rawValue { Operation.observeValue(forKeyPath: _NSOperationIsFinished, ofObject: op) } } internal func _schedule() { var retestOps = [Operation]() _lock() var slotsAvail = __actualMaxNumOps - __numExecOps for prio in Operation.QueuePriority.priorities { if 0 >= slotsAvail || _suspended { break } var op = _firstPriorityOperation(prio) var prev: Unmanaged<Operation>? while let operation = op?.takeUnretainedValue() { if 0 >= slotsAvail || _suspended { break } let next = operation.__nextPriorityOperation var retest = false // if the cached state is possibly not valid then the isReady value needs to be re-updated if Operation.__NSOperationState.enqueued == operation._state && operation._fetchCachedIsReady(&retest) { if let previous = prev?.takeUnretainedValue() { previous.__nextOperation = next } else { _setFirstPriorityOperation(prio, next) } if next == nil { _setlastPriorityOperation(prio, prev) } operation.__nextPriorityOperation = nil operation._state = .dispatching _incrementExecutingOperations() slotsAvail -= 1 let queue: DispatchQueue if __mainQ { queue = DispatchQueue.main } else { queue = __dispatch_queue ?? _synthesizeBackingQueue() } if let schedule = operation.__schedule { if operation is _BarrierOperation { queue.async(flags: .barrier, execute: { schedule.perform() }) } else { queue.async(execute: schedule) } } op = next } else { if retest { retestOps.append(operation) } prev = op op = next } } } _unlock() for op in retestOps { if op.isReady { op._cachedIsReady = true } } } internal var _isReportingProgress: Bool { return __progressReporting } internal func _execute(_ op: Operation) { var operationProgress: Progress? = nil if !(op is _BarrierOperation) && _isReportingProgress { let opProgress = Progress(parent: nil, userInfo: nil) opProgress.totalUnitCount = 1 progress.addChild(opProgress, withPendingUnitCount: 1) operationProgress = opProgress } operationProgress?.becomeCurrent(withPendingUnitCount: 1) defer { operationProgress?.resignCurrent() } op.main() } internal var _maxNumOps: Int { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __maxNumOps } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __maxNumOps = newValue } } internal var _isSuspended: Bool { get { __atomicLoad.lock() defer { __atomicLoad.unlock() } return __suspended } set(newValue) { __atomicLoad.lock() defer { __atomicLoad.unlock() } __suspended = newValue } } internal var _operationCount: Int { _lock() defer { _unlock() } var op = __firstOperation var cnt = 0 if let operation = op?.takeUnretainedValue() { if !(operation is _BarrierOperation) { cnt += 1 } op = operation.__nextOperation } return cnt } internal func _operations(includingBarriers: Bool = false) -> [Operation] { _lock() defer { _unlock() } var operations = [Operation]() var op = __firstOperation if let operation = op?.takeUnretainedValue() { if includingBarriers || !(operation is _BarrierOperation) { operations.append(operation) } op = operation.__nextOperation } return operations } public override init() { super.init() __name = "NSOperationQueue \(Unmanaged<OperationQueue>.passUnretained(self).toOpaque())" } internal init(asMainQueue: ()) { super.init() __mainQ = true __maxNumOps = 1 __actualMaxNumOps = 1 __name = "NSOperationQueue Main Queue" #if canImport(Darwin) __propertyQoS = QualityOfService(qos_class_main()) #else __propertyQoS = QualityOfService.userInteractive #endif } open var progress: Progress { get { _lock() defer { _unlock() } guard let progress = _progress else { let progress = _OperationQueueProgress(self) _progress = progress return progress } return progress } } internal func _addOperations(_ ops: [Operation], barrier: Bool = false) { if 0 == ops.count { return } var failures = 0 var successes = 0 var firstNewOp: Unmanaged<Operation>? var lastNewOp: Unmanaged<Operation>? for op in ops { if op._compareAndSwapState(.initialized, .enqueuing) { successes += 1 if 0 == failures { let retained = Unmanaged.passRetained(op) op._cachedIsReady = op.isReady let schedule: DispatchWorkItem if let qos = op.__propertyQoS?.qosClass { schedule = DispatchWorkItem.init(qos: qos, flags: .enforceQoS, block: { self._schedule(op) }) } else { schedule = DispatchWorkItem(flags: .assignCurrentContext, block: { self._schedule(op) }) } op._adopt(queue: self, schedule: schedule) op.__previousOperation = lastNewOp op.__nextOperation = nil if let lastNewOperation = lastNewOp?.takeUnretainedValue() { lastNewOperation.__nextOperation = retained } else { firstNewOp = retained } lastNewOp = retained } else { _ = op._compareAndSwapState(.enqueuing, .initialized) } } else { failures += 1 } } if 0 < failures { while let firstNewOperation = firstNewOp?.takeUnretainedValue() { let nextNewOp = firstNewOperation.__nextOperation firstNewOperation._invalidateQueue() firstNewOperation.__previousOperation = nil firstNewOperation.__nextOperation = nil _ = firstNewOperation._compareAndSwapState(.enqueuing, .initialized) firstNewOp?.release() firstNewOp = nextNewOp } fatalError("operations finished, executing or already in a queue cannot be enqueued") } // Attach any operations pending attachment to main list if !barrier { _lock() _incrementOperationCount() } var pending = firstNewOp if let pendingOperation = pending?.takeUnretainedValue() { let old_last = __lastOperation pendingOperation.__previousOperation = old_last if let old = old_last?.takeUnretainedValue() { old.__nextOperation = pending } else { __firstOperation = pending } __lastOperation = lastNewOp } while let pendingOperation = pending?.takeUnretainedValue() { if !barrier { var barrierOp = _firstPriorityOperation(Operation.QueuePriority.barrier) while let barrierOperation = barrierOp?.takeUnretainedValue() { pendingOperation._addDependency(barrierOperation) barrierOp = barrierOperation.__nextPriorityOperation } } _ = pendingOperation._compareAndSwapState(.enqueuing, .enqueued) var pri = pendingOperation.__priorityValue if pri == nil { let v = __actualMaxNumOps == 1 ? nil : pendingOperation.__propertyQoS if let qos = v { switch qos { case .default: pri = Operation.QueuePriority.normal.rawValue case .userInteractive: pri = Operation.QueuePriority.veryHigh.rawValue case .userInitiated: pri = Operation.QueuePriority.high.rawValue case .utility: pri = Operation.QueuePriority.low.rawValue case .background: pri = Operation.QueuePriority.veryLow.rawValue } } else { pri = Operation.QueuePriority.normal.rawValue } } pendingOperation.__nextPriorityOperation = nil if let old_last = _lastPriorityOperation(pri)?.takeUnretainedValue() { old_last.__nextPriorityOperation = pending } else { _setFirstPriorityOperation(pri!, pending) } _setlastPriorityOperation(pri!, pending) pending = pendingOperation.__nextOperation } if !barrier { _unlock() } if !barrier { _schedule() } } open func addOperation(_ op: Operation) { _addOperations([op], barrier: false) } open func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) { _addOperations(ops, barrier: false) if wait { for op in ops { op.waitUntilFinished() } } } open func addOperation(_ block: @escaping () -> Void) { let op = BlockOperation(block: block) if let qos = __propertyQoS { op.qualityOfService = qos } addOperation(op) } open func addBarrierBlock(_ barrier: @escaping () -> Void) { var queue: DispatchQueue? _lock() if let op = __firstOperation { let barrierOperation = _BarrierOperation(barrier) barrierOperation.__priorityValue = Operation.QueuePriority.barrier var iterOp: Unmanaged<Operation>? = op while let operation = iterOp?.takeUnretainedValue() { barrierOperation.addDependency(operation) iterOp = operation.__nextOperation } _addOperations([barrierOperation], barrier: true) } else { queue = _synthesizeBackingQueue() } _unlock() if let q = queue { q.async(flags: .barrier, execute: barrier) } else { _schedule() } } open var maxConcurrentOperationCount: Int { get { return _maxNumOps } set(newValue) { if newValue < 0 && newValue != OperationQueue.defaultMaxConcurrentOperationCount { fatalError("count (\(newValue)) cannot be negative") } if !__mainQ { _lock() _maxNumOps = newValue let acnt = OperationQueue.defaultMaxConcurrentOperationCount == newValue || Int32.max < newValue ? Int32.max : Int32(newValue) __actualMaxNumOps = acnt _unlock() _schedule() } } } open var isSuspended: Bool { get { return _isSuspended } set(newValue) { if !__mainQ { _isSuspended = newValue if !newValue { _schedule() } } } } open var name: String? { get { _lock() defer { _unlock() } return __name ?? "NSOperationQueue \(Unmanaged.passUnretained(self).toOpaque())" } set(newValue) { if !__mainQ { _lock() __name = newValue ?? "" _unlock() } } } open var qualityOfService: QualityOfService { get { return _propertyQoS ?? .default } set(newValue) { if !__mainQ { _lock() _propertyQoS = newValue _unlock() } } } unowned(unsafe) open var underlyingQueue: DispatchQueue? { get { if __mainQ { return DispatchQueue.main } else { _lock() defer { _unlock() } return __dispatch_queue } } set(newValue) { if !__mainQ { if 0 < _operationCount { fatalError("operation queue must be empty in order to change underlying dispatch queue") } __dispatch_queue = newValue } } } open func cancelAllOperations() { if !__mainQ { for op in _operations(includingBarriers: true) { op.cancel() } } } open func waitUntilAllOperationsAreFinished() { var ops = _operations(includingBarriers: true) while 0 < ops.count { for op in ops { op.waitUntilFinished() } ops = _operations(includingBarriers: true) } } open class var current: OperationQueue? { get { if Thread.isMainThread { return main } return OperationQueue._currentQueue.current } } open class var main: OperationQueue { get { struct Once { static let mainQ = OperationQueue(asMainQueue: ()) } return Once.mainQ } } } extension OperationQueue { // These two functions are inherently a race condition and should be avoided if possible @available(OSX, introduced: 10.5, deprecated: 100000, message: "access to operations is inherently a race condition, it should not be used. For barrier style behaviors please use addBarrierBlock: instead") open var operations: [Operation] { get { return _operations(includingBarriers: false) } } @available(OSX, introduced: 10.6, deprecated: 100000) open var operationCount: Int { get { return _operationCount } } }
apache-2.0
a299426e0dd17bf2b32b7109946ccd1b
33.7127
219
0.538334
5.317989
false
false
false
false
swilliams/pathway
PathwayExampleApp/PathwayExampleApp/PersonStateMachine.swift
1
1392
// // PersonStateMachine.swift // PathwayExampleApp // // Created by Scott Williams on 2/23/15. // Copyright (c) 2015 Scott Williams. All rights reserved. // import UIKit // This combines both the app's state and the navigation states into a single class. Since the state is simple (2 fields) that's ok, but you'll want to split that out as things start to get a little more complex. class PersonStateMachine: ViewControllerStateMachine { var firstName: String = "" var lastName: String = "" init() { let del = UIApplication.sharedApplication().delegate as? AppDelegate let nav = del?.window?.rootViewController as UINavigationController let firstnameState = NavigationState(identifier: HomeViewController.self) { return HomeViewController(nibName: "HomeViewController", bundle: nil) } let lastnameState = NavigationState(identifier: LastNameViewController.self) { return LastNameViewController(nibName: "LastNameViewController", bundle: nil) } let finalState = NavigationState(identifier: EndViewController.self) { return EndViewController(nibName: "EndViewController", bundle: nil) } let linearDecider = LinearStateMachineLogic(states: [firstnameState, lastnameState, finalState]) super.init(navController: nav, stateMachineLogic: linearDecider) } }
mit
61eb66035c79783f7823e7d47accf174
42.5
212
0.715517
4.867133
false
false
false
false
ygweric/swift-extension
UIButton+Extension.swift
1
2624
// // UIButton+Extension.swift // ZBCool // // Created by ericyang on 11/24/15. // Copyright © 2015 i-chou. All rights reserved. // import UIKit extension UIButton{ convenience init( frame_:CGRect? = nil, imgName:String? = nil, hlImgName:String? = nil, disabledImageName:String? = nil, title:String? = nil, titleColor:UIColor? = nil, hlTitleColor:UIColor? = nil, disabledTitleColor:UIColor? = nil, font:UIFont? = nil, backgroundColor:UIColor? = nil, hlBackgroundColor:UIColor? = nil, titleEdgeInsets:UIEdgeInsets? = nil, contentHorizontalAlignment:UIControlContentHorizontalAlignment? = nil, block:((btn:UIControl)->Void)? = nil ){ self.init(type: .Custom) if (frame_ != nil) { self.frame=frame_! } if !imgName.isNilOrEmpty { self.setBackgroundImage(UIImage(named: imgName!), forState: .Normal) }else if(backgroundColor != nil){ self.setBackgroundImage(UIImage(color: backgroundColor!), forState: .Normal) } if !hlImgName.isNilOrEmpty { self.setBackgroundImage(UIImage(named: hlImgName!), forState: .Highlighted) }else if(hlBackgroundColor != nil){ self.setBackgroundImage(UIImage(color: hlBackgroundColor!), forState: .Highlighted) } if !disabledImageName.isNilOrEmpty { self.setBackgroundImage(UIImage(named: disabledImageName!), forState: .Disabled) } if !title.isNilOrEmpty{ self.setTitle(title, forState: .Normal) } if (titleColor != nil){ self.setTitleColor(titleColor, forState: .Normal) } if (hlTitleColor != nil){ self.setTitleColor(hlTitleColor, forState: .Selected) } if (disabledTitleColor != nil){ self.setTitleColor(disabledTitleColor, forState: .Disabled) } if (font != nil){ self.titleLabel?.font=font } if (titleEdgeInsets != nil){ self.titleEdgeInsets=titleEdgeInsets! } if (contentHorizontalAlignment != nil){ self.contentHorizontalAlignment=contentHorizontalAlignment! } if (block != nil){ self.addControlEvent(.TouchUpInside, closure: block!) } } }
apache-2.0
3eae3a517910a7045e67927a889ed8b6
31.382716
99
0.54289
5.103113
false
false
false
false
tensorflow/swift-models
SwiftModelsBenchmarksCore/BenchmarkSettings.swift
1
3577
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Benchmark import TensorFlow public struct BatchSize: BenchmarkSetting { var value: Int init(_ value: Int) { self.value = value } } public struct Length: BenchmarkSetting { var value: Int init(_ value: Int) { self.value = value } } public struct Synthetic: BenchmarkSetting { var value: Bool init(_ value: Bool) { self.value = value } } public struct Backend: BenchmarkSetting { var value: Value init(_ value: Value) { self.value = value } public enum Value { case x10 case eager } } public struct Platform: BenchmarkSetting { var value: Value init(_ value: Value) { self.value = value } public enum Value { case `default` case cpu case gpu case tpu } } public struct DatasetFilePath: BenchmarkSetting { var value: String init(_ value: String) { self.value = value } } extension BenchmarkSettings { public var batchSize: Int? { return self[BatchSize.self]?.value } public var length: Int? { return self[Length.self]?.value } public var synthetic: Bool { if let value = self[Synthetic.self]?.value { return value } else { fatalError("Synthetic setting must have a default.") } } public var backend: Backend.Value { if let value = self[Backend.self]?.value { return value } else { fatalError("Backend setting must have a default.") } } public var platform: Platform.Value { if let value = self[Platform.self]?.value { return value } else { fatalError("Platform setting must have a default.") } } public var device: Device { // Note: The line is needed, or all GPU memory // will be exhausted on initial allocation of the model. // TODO: Remove the following tensor workaround when above is fixed. let _ = _ExecutionContext.global switch backend { case .eager: switch platform { case .default: return Device.defaultTFEager case .cpu: return Device(kind: .CPU, ordinal: 0, backend: .TF_EAGER) case .gpu: return Device(kind: .GPU, ordinal: 0, backend: .TF_EAGER) case .tpu: fatalError("TFEager is unsupported on TPU.") } case .x10: switch platform { case .default: return Device.defaultXLA case .cpu: return Device(kind: .CPU, ordinal: 0, backend: .XLA) case .gpu: return Device(kind: .GPU, ordinal: 0, backend: .XLA) case .tpu: return (Device.allDevices.filter { $0.kind == .TPU }).first! } } } public var datasetFilePath: String? { return self[DatasetFilePath.self]?.value } } public let defaultSettings: [BenchmarkSetting] = [ TimeUnit(.s), InverseTimeUnit(.s), Backend(.eager), Platform(.default), Synthetic(false), Columns([ "name", "wall_time", "startup_time", "iterations", "avg_exp_per_second", "exp_per_second", "step_time_median", "step_time_min", "step_time_max", ]), ]
apache-2.0
9bfff3bddb42e7c1a38c30c6113af08b
23.006711
77
0.655577
3.842105
false
false
false
false
khizkhiz/swift
test/Serialization/Inputs/def_func.swift
2
1730
public func getZero() -> Int { return 0 } public func getInput(x x: Int) -> Int { return x } public func getSecond(_: Int, y: Int) -> Int { return y } public func useNested(_: (x: Int, y: Int), n: Int) {} public func variadic(x x: Double, _ y: Int...) {} public func variadic2(y: Int..., x: Double) {} public func slice(x x: [Int]) {} public func optional(x x: Int?) {} public func overloaded(x x: Int) {} public func overloaded(x x: Bool) {} // Generic functions. public func makePair<A, B>(a a: A, b: B) -> (A, B) { return (a, b) } public func different<T : Equatable>(a a: T, b: T) -> Bool { return a != b } public func different2<T where T : Equatable>(a a: T, b: T) -> Bool { return a != b } public func selectorFunc1(a a: Int, b x: Int) {} public protocol Wrapped { associatedtype Value : Equatable //var value : Value func getValue() -> Value } public func differentWrapped< T : Wrapped, U : Wrapped where T.Value == U.Value >(a a: T, b: U) -> Bool { return a.getValue() != b.getValue() } @noreturn @_silgen_name("exit") public func exit () -> () @noreturn public func testNoReturnAttr() -> () { exit() } @noreturn public func testNoReturnAttrPoly<T>(x x: T) -> () { exit() } @_silgen_name("primitive") public func primitive() public protocol EqualOperator { func ==(x: Self, y: Self) -> Bool } public func throws1() throws {} public func throws2<T>(t: T) throws -> T { return t } @warn_unused_result(message="you might want to keep it") public func mineGold() -> Int { return 1 } public struct Foo { public init() { } @warn_unused_result(mutable_variant="reverseInPlace") public func reverse() -> Foo { return self } public mutating func reverseInPlace() { } }
apache-2.0
4e36f79856549d06df80d80c6c2fbfc1
20.898734
70
0.634104
3.168498
false
false
false
false
TouchInstinct/LeadKit
TITransitions/Sources/PanelTransition/Animations/DismissAnimation.swift
1
1999
// // Copyright (c) 2020 Touch Instinct // // 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 open class DismissAnimation: BaseAnimation { override open func animator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating { guard let fromView = transitionContext.view(forKey: .from), let fromController = transitionContext.viewController(forKey: .from) else { return UIViewPropertyAnimator() } let initialFrame = transitionContext.initialFrame(for: fromController) let animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { fromView.frame = initialFrame.offsetBy(dx: .zero, dy: initialFrame.height) } animator.addCompletion { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } return animator } }
apache-2.0
b5c1faa9e9259895fd0e78d3a7b1aa94
44.431818
125
0.71936
5.04798
false
false
false
false
Eliothu/WordPress-iOS
WordPress/Classes/ViewRelated/Cells/SwitchTableViewCell.swift
6
2241
import Foundation /** * @class SwitchTableViewCell * @brief The purpose of this class is to simply display a regular TableViewCell, with a Switch * on the right hand side. */ public class SwitchTableViewCell : WPTableViewCell { // MARK: - Public Properties public var onChange : ((newValue: Bool) -> ())? public var name : String { get { return textLabel?.text ?? String() } set { textLabel?.text = newValue } } public var on : Bool { get { return flipSwitch.on } set { flipSwitch.on = newValue } } // MARK: - Initializers public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupSubviews() } public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() } // MARK: - UITapGestureRecognizer Helpers @IBAction private func rowWasPressed(recognizer: UITapGestureRecognizer) { // Manually relay the event, since .ValueChanged doesn't get posted if we toggle the switch // programatically flipSwitch.setOn(!on, animated: true) switchDidChange(flipSwitch) } // MARK: - UISwitch Helpers @IBAction private func switchDidChange(theSwitch: UISwitch) { onChange?(newValue: theSwitch.on) } // MARK: - Private Helpers private func setupSubviews() { selectionStyle = .None contentView.addGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer.addTarget(self, action: "rowWasPressed:") flipSwitch = UISwitch() flipSwitch.addTarget(self, action: "switchDidChange:", forControlEvents: .ValueChanged) accessoryView = flipSwitch WPStyleGuide.configureTableViewCell(self) } // MARK: - Private Properties private let tapGestureRecognizer = UITapGestureRecognizer() // MARK: - Private Outlets private var flipSwitch : UISwitch! }
gpl-2.0
ad2852c69b053a6eacba29cb0ab632f6
25.05814
105
0.601517
5.519704
false
false
false
false
bestwpw/RxSwift
RxSwift/Observables/Implementations/Throttle.swift
2
3395
// // Throttle.swift // Rx // // Created by Krunoslav Zaher on 3/22/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ThrottleSink<O: ObserverType, SchedulerType: Scheduler> : Sink<O>, ObserverType { typealias Element = O.E typealias ParentType = Throttle<Element, SchedulerType> let parent: ParentType var lock = NSRecursiveLock() // state var id = 0 as UInt64 var value: Element? = nil let cancellable = SerialDisposable() init(parent: ParentType, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = parent.source.subscribeSafe(self) return CompositeDisposable(subscription, cancellable) } func on(event: Event<Element>) { switch event { case .Next: break case .Error: fallthrough case .Completed: cancellable.dispose() break } let latestId = self.lock.calculateLocked { () -> UInt64 in let observer = self.observer let oldValue = self.value self.id = self.id &+ 1 switch event { case .Next(let element): self.value = element case .Error: self.value = nil observer?.on(event) self.dispose() case .Completed: self.value = nil if let value = oldValue { observer?.on(.Next(value)) } observer?.on(.Completed) self.dispose() } return id } switch event { case .Next(_): let d = SingleAssignmentDisposable() self.cancellable.disposable = d let scheduler = self.parent.scheduler let dueTime = self.parent.dueTime let disposeTimer = scheduler.scheduleRelative(latestId, dueTime: dueTime) { (id) in self.propagate() return NopDisposable.instance } d.disposable = disposeTimer default: break } } func propagate() { let originalValue: Element? = self.lock.calculateLocked { let originalValue = self.value self.value = nil return originalValue } if let value = originalValue { observer?.on(.Next(value)) } } } class Throttle<Element, SchedulerType: Scheduler> : Producer<Element> { let source: Observable<Element> let dueTime: SchedulerType.TimeInterval let scheduler: SchedulerType init(source: Observable<Element>, dueTime: SchedulerType.TimeInterval, scheduler: SchedulerType) { self.source = source self.dueTime = dueTime self.scheduler = scheduler } override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
87472fc65f248ee7c5c48ac2f2e12d8c
26.836066
139
0.541384
5.207055
false
false
false
false
vokal/Xcode-Template
Vokal-Swift.xctemplate/UserAPI.swift
2
8113
// // ___FILENAME___ // ___PACKAGENAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation /** API for getting information about users. */ struct UserAPI { // MARK: - User Key Enums private enum POSTPath: String, APIVersionable { case login = "authenticate" case register = "user" case facebookLoginRegister = "user/facebook" case notificationRegister = "push/apn" } private enum GETPath: String, APIVersionable { case currentUser = "user" static func specificUser(userID: String) -> String { return "user/" + userID } } private enum JSONKey: String { case email = "email" case password = "password" case userID = "id" case facebookID = "facebook_id" case token = "token" ///Aliases for things that use the same JSON key static let facebookToken = JSONKey.token static let pushNotificationToken = JSONKey.token } // MARK: - Login/Register /** Registers a new user with the given information. - parameter email: The email to register a user for. - parameter password: The password to use for the user being registered. - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ static func register(withEmail email: String, password: String, success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let parameters = [ JSONKey.email.rawValue: email, JSONKey.password.rawValue: password, ] let registerPath = POSTPath.register.path(forVersion: .v1) let headers = requestHeaders(withAuthToken: false) MainAPIUtility .sharedUtility .postUserJSON(to: registerPath, headers: headers, params: parameters, userEmail: email, success: success, failure: failure) } /** Logs in a user with the given information. - parameter email: The email address to use to log in the user. - parameter password: The password to use to log in the user. - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ static func login(withEmail email: String, password: String, success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let parameters = [ JSONKey.email.rawValue: email, JSONKey.password.rawValue: password, ] let loginPath = POSTPath.login.path(forVersion: .v1) let headers = requestHeaders(withAuthToken: false) MainAPIUtility .sharedUtility .postUserJSON(to: loginPath, headers: headers, params: parameters, userEmail: email, success: success, failure: failure) } /** Logs in or registers a user with the given Facebook information. - parameter facebookID: The Facebook identifier of the user to login or register. - parameter facebookToken: The token received from the Facebook SDK - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ static func facebookLoginOrRegister(withFacebookID facebookID: String, facebookToken: String, success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let parameters = [ JSONKey.facebookID.rawValue: facebookID, JSONKey.facebookToken.rawValue: facebookToken, ] let fbLoginRegisterPath = POSTPath.facebookLoginRegister.path(forVersion: .v1) let headers = requestHeaders(withAuthToken: false) MainAPIUtility .sharedUtility .postUserJSON(to: fbLoginRegisterPath, headers: headers, params: parameters, userEmail: facebookID, success: success, failure: failure) } // MARK: - Current User /** Fetches information about the current, logged in user. - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ static func fetchCurrentUserInfo(success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let currentUserFetchPath = GETPath.currentUser.path(forVersion: .v1) let headers = requestHeaders(withAuthToken: true) MainAPIUtility .sharedUtility .getJSON(from: currentUserFetchPath, headers: headers, success: success, failure: failure) } /** Registers the given device token received from the Apple Push Notification Service (APNS) server as a device for the current user. - parameter deviceToken: The device token, converted to a string - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ // TODO: maybe expect an empty response here static func registerCurrentUserForNotifications(withToken deviceToken: String, success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let parameters = [ JSONKey.pushNotificationToken.rawValue: deviceToken, ] let registerDeviceTokenPath = POSTPath.notificationRegister.path(forVersion: .v1) let headers = requestHeaders(withAuthToken: true) MainAPIUtility .sharedUtility .postJSON(to: registerDeviceTokenPath, headers: headers, params: parameters, success: success, failure: failure) } // MARK: - Other Users /** Fetches information about a specific user. - parameter userID: The identifier of the user whose information you wish to retrieve. - parameter success: The closure to execute if the request succeeds. - parameter failure: The closure to execute if the request fails. */ static func fetchUserInfo(forUserID userID: String, success: @escaping APIDictionaryCompletion, failure: @escaping APIFailureCompletion) { let userFetchPath = APIVersion.v1.versioned(path: GETPath.specificUser(userID: userID)) let headers = requestHeaders(withAuthToken: true) MainAPIUtility .sharedUtility .getJSON(from: userFetchPath, headers: headers, success: success, failure: failure) } // MARK: - Private Helper Methods private static func requestHeaders(withAuthToken requiresToken: Bool) -> [HTTPHeaderKey: HTTPHeaderValue] { return MainAPIUtility .sharedUtility .requestHeaders(withAuthToken: requiresToken) } }
mit
518b6cac15b0c0ec8d9ee16221accf2c
36.734884
111
0.569826
5.572115
false
false
false
false
sotownsend/flok-apple
Pod/Classes/Drivers/Timer.swift
1
1018
@objc class FlokTimerModule : FlokModule { override var exports: [String] { return ["if_timer_init:"] } private static var tickHelper: TimerTickHelper! func if_timer_init(args: [AnyObject]) { let tps = args[0] as! Int let secondsPerInterval = 1 / Double(tps) self.dynamicType.tickHelper = TimerTickHelper(interval: secondsPerInterval) { self.engine.int_dispatch([0, "int_timer"]) } self.dynamicType.tickHelper.start() } } @objc class TimerTickHelper : NSObject { let interval: Double let onTick: () -> () init(interval: Double, onTick: ()->()) { self.interval = interval self.onTick = onTick } var timer: NSTimer! func start() { timer = NSTimer(timeInterval: interval, target: self, selector: "tick", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } func tick() { onTick() } }
mit
6ba65198450aa17be78eec0816a22f8e
27.277778
109
0.598232
4.039683
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/Blog+Jetpack.swift
2
1154
extension Blog { func getOption<T>(name: String) -> T? { return getOptionValue(name) as? T } func getOptionString(name: String) -> String? { return (getOption(name: name) as NSString?).map(String.init) } func getOptionNumeric(name: String) -> NSNumber? { switch getOptionValue(name) { case let numericValue as NSNumber: return numericValue case let stringValue as NSString: return stringValue.numericValue() default: return nil } } @objc var jetpack: JetpackState? { guard let options = options, !options.isEmpty else { return nil } let state = JetpackState() state.siteID = getOptionNumeric(name: "jetpack_client_id") state.version = getOptionString(name: "jetpack_version") state.connectedUsername = account?.username ?? getOptionString(name: "jetpack_user_login") state.connectedEmail = getOptionString(name: "jetpack_user_email") state.automatedTransfer = getOption(name: "is_automated_transfer") ?? false return state } }
gpl-2.0
99f09fdb579b6eb57024a2a2b08d78f0
32.941176
98
0.615251
4.40458
false
false
false
false
narner/AudioKit
AudioKit/Common/Operations/AKStereoOperation.swift
1
4278
// // AKStereoOperation.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Stereo version of AKComputedParameter open class AKStereoOperation: AKComputedParameter { // MARK: - Dependency Management fileprivate var inputs = [AKParameter]() fileprivate var savedLocation = -1 fileprivate var dependencies = [AKOperation]() internal var recursiveDependencies: [AKOperation] { var all = [AKOperation]() var uniq = [AKOperation]() var added = Set<String>() for dep in dependencies { all += dep.recursiveDependencies all.append(dep) } for elem in all { if ❗️added.contains(elem.inlineSporth) { uniq.append(elem) added.insert(elem.inlineSporth) } } return uniq } // MARK: - String Representations fileprivate var valueText = "" fileprivate var module = "" internal var setupSporth = "" fileprivate var inlineSporth: String { if valueText != "" { return valueText } var opString = "" for input in inputs { if type(of: input) == AKOperation.self { if let operation = input as? AKOperation { if operation.savedLocation >= 0 { opString += "\(operation.savedLocation) \"ak\" tget " } else { opString += operation.inlineSporth } } } else { opString += "\(input) " } } opString += "\(module) " return opString } /// Final sporth string when this operation is the last operation in the stack internal var sporth: String { let rd = recursiveDependencies var str = "\"ak\" \"" for _ in rd { str += "0 " } str += "\" gen_vals \n" var counter = 0 for op in rd { op.savedLocation = counter str += "\(op.setupSporth) \n" str += "\(op.inlineSporth) \(op.savedLocation) \"ak\" tset\n" counter += 1 } str += "\(setupSporth) \n" str += "\(inlineSporth) \n" return str } /// Redefining description to return the operation string open var description: String { return inlineSporth } // MARK: - Functions /// Create a mono signal by dropping the right channel open func toMono() -> AKOperation { return AKOperation(module: "add", inputs: self) } /// Create a mono signal by dropping the right channel open func left() -> AKOperation { return AKOperation(module: "drop", inputs: self) } /// Create a mono signal by dropping the left channel open func right() -> AKOperation { return AKOperation(module: "swap drop", inputs: self) } /// An operation is requiring a parameter to be stereo, which in this case, it is, so just return self open func toStereo() -> AKStereoOperation { return self } // MARK: - Initialization /// Default stereo input to any operation stack open static var input = AKStereoOperation("((14 p) (15 p))") /// Initialize the stereo operation with a Sporth string /// /// - parameter operationString: Valid Sporth string (proceed with caution /// public init(_ operationString: String) { self.valueText = operationString } /// Initialize the stereo operation /// /// - parameter module: Sporth unit generator /// - parameter setup: Any setup Sporth code that this operation may require /// - parameter inputs: All the parameters of the operation /// public init(module: String, setup: String = "", inputs: AKParameter...) { self.module = module self.setupSporth = setup self.inputs = inputs for input in inputs { if type(of: input) == AKOperation.self { if let forcedInput = input as? AKOperation { dependencies.append(forcedInput) } } } } }
mit
8ef0cbccacf12ba5df82bc7cf8628fe8
28.068027
106
0.5619
4.894616
false
false
false
false
stephentyrone/swift
test/SILGen/scalar_to_tuple_args.swift
1
4168
// RUN: %target-swift-emit-silgen -module-name scalar_to_tuple_args %s | %FileCheck %s func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {} func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {} func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {} func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {} func tupleWithDefaults(x: (Int, Int), y: Int = 0, z: Int = 0) {} func variadicFirst(_ x: Int...) {} func variadicSecond(_ x: Int, _ y: Int...) {} var x = 0 // CHECK: [[X_ADDR:%.*]] = global_addr @$s20scalar_to_tuple_args1xSivp : $*Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args17inoutWithDefaults_1y1zySiz_S2itF // CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]]) inoutWithDefaults(&x) // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args27inoutWithCallerSideDefaults_1yySiz_SitF // CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]]) inoutWithCallerSideDefaults(&x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A12WithDefaults_1y1zySi_S2itF // CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]]) scalarWithDefaults(x) // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] // CHECK: [[LINE_VAL:%.*]] = integer_literal // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]] // CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A22WithCallerSideDefaults_1yySi_SitF // CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]]) scalarWithCallerSideDefaults(x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X1:%.*]] = load [trivial] [[READ]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X2:%.*]] = load [trivial] [[READ]] // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int // CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0C12WithDefaults1x1y1zySi_Sit_S2itF // CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]]) tupleWithDefaults(x: (x,x)) // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]] // CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: copy_addr [[READ]] to [initialization] [[ADDR]] // CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF // CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Int>([[ARRAY]]) // CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @$s20scalar_to_tuple_args13variadicFirstyySid_tF // CHECK: apply [[VARIADIC_FIRST]]([[FIN_ARR]]) variadicFirst(x) // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]] // CHECK: [[FIN_FN:%.*]] = function_ref @$ss27_finalizeUninitializedArrayySayxGABnlF // CHECK: [[FIN_ARR:%.*]] = apply [[FIN_FN]]<Int>([[ARRAY]]) // CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @$s20scalar_to_tuple_args14variadicSecondyySi_SidtF // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[FIN_ARR]]) variadicSecond(x)
apache-2.0
a5b45ae8b0bda104c54fc300dc498526
54.546667
126
0.602496
3.148904
false
false
false
false
NinjaIshere/GKGraphKit
GKGraphKit/GKEntity.swift
1
5582
/** * Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program located at the root of the software package * in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. * * GKEntity * * Represents Entity Nodes, which are person, places, or things -- nouns. */ import Foundation @objc(GKEntity) public class GKEntity: GKNode { /** * init * Initializes GKEntity with a given type. * @param type: String */ override public init(type: String) { super.init(type: type) } /** * actions * Retrieves an Array of GKAction Objects. * @return Array<GKAction> */ public var actions: Array<GKAction> { get { return actionsWhenSubject + actionsWhenObject } set(value) { assert(false, "[GraphKit Error: Actions may not be set.]") } } /** * actionsWhenSubject * Retrieves an Array of GKAction Objects when the Entity is a Subject of the Action. * @return Array<GKAction> */ public var actionsWhenSubject: Array<GKAction> { get { var nodes: Array<GKAction> = Array<GKAction>() graph.managedObjectContext.performBlockAndWait { var node: GKManagedEntity = self.node as GKManagedEntity for item: AnyObject in node.actionSubjectSet { nodes.append(GKAction(action: item as GKManagedAction)) } } return nodes } set(value) { assert(false, "[GraphKit Error: ActionWhenSubject may not be set.]") } } /** * actionsWhenObject * Retrieves an Array of GKAction Objects when the Entity is an Object of the Action. * @return Array<GKAction> */ public var actionsWhenObject: Array<GKAction> { get { var nodes: Array<GKAction> = Array<GKAction>() graph.managedObjectContext.performBlockAndWait { var node: GKManagedEntity = self.node as GKManagedEntity for item: AnyObject in node.actionObjectSet { nodes.append(GKAction(action: item as GKManagedAction)) } } return nodes } set(value) { assert(false, "[GraphKit Error: ActionWhenObject may not be set.]") } } /** * bonds * Retrieves an Array of GKBond Objects. * @return Array<GKBond> */ public var bonds: Array<GKBond> { get { return bondsWhenSubject + bondsWhenObject } set(value) { assert(false, "[GraphKit Error: Bonds may not be set.]") } } /** * bondsWhenSubject * Retrieves an Array of GKBond Objects when the Entity is a Subject of the Bond. * @return Array<GKBond> */ public var bondsWhenSubject: Array<GKBond> { get { var nodes: Array<GKBond> = Array<GKBond>() graph.managedObjectContext.performBlockAndWait { var node: GKManagedEntity = self.node as GKManagedEntity for item: AnyObject in node.bondSubjectSet { nodes.append(GKBond(bond: item as GKManagedBond)) } } return nodes } set(value) { assert(false, "[GraphKit Error: BondWhenSubject may not be set.]") } } /** * bondsWhenObject * Retrieves an Array of GKBond Objects when the Entity is an Object of the Bond. * @return Array<GKBond> */ public var bondsWhenObject: Array<GKBond> { get { var nodes: Array<GKBond> = Array<GKBond>() graph.managedObjectContext.performBlockAndWait { var node: GKManagedEntity = self.node as GKManagedEntity for item: AnyObject in node.bondObjectSet { nodes.append(GKBond(bond: item as GKManagedBond)) } } return nodes } set(value) { assert(false, "[GraphKit Error: BondWhenObject may not be set.]") } } /** * delete * Marks the Model Object to be deleted from the Graph. */ public func delete() { graph.managedObjectContext.performBlockAndWait { var node: GKManagedEntity = self.node as GKManagedEntity node.delete() } } /** * init * Initializes GKEntity with a given GKManagedEntity. * @param entity: GKManagedEntity! */ internal init(entity: GKManagedEntity!) { super.init(node: entity) } /** * createImplementorWithType * Initializes GKManagedEntity with a given type. * @param type: String * @return GKManagedEntity */ override internal func createImplementorWithType(type: String) -> GKManagedNode { return GKManagedEntity(type: type); } }
agpl-3.0
fadd5a4c248081e6c1bb67a6d4e3380d
30.359551
89
0.595485
4.497985
false
false
false
false
googleprojectzero/fuzzilli
Sources/FuzzilliCli/Profiles/JSCProfile.swift
1
4931
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 Fuzzilli fileprivate let ForceDFGCompilationGenerator = CodeGenerator("ForceDFGCompilationGenerator", input: .function()) { b, f in // The MutationEngine may use variables of unknown type as input as well, however, we only want to call functions that we generated ourselves. Further, attempting to call a non-function will result in a runtime exception. // For both these reasons, we abort here if we cannot prove that f is indeed a function. guard b.type(of: f).Is(.function()) else { return } guard let arguments = b.randCallArguments(for: f) else { return } b.buildRepeat(n: 10) { _ in b.callFunction(f, withArgs: arguments) } } fileprivate let ForceFTLCompilationGenerator = CodeGenerator("ForceFTLCompilationGenerator", input: .function()) { b, f in guard b.type(of: f).Is(.function()) else { return } guard let arguments = b.randCallArguments(for: f) else { return } b.buildRepeat(n: 100) { _ in b.callFunction(f, withArgs: arguments) } } let jscProfile = Profile( getProcessArguments: { (randomizingArguments: Bool) -> [String] in var args = [ "--validateOptions=true", // No need to call functions thousands of times before they are JIT compiled "--thresholdForJITSoon=10", "--thresholdForJITAfterWarmUp=10", "--thresholdForOptimizeAfterWarmUp=100", "--thresholdForOptimizeAfterLongWarmUp=100", "--thresholdForOptimizeSoon=100", "--thresholdForFTLOptimizeAfterWarmUp=1000", "--thresholdForFTLOptimizeSoon=1000", // Enable bounds check elimination validation "--validateBCE=true", "--reprl"] guard randomizingArguments else { return args } args.append("--useBaselineJIT=\(probability(0.9) ? "true" : "false")") args.append("--useDFGJIT=\(probability(0.9) ? "true" : "false")") args.append("--useFTLJIT=\(probability(0.9) ? "true" : "false")") args.append("--useRegExpJIT=\(probability(0.9) ? "true" : "false")") args.append("--useTailCalls=\(probability(0.9) ? "true" : "false")") args.append("--optimizeRecursiveTailCalls=\(probability(0.9) ? "true" : "false")") args.append("--useObjectAllocationSinking=\(probability(0.9) ? "true" : "false")") args.append("--useArityFixupInlining=\(probability(0.9) ? "true" : "false")") args.append("--useValueRepElimination=\(probability(0.9) ? "true" : "false")") args.append("--useArchitectureSpecificOptimizations=\(probability(0.9) ? "true" : "false")") args.append("--useAccessInlining=\(probability(0.9) ? "true" : "false")") return args }, processEnv: ["UBSAN_OPTIONS":"handle_segv=0"], codePrefix: """ function main() { """, codeSuffix: """ gc(); } noDFG(main); noFTL(main); main(); """, ecmaVersion: ECMAScriptVersion.es6, crashTests: ["fuzzilli('FUZZILLI_CRASH', 0)", "fuzzilli('FUZZILLI_CRASH', 1)", "fuzzilli('FUZZILLI_CRASH', 2)"], additionalCodeGenerators: [ (ForceDFGCompilationGenerator, 5), (ForceFTLCompilationGenerator, 5), ], additionalProgramTemplates: WeightedList<ProgramTemplate>([]), disabledCodeGenerators: [], additionalBuiltins: [ "gc" : .function([] => .undefined), "transferArrayBuffer" : .function([.object(ofGroup: "ArrayBuffer")] => .undefined), "noInline" : .function([.function()] => .undefined), "noFTL" : .function([.function()] => .undefined), "createGlobalObject" : .function([] => .object()), "OSRExit" : .function([] => .unknown), "drainMicrotasks" : .function([] => .unknown), "runString" : .function([.string] => .unknown), "makeMasquerader" : .function([] => .unknown), "fullGC" : .function([] => .undefined), "edenGC" : .function([] => .undefined), "fiatInt52" : .function([.number] => .number), "forceGCSlowPaths" : .function([] => .unknown), "ensureArrayStorage" : .function([] => .unknown), ] )
apache-2.0
a99c54dfb8182ba3413bcc02eb99f32e
42.637168
225
0.606976
4.028595
false
false
false
false
finngaida/wwdc
2016/Finn Gaida/AppBoxWidget.swift
1
958
// // AppBoxWidget.swift // Finn Gaida // // Created by Finn Gaida on 24.04.16. // Copyright © 2016 Finn Gaida. All rights reserved. // import UIKit import GradientView class AppBoxWidget: UIView { override init(frame: CGRect) { super.init(frame: frame) self.layer.masksToBounds = true self.layer.cornerRadius = frame.height / 20 let gradientView = GradientView(frame: CGRectMake(0, 0, frame.width, frame.height)) gradientView.colors = [UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1), UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)] self.addSubview(gradientView) let confetti = SAConfettiView(frame: gradientView.frame) confetti.startConfetti() self.layer.addSublayer(confetti.layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
308d5e99566105e4e8e2adcd29ebbce3
27.147059
154
0.636364
3.797619
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Home/Views/HomePlaylistCollectionViewLayout.swift
1
3194
// // HomePlaylistCollectionViewLayout.swift // MusicApp // // Created by Hưng Đỗ on 7/1/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit let kHomePlaylistCollectionViewLayoutMaximumElements = 6 protocol HomePlaylistCollectionViewLayoutDelegate: class { func itemSizeForCollectionView(_ collectionView: UICollectionView) -> CGFloat func itemPaddingForCollectionView(_ collectionView: UICollectionView) -> CGFloat } class HomePlaylistCollectionViewLayout: UICollectionViewLayout { weak var delegate: HomePlaylistCollectionViewLayoutDelegate? fileprivate var cache = [UICollectionViewLayoutAttributes]() override func prepare() { guard cache.isEmpty else { return } guard let collectionView = collectionView else { return } guard collectionView.numberOfItems(inSection: 0) == 6 else { return } guard let itemSize = self.delegate?.itemSizeForCollectionView(collectionView) else { return } guard let itemPadding = self.delegate?.itemPaddingForCollectionView(collectionView) else { return } let bigLayoutAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0)) bigLayoutAttributes.frame = CGRect( x: itemPadding, y: itemPadding, width: 2 * itemSize + itemPadding, height: 2 * itemSize + itemPadding ) cache.append(bigLayoutAttributes) for item in 1 ... 2 { let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: 0)) layoutAttributes.frame = CGRect( x: 2 * itemSize + 3 * itemPadding, y: CGFloat(item - 1) * (itemSize + itemPadding) + itemPadding, width: itemSize, height: itemSize ) cache.append(layoutAttributes) } for item in 3 ... 5 { let layoutAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: 0)) layoutAttributes.frame = CGRect( x: itemPadding + CGFloat(item - 3) * (itemSize + itemPadding), y: 2 * itemSize + 3 * itemPadding, width: itemSize, height: itemSize ) cache.append(layoutAttributes) } } override var collectionViewContentSize : CGSize { guard let collectionView = collectionView else { return CGSize.zero } guard let itemSize = self.delegate?.itemSizeForCollectionView(collectionView) else { return CGSize.zero } guard let itemPadding = self.delegate?.itemPaddingForCollectionView(collectionView) else { return CGSize.zero } return CGSize( width: 3 * itemSize + 4 * itemPadding, height: 3 * itemSize + 2 * itemPadding ) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let layoutAttributes = cache.filter { $0.frame.intersects(rect) } return layoutAttributes.isEmpty ? nil : layoutAttributes } }
mit
8262925fa49521b0b08bcd5526079574
37.890244
119
0.64503
5.488812
false
false
false
false
0x4a616e/ArtlessEdit
ArtlessEdit/OpenFilesDataSource.swift
1
1190
// // OpenFilesDataSource.swift // ArtlessEdit // // Created by Jan Gassen on 04/01/15. // Copyright (c) 2015 Jan Gassen. All rights reserved. // import Foundation class OpenFilesDataSource: NSObject, NSTableViewDelegate, NSTableViewDataSource { lazy var workspace = NSWorkspace.sharedWorkspace() lazy var documentController:NSDocumentController = NSDocumentController.sharedDocumentController() as NSDocumentController func tableView(tableView: NSTableView!, viewForTableColumn tableColumn: NSTableColumn!, row: Int)-> NSTableCellView? { var doc: Document = documentController.documents[row] as Document var view = tableView.makeViewWithIdentifier("OpenFileView", owner: self) as NSTableCellView?; view?.textField?.stringValue = doc.displayName if let path = doc.fileURL?.path { view?.imageView?.image = workspace.iconForFile(path) } else { view?.imageView?.image = workspace.iconForFileType(NSFileTypeUnknown) } return view } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return documentController.documents.count } }
bsd-3-clause
19960c90b1f7e9bf443f53d6ccc71d91
35.090909
126
0.69916
5.196507
false
false
false
false
andrea-prearo/SwiftExamples
SmoothScrolling/Client/Shared/Prefetch/ImageLoadOperation.swift
1
861
// // ImageLoadOperation.swift // SmoothScrolling // // Created by Andrea Prearo on 2/15/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import UIKit typealias ImageLoadOperationCompletionHandlerType = ((UIImage) -> ()) class ImageLoadOperation: Operation { var url: String var completionHandler: ImageLoadOperationCompletionHandlerType? var image: UIImage? init(url: String) { self.url = url } override func main() { if isCancelled { return } UIImage.downloadImageFromUrl(url) { [weak self] (image) in guard let strongSelf = self, !strongSelf.isCancelled, let image = image else { return } strongSelf.image = image strongSelf.completionHandler?(image) } } }
mit
c28ee9c88d51994a55f0ecd467fb7886
22.243243
69
0.596512
4.858757
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Styles/Style.swift
1
9285
// // Style.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import Reactant #endif /** * Style identifier used to resolve the style name. */ public enum StyleName: XMLAttributeDeserializable, XMLAttributeName { case local(name: String) case global(group: String, name: String) /** * Gets the `name` variable from either of the cases. */ public var name: String { switch self { case .local(let name): return name case .global(_, let name): return name } } public init(from value: String) throws { let notationCharacter: String if value.contains(".") { notationCharacter = "." } else { notationCharacter = ":" } let components = value.components(separatedBy: notationCharacter).filter { !$0.isEmpty } if components.count == 2 { self = .global(group: components[0], name: components[1]) } else if components.count == 1 { self = .local(name: components[0]) } else { throw TokenizationError.invalidStyleName(text: value) } } /** * Generates an XML `String` representation of the `StyleName`. * - returns: XML `String` representation of the `StyleName` */ public func serialize() -> String { switch self { case .local(let name): return name case .global(let group, let name): return ":\(group):\(name)" } } /** * Tries to parse the passed XML attribute into a `StyleName` identifier. * - parameter attribute: XML attribute to be parsed into `StyleName` * - returns: if not thrown, the parsed `StyleName` */ public static func deserialize(_ attribute: XMLAttribute) throws -> StyleName { return try StyleName(from: attribute.text) } } extension StyleName: Equatable { public static func ==(lhs: StyleName, rhs: StyleName) -> Bool { switch (lhs, rhs) { case (.local(let lName), .local(let rName)): return lName == rName case (.global(let lGroup, let lName), .global(let rGroup, let rName)): return lGroup == rGroup && lName == rName default: return false } } } /** * Structure representing an XML style. * * Example: * ``` * <styles name="ReactantStyles"> * <LabelStyle name="base" backgroundColor="white" /> * <ButtonStyle name="buttona" * backgroundColor.highlighted="white" * isUserInteractionEnabled="true" /> * <attributedTextStyle name="bandaska" extend="common:globalko"> * <i font=":bold@20" /> * <base foregroundColor="white" /> * </attributedTextStyle> * </styles> * ``` */ public struct Style: XMLAttributeDeserializable, XMLElementDeserializable { public var name: StyleName public var extend: [StyleName] public var accessModifier: AccessModifier public var parentModuleImport: String public var properties: [Property] public var type: StyleType init(node: XMLElement, groupName: String?) throws { let name = try node.value(ofAttribute: "name") as String let extendedStyles = try node.value(ofAttribute: "extend", defaultValue: []) as [StyleName] if let modifier = node.value(ofAttribute: "accessModifier") as String? { accessModifier = AccessModifier(rawValue: modifier) ?? .internal } else { accessModifier = .internal } if let groupName = groupName { self.name = .global(group: groupName, name: name) self.extend = extendedStyles.map { if case .local(let name) = $0 { return .global(group: groupName, name: name) } else { return $0 } } } else { self.name = .local(name: name) self.extend = extendedStyles } if node.name == "attributedTextStyle" { parentModuleImport = "Reactant" properties = try PropertyHelper.deserializeSupportedProperties(properties: Properties.attributedText.allProperties, in: node) as [Property] type = try .attributedText(styles: node.xmlChildren.map(AttributedTextStyle.deserialize)) } else if let (elementName, element) = ElementMapping.mapping.first(where: { node.name == "\($0.key)Style" }) { parentModuleImport = element.parentModuleImport properties = try PropertyHelper.deserializeSupportedProperties(properties: element.availableProperties, in: node) as [Property] type = .view(type: elementName) } else { throw TokenizationError(message: "Unknown style \(node.name). (\(node))") } } /** * Checks if any of Style's properties require theming. * - parameter context: context to use * - returns: `Bool` whether or not any of its properties require theming */ public func requiresTheme(context: DataContext) -> Bool { return properties.contains(where: { $0.anyValue.requiresTheme }) || extend.contains(where: { context.style(named: $0)?.requiresTheme(context: context) == true }) } /** * Tries to create the `Style` structure from an XML element. * - parameter element: XML element to parse * - returns: if not thrown, `Style` obtained from the passed XML element */ public static func deserialize(_ element: XMLElement) throws -> Style { return try Style(node: element, groupName: nil) } } /** * Represents `Style`'s type. * Currently, there are: * - view: basic UI element styling * - attributedText: attributed string styling allowing multiple attributed style tags to be defined within it */ public enum StyleType { case view(type: String) case attributedText(styles: [AttributedTextStyle]) public var styleType: String { switch self { case .view(let type): return type case .attributedText: return "attributedText" } } } /** * Structure representing a single tag inside an <attributedTextStyle> element within `StyleGroup` (<styles>). */ public struct AttributedTextStyle: XMLElementDeserializable { public var name: String public var accessModifier: AccessModifier public var properties: [Property] init(node: XMLElement) throws { name = node.name if let modifier = node.value(ofAttribute: "accessModifier") as String? { accessModifier = AccessModifier(rawValue: modifier) ?? .internal } else { accessModifier = .internal } properties = try PropertyHelper.deserializeSupportedProperties(properties: Properties.attributedText.allProperties, in: node) as [Property] } public static func deserialize(_ element: XMLElement) throws -> AttributedTextStyle { return try AttributedTextStyle(node: element) } } extension XMLElement { public func value<T: XMLAttributeDeserializable>(ofAttribute attr: String, defaultValue: T) throws -> T { if let attr = self.attribute(by: attr) { return try T.deserialize(attr) } else { return defaultValue } } } extension Sequence where Iterator.Element == Style { public func resolveStyle(for element: UIElement) throws -> [Property] { guard !element.styles.isEmpty else { return element.properties } guard let type = ElementMapping.mapping.first(where: { $0.value == type(of: element) })?.key else { print("// No type found for \(element)") return element.properties } let viewStyles = compactMap { style -> Style? in if case .view(let styledType) = style.type, styledType == type { return style } else { return nil } } // FIXME This will be slow var result = Dictionary<String, Property>(minimumCapacity: element.properties.count) for name in element.styles { for property in try viewStyles.resolveViewStyle(for: type, named: name) { result[property.attributeName] = property } } for property in element.properties { result[property.attributeName] = property } return Array(result.values) } private func resolveViewStyle(for type: String, named name: StyleName) throws -> [Property] { guard let style = first(where: { $0.name == name }) else { // FIXME wrong type of error throw TokenizationError(message: "Style \(name) for type \(type) doesn't exist!") } let baseProperties = try style.extend.flatMap { base in try resolveViewStyle(for: type, named: base) } // FIXME This will be slow var result = Dictionary<String, Property>(minimumCapacity: style.properties.count) for property in baseProperties + style.properties { result[property.attributeName] = property } return Array(result.values) } }
mit
bea627fac05e7ba472f9ba45628f498a
33.771536
151
0.616652
4.589224
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPCityRegionModel.swift
1
7386
// // KPCityRegionModel.swift // kapi-kaffeine // // Created by MengHsiu Chang on 29/08/2017. // Copyright © 2017 kapi-kaffeine. All rights reserved. // import UIKit struct regionData { var name: String var icon: UIImage var cities: [String] var cityKeys: [String] var countryKeys: [String] var cityCoordinate: [CLLocationCoordinate2D] var expanded: Bool } class KPCityRegionModel: NSObject { static let defaultRegionData = [regionData(name:"北部", icon:R.image.icon_taipei()!, cities:["台北 Taipei", "基隆 Keelung", "桃園 Taoyuan", "新竹 Hsinchu"], cityKeys:["taipei", "keelung", "taoyuan", "hsinchu"], countryKeys:["tw", "tw", "tw", "tw",], cityCoordinate: [CLLocationCoordinate2D(latitude: 25.0470462, longitude: 121.5156119), CLLocationCoordinate2D(latitude: 25.131736, longitude: 121.738372), CLLocationCoordinate2D(latitude: 24.989206, longitude: 121.311351), CLLocationCoordinate2D(latitude: 24.8015771, longitude: 120.969366)], expanded: false), regionData(name:"東部", icon:R.image.icon_taitung()!, cities:["宜蘭 Yilan", "花蓮 Hualien", "台東 Taitung", "澎湖 Penghu"], cityKeys:["yilan", "hualien", "taitung", "penghu"], countryKeys:["tw", "tw", "tw", "tw",], cityCoordinate: [CLLocationCoordinate2D(latitude: 24.7543117, longitude: 121.756184), CLLocationCoordinate2D(latitude: 23.9929463, longitude: 121.5989202), CLLocationCoordinate2D(latitude: 22.791625, longitude: 121.1233145), CLLocationCoordinate2D(latitude: 23.6294021, longitude: 119.526859)], expanded: false), regionData(name:"中部", icon:R.image.icon_taichung()!, cities:["苗栗 Miaoli", "台中 Taichung", "南投 Nantou", "彰化 Changhua", "雲林 Yunlin"], cityKeys:["miaoli", "taichung", "nantou", "changhua", "yunlin"], countryKeys:["tw", "tw", "tw", "tw",], cityCoordinate: [CLLocationCoordinate2D(latitude: 24.57002, longitude: 120.820149), CLLocationCoordinate2D(latitude: 24.1375758, longitude: 120.6844115), CLLocationCoordinate2D(latitude: 23.8295543, longitude: 120.7904003), CLLocationCoordinate2D(latitude: 24.0816314, longitude: 120.5362503), CLLocationCoordinate2D(latitude: 23.7289229, longitude: 120.4206707)], expanded: false), regionData(name:"南部", icon:R.image.icon_pingtung()!, cities:["嘉義 Chiayi", "台南 Tainan", "高雄 Kaohsiung", "屏東 Pingtung"], cityKeys:["chiayi", "tainan", "kaohsiung", "pingtung"], countryKeys:["tw", "tw", "tw", "tw",], cityCoordinate: [CLLocationCoordinate2D(latitude: 23.4791187, longitude: 120.4389442), CLLocationCoordinate2D(latitude: 22.9719654, longitude: 120.2140395), CLLocationCoordinate2D(latitude: 22.6397615, longitude: 120.299913), CLLocationCoordinate2D(latitude: 22.668857, longitude: 120.4837693)], expanded: false), regionData(name:"其他國家", icon:R.image.icon_global()!, cities:["日本 Japan", "英國 England", "美國 United States"], cityKeys:["jp", "gb", "us"], countryKeys:["jp", "gb", "us"], cityCoordinate: [CLLocationCoordinate2D(latitude: 35.6811673, longitude: 139.7648576), CLLocationCoordinate2D(latitude: 51.5316396, longitude: -0.1266171), CLLocationCoordinate2D(latitude: 37.7631955, longitude: -122.4294305)], expanded: false)] static func getRegionStringWithKey(_ key: String?) -> String? { if key == nil { return nil } for region in defaultRegionData { for (index, regionkey) in region.cityKeys.enumerated() { if key == regionkey { return region.cities[index] } } } return nil } static func getKeyWithRegionString(_ region: String?) -> String? { if region == nil || region == "" { return nil } for regionData in defaultRegionData { for (index, regionString) in regionData.cities.enumerated() { if region == regionString { return regionData.cityKeys[index] } } } return nil } static func getCountryWithRegionString(_ region: String?) -> String? { if region == nil || region == "" { return nil } for regionData in defaultRegionData { for (index, regionString) in regionData.cities.enumerated() { if region == regionString { return regionData.countryKeys[index] } } } return nil } }
mit
a0c0d30ccb72f88d19b3c240d0496a5a
49.916084
104
0.394177
5.644186
false
false
false
false
WE-St0r/SwiftyVK
Library/Sources/API/Upload.swift
2
19183
import CoreLocation /// File uploading target public enum UploadTarget { case user(id: String) case group(id: String) var decoded: (userId: String?, groupId: String?) { switch self { case .user(let id): return (userId: id, groupId: nil) case .group(let id): return (userId: nil, groupId: id) } } var signed: String { switch self { case .user(let id): return id case .group(let id): return "-" + id } } } public typealias PhotoCrop = (x: String?, y: String?, w: String?) public typealias CoverCrop = (x: String, y: String, x2: String, y2: String) // swiftlint:disable next nesting // swiftlint:disable next type_body_length extension APIScope { /// Metods to upload Mediafiles. More info - https://vk.com/dev/upload_files public struct Upload { ///Methods to upload photo public struct Photo { /// Upload photo to user or group avatar public static func toMain( _ media: Media, to target: UploadTarget, crop: PhotoCrop? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getOwnerPhotoUploadServer([ .ownerId: target.signed ]) .chain { let response = try JSON(data: $0) let crop = crop.flatMap { "&_square_crop=\($0.x ?? ""),\($0.y ?? ""),\($0.w ?? "")" } ?? "" return Request( type: .upload( url: response.forcedString("upload_url") + crop, media: [media], partType: .photo ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveOwnerPhoto([ .server: response.forcedInt("server").toString(), .photo: response.forcedString("photo"), .hash: response.forcedString("hash") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload chat main photo public static func toChatMain( _ media: Media, to chatId: Int, crop: PhotoCrop? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getChatUploadServer([ .chatId: String(chatId), .cropX: crop?.x, .cropY: crop?.y, .cropWidth: crop?.w ]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Messages.setChatPhoto([ .file: response.forcedString("response") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo to group cover public static func toGroupCover( _ media: Media, to groupId: Int, crop: CoverCrop ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getOwnerCoverPhotoUploadServer([ .groupId: String(groupId), .cropX: crop.x, .cropY: crop.y, .cropX2: crop.x2, .cropY2: crop.y2 ]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .photo ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveOwnerCoverPhoto([ .photo: response.forcedString("photo"), .hash: response.forcedString("hash") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo to user album public static func toAlbum( _ media: [Media], to target: UploadTarget, albumId: String, caption: String? = nil, location: CLLocationCoordinate2D? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getUploadServer([ .albumId: albumId, .userId: target.decoded.userId, .groupId: target.decoded.groupId ]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: Array(media.prefix(5)), partType: .indexedFile ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.save([ .albumId: albumId, .userId: target.decoded.userId, .groupId: target.decoded.groupId, .server: response.forcedInt("server").toString(), .photosList: response.forcedString("photos_list"), .aid: response.forcedInt("aid").toString(), .hash: response.forcedString("hash"), .caption: caption, .latitude: location?.latitude.toString(), .longitude: location?.longitude.toString() ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo for using in messages.send method public static func toMessage(_ media: Media, peerId: String? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getMessagesUploadServer([.peerId: peerId]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .photo ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveMessagesPhoto([ .photo: response.forcedString("photo"), .server: response.forcedInt("server").toString(), .hash: response.forcedString("hash") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo for using in market.add or market.edit methods public static func toMarket( _ media: Media, mainPhotoCrop: PhotoCrop?, groupId: String ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getMarketUploadServer([.groupId: groupId]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveMarketPhoto([ .groupId: groupId, .photo: response.forcedString("photo"), .server: response.forcedInt("server").toString(), .hash: response.forcedString("hash"), .cropData: response.forcedString("crop_data"), .cropHash: response.forcedString("crop_hash"), .mainPhoto: (mainPhotoCrop != nil ? "1" : "0"), .cropX: mainPhotoCrop?.x, .cropY: mainPhotoCrop?.y, .cropWidth: mainPhotoCrop?.w ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo for using in market.addAlbum or market.editAlbum methods public static func toMarketAlbum( _ media: Media, groupId: String ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getMarketAlbumUploadServer([.groupId: groupId]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveMarketAlbumPhoto([ .groupId: groupId, .photo: response.forcedString("photo"), .server: response.forcedInt("server").toString(), .hash: response.forcedString("hash") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload photo for using in wall.post method public static func toWall( _ media: Media, to target: UploadTarget ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Photos.getWallUploadServer([ .userId: target.decoded.userId, .groupId: target.decoded.groupId ]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .photo ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Photos.saveWallPhoto([ .userId: target.decoded.userId, .groupId: target.decoded.groupId, .photo: response.forcedString("photo"), .server: response.forcedInt("server").toString(), .hash: response.forcedString("hash") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } } /// Upload video file to "my videos" public static func video( _ media: Media, savingParams: Parameters = .empty ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Video.save(savingParams) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .video ), config: .upload ) .toMethod() } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload audio to "My audios" public static func audio( _ media: Media, artist: String? = nil, title: String? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Audio.getUploadServer(.empty) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Audio.save([ .audio: response.forcedString("audio"), .server: response.forcedInt("server").toString(), .hash: response.forcedString("hash"), .artist: artist, .title: title ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload document public static func document( _ media: Media, groupId: String? = nil, title: String? = nil, tags: String? = nil ) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Docs.getUploadServer([.groupId: groupId]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Docs.save([ .file: response.forcedString("file"), .title: title, .tags: tags ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } /// Upload audio for using in messages.send method public static func toAudioMessage(_ media: Media) -> Methods.SuccessableFailableProgressableConfigurable { let method = APIScope.Docs.getMessagesUploadServer ([ .type: "audio_message" ]) .chain { let response = try JSON(data: $0) return Request( type: .upload( url: response.forcedString("upload_url"), media: [media], partType: .file ), config: .upload ) .toMethod() } .chain { let response = try JSON(data: $0) return APIScope.Docs.save([ .file: response.forcedString("file") ]) } return Methods.SuccessableFailableProgressableConfigurable(method.request) } } }
mit
3823e26820f12f85d78092675bd36cdd
40.077088
115
0.389616
6.415719
false
true
false
false
cfilipov/MuscleBook
MuscleBook/DebugTimersViewController.swift
1
1598
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import Eureka class DebugTimersViewController : FormViewController { let decimalFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle formatter.maximumFractionDigits = 4 return formatter }() override func viewDidLoad() { super.viewDidLoad() title = "Timers" form +++ Section() <<< Profiler.sharedinstance .traces .values .sort() .map(rowForTrace) } func rowForTrace(trace: Profiler.Trace) -> BaseRow { return LabelRow() { $0.title = trace.title $0.value = self.decimalFormatter.stringFromNumber(trace.duration) }.cellSetup { cell, row in if trace.duration > 0.25 { cell.detailTextLabel?.textColor = UIColor.redColor() } } } }
gpl-3.0
6ae043312d39f36dd12bd33e30319771
28.054545
77
0.660826
4.842424
false
false
false
false
Rflpz/Timing
Timing/TMTimerViewController.swift
1
1031
// // TMTimerViewController.swift // Timing // // Created by Rflpz on 20/10/14. // Copyright (c) 2014 Rflpz. All rights reserved. // import UIKit class TMTimerViewController: UIViewController { var titleView:String! override func viewDidLoad() { super.viewDidLoad() customizeView() customItemsBar() } } //MARK: - Customize navigatioController extension TMTimerViewController{ func customizeView(){ title = titleView self.navigationController?.navigationBar.topItem?.title = "" } func customItemsBar(){ UIBarButtonItemStyle.Plain var imgButton = UIImage(named: "edit") var buttonRight = UIBarButtonItem(image: imgButton, style: .Plain, target: self, action:("editActivity")) buttonRight.tintColor = .whiteColor() self.navigationItem.rightBarButtonItem = buttonRight } } //MARK: - Edit activity extension TMTimerViewController{ func editActivity(){ println("Edit") } }
mit
6e231088f5739e34bf43a5f7263ea89c
21.933333
113
0.650824
4.52193
false
false
false
false
sora0077/QiitaKit
QiitaKit/src/Endpoint/User/ListUserFollowees.swift
1
2060
// // ListUserFollowees.swift // QiitaKit // // Created on 2015/06/08. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit import Result /** * ユーザがフォローしているユーザ一覧を取得します。 */ public struct ListUserFollowees { public let id: User.Identifier /// ページ番号 (1から100まで) /// example: 1 /// ^[0-9]+$ public let page: Int /// 1ページあたりに含まれる要素数 (1から100まで) /// example: 20 /// ^[0-9]+$ public let per_page: Int public init(id: User.Identifier, page: Int, per_page: Int = 20) { self.id = id self.page = page self.per_page = per_page } } extension ListUserFollowees: QiitaRequestToken { public typealias Response = ([User], LinkMeta<ListUserFollowees>) public typealias SerializedObject = [[String: AnyObject]] public var method: HTTPMethod { return .GET } public var path: String { return "/api/v2/users/\(id)/followees" } public var parameters: [String: AnyObject]? { return [ "page": page, "per_page": per_page ] } } extension ListUserFollowees: LinkProtocol { public init(url: NSURL!) { let comps = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) self.page = Int(find(comps?.queryItems ?? [], name: "page")!.value!)! if let value = find(comps?.queryItems ?? [], name: "per_page")?.value, let per_page = Int(value) { self.per_page = per_page } else { self.per_page = 20 } self.id = url.pathComponents![url.pathComponents!.count - 2] } } public extension ListUserFollowees { func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { return (try _Users(object), LinkMeta<ListUserFollowees>(dict: response!.allHeaderFields)) } }
mit
867c46936bbb1809dc910b3416a7e69c
22.780488
119
0.591795
3.80117
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/Sections/ShotSectionReactor.swift
1
1967
// // ShotSectionReactor.swift // Drrrible // // Created by Suyeol Jeon on 09/09/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import ReactorKit import RxSwift import SectionReactor final class ShotSectionReactor: SectionReactor { enum SectionItem { case image(ShotViewImageCellReactor) case title(ShotViewTitleCellReactor) case text(ShotViewTextCellReactor) case reaction(ShotViewReactionCellReactor) } enum Action { case updateShot(Shot) } enum Mutation { case setShot(Shot) } struct State: SectionReactorState { var sectionItems: [SectionItem] = [] } let initialState: State fileprivate let reactionCellReactorFactory: (Shot) -> ShotViewReactionCellReactor init( shotID: Int, shot initialShot: Shot? = nil, reactionCellReactorFactory: @escaping (Shot) -> ShotViewReactionCellReactor ) { defer { _ = self.state } let sectionItems: [SectionItem] if let shot = initialShot { sectionItems = [ .image(ShotViewImageCellReactor(shot: shot)), .title(ShotViewTitleCellReactor(shot: shot)), .text(ShotViewTextCellReactor(shot: shot)), .reaction(reactionCellReactorFactory(shot)), ] } else { sectionItems = [] } self.initialState = State(sectionItems: sectionItems) self.reactionCellReactorFactory = reactionCellReactorFactory } func mutate(action: Action) -> Observable<Mutation> { switch action { case let .updateShot(shot): return .just(.setShot(shot)) } } func reduce(state: State, mutation: Mutation) -> State { var state = state switch mutation { case let .setShot(shot): state.sectionItems = [ .image(ShotViewImageCellReactor(shot: shot)), .title(ShotViewTitleCellReactor(shot: shot)), .text(ShotViewTextCellReactor(shot: shot)), .reaction(self.reactionCellReactorFactory(shot)), ] } return state } }
mit
242d06d957c0a1939f7e6e0fc66cc626
24.532468
83
0.681078
4.218884
false
false
false
false
cactis/SwiftEasyKit
Source/Extensions/UIButton.swift
1
9587
// // UIButton.swift // // Created by ctslin on 5/18/16. // import Foundation import MapKit import LoremIpsum import FontAwesome_swift import Neon import SwiftRandom extension UIButton { public func layoutAsSubmit() { anchorAndFillEdge(.bottom, xPad: 0, yPad: 0, otherSize: estimateHeight()) } open func estimateHeight() -> CGFloat { return K.Size.Submit.height + 2 * K.Size.Padding.large } @discardableResult public func html(_ html: NSAttributedString?) -> UIButton { if let _ = html { self.setAttributedTitle(html, for: .normal) } return self } public func autoWidth(weight: CGFloat = 1) -> CGFloat { return textWidth() == 0 ? 0 : textWidth() + weight * K.Size.Text.normal } public func autoHeight(weight: CGFloat = 1) -> CGFloat { return textWidth() == 0 ? 0 : textHeight() + weight * K.Size.Text.normal } @discardableResult public func textUnderlined(_ text: String?, color: UIColor = K.Color.text, size: CGFloat = K.Size.Text.normal.smaller()) -> UIButton { if text != nil { let titleString = NSMutableAttributedString(string: text!) let range = NSMakeRange(0, (text?.characters.count)!) titleString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: range) titleString.addAttributes([NSAttributedStringKey.foregroundColor: color], range: range) titleString.addAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: size)], range: range) self.setAttributedTitle(titleString, for: .normal) } return self } @objc public convenience init(iconCode: String) { self.init(frame: .zero) setTitle(iconCode, for: .normal) setTitleColor(K.Color.text, for: .normal) titleLabel?.font = UIFont(name: K.Font.icon, size: K.Size.barButtonItem.height) } @objc public convenience init(text: String) { self.init(frame: .zero) self.setTitle(text, for: .normal) } @objc public convenience init(image: UIImage) { self.init(frame: .zero) self.imaged(image) } public convenience init(underlinedText: String) { self.init(frame: .zero) self.textUnderlined(underlinedText) self.colored(K.Color.Text.normal).smaller() } @discardableResult public convenience init(name: FontAwesome, options: NSDictionary = NSDictionary(), inset: CGFloat = 0) { self.init(frame: .zero) let color = options.value(forKey: "color") != nil ? options.value(forKey: "color") as! UIColor : K.Color.button let size = options.value(forKey: "size") != nil ? options.value(forKey: "size") as! CGFloat : K.BarButtonItem.size setTitle(name.rawValue.split().first, for: .normal) setTitleColor(color, for: .normal) setTitleColor(UIColor.red, for: .selected) setTitleColor(UIColor.lightGray, for: .disabled) titleLabel?.font = UIFont.fontAwesome(ofSize: size) // titleLabel?.minimumScaleFactor = 0.5 // titleLabel?.numberOfLines = 0 // titleLabel?.adjustsFontSizeToFitWidth = true // sizeToFit() // titleLabel?.baselineAdjustment = .alignCenters // self.imaged(getIcon(name, options: options, inset: inset)) } @discardableResult public func imaged(_ image: UIImage) -> UIButton { setImage(image, for: .normal) setImage(image, for: .selected) setImage(image, for: .focused) setImage(image, for: .highlighted) return self } @discardableResult public func clicked() -> UIButton { self.sendActions(for: .touchUpInside) return self } @discardableResult public func sized(_ size: CGFloat) -> UIButton { titleLabel?.font = UIFont(name: (titleLabel?.font?.fontName)!, size: size) return self } @discardableResult public func colored(_ color: UIColor) -> UIButton { self.setTitleColor(color, for: .normal) return self } @discardableResult override open func backgroundColored(_ color: UIColor?) -> UIButton { backgroundColor = color return self } @discardableResult public func larger(_ n: CGFloat = 1) -> UIButton { smaller(-1 * n) return self } @discardableResult public func smaller(_ n: CGFloat = 1) -> UIButton { self.titleLabel?.font = UIFont(name: (self.titleLabel?.font.fontName)!, size: (self.titleLabel?.font?.pointSize)! - n) return self } @discardableResult public func lighter(_ diff: CGFloat = 0.2) -> UIButton { titleLabel?.lighter(diff) return self } @discardableResult public func darker(_ diff: CGFloat = 0.2) -> UIButton { titleLabel?.darker(diff) return self } @discardableResult public func styled(_ text: String = Lorem.name(), options: NSDictionary = NSDictionary()) -> UIButton { let fontSize = options["fontSize"] as? CGFloat ?? options["size"] as? CGFloat ?? K.Size.Submit.size let backgroundColor = options["backgroundColor"] as? UIColor ?? UIColor.clear let color: UIColor = options["color"] as? UIColor ?? K.Color.button self.backgroundColor = backgroundColor setTitleColor(color, for: .normal) setTitle(self.titleLabel?.text ?? text, for: UIControlState.normal) titleLabel!.font = UIFont.systemFont(ofSize: fontSize) return self } @discardableResult public func texted() -> String { return (titleLabel?.text)! } @discardableResult public func darkered(_ n: CGFloat = 0.2) -> UIButton { setTitleColor(currentTitleColor.darker(n), for: .normal) return self } @discardableResult public func buttonWidth() -> CGFloat { return textWidth() * 1.5 } @discardableResult public func buttonHeight() -> CGFloat { return textHeight() * 2 } @discardableResult public func buttonSize() -> (CGFloat, CGFloat) { return (buttonWidth(), buttonHeight()) } @discardableResult public func texted(_ text: String?, options: NSDictionary = NSDictionary()) -> UIButton { // titleLabel!.text = text setTitle(text, for: .normal) // setAttributedTitle(NSAttributedString(string: text), for: .normal) return self //styled(text, options: options) } @discardableResult public func styledAsSubmit(_ options: NSDictionary = NSDictionary()) -> UIButton { backgroundColor = K.Color.submitBg setTitleColor(K.Color.submit, for: .normal) titleLabel!.font = UIFont.systemFont(ofSize: options["size"] as? CGFloat ?? K.Size.Submit.size) bordered(1, color: K.Color.submit.cgColor) radiused(4) return self } @discardableResult public func styledAsSubButton(_ options: NSDictionary = NSDictionary()) -> UIButton { backgroundColor = UIColor.white bordered(1, color: K.Color.buttonBg.cgColor) setTitleColor(K.Color.buttonBg, for: .normal) titleLabel!.font = UIFont.systemFont(ofSize: options["size"] as? CGFloat ?? K.Size.Submit.size) radiused(4) return self } @discardableResult public func styledAsInfo(_ options: NSDictionary = NSDictionary()) -> UIButton { // styledAsSubmit() backgroundColored(UIColor.white) setTitleColor(K.Color.Segment.active, for: .normal) titleLabel!.font = UIFont.systemFont(ofSize: options["size"] as? CGFloat ?? K.Size.Submit.size) radiused(4).bordered(0, color: K.Color.Segment.active.cgColor) return self } @discardableResult public func disabled() -> UIButton { backgroundColor = UIColor.lightGray isUserInteractionEnabled = false return self } @discardableResult public func textHeight() -> CGFloat { return titleLabel!.font.pointSize } @discardableResult public func textWidth() -> CGFloat { return titleLabel!.intrinsicContentSize.width } @objc public func tapped() { sendActions(for: .touchUpInside) } @objc @discardableResult public func whenTapped(_ handler: @escaping () -> Void) -> UIButton { handleControlEvent(event: .touchUpInside, handler: delayedEvent(handler)) return self } @discardableResult public func delayedEvent(_ handler: @escaping () -> ()) -> () -> () { asFadable() let handlerWithDelayed = { self.isUserInteractionEnabled = false let color = self.currentTitleColor self.setTitleColor(color.isLight() ? color.darker() : color.lighter(), for: .normal) delayedJob{ self.isUserInteractionEnabled = true self.setTitleColor(color, for: .normal) } handler() } return handlerWithDelayed } @discardableResult public func imageFromText(_ drawText: NSString, color: UIColor = K.Color.button) -> UIButton { let button = UIButton(type: .custom) // let title = "\(G.Icons.comment) 留言板" button.texted(drawText as String).colored(K.BarButtonItem.color).sizeToFit() // button.titleLabel!.font = UIFont(name: K.Font.icon, size: K.BarButtonItem.size) return button } @discardableResult public func imageFromText____(_ drawText: NSString, color: UIColor = K.Color.button) -> UIButton { let s = height * 0.5 let textColor: UIColor = color let textFont: UIFont = UIFont(name: K.Font.icon, size: s)! let size = CGSize(width: s, height: s) UIGraphicsBeginImageContext(size) let textFontAttributes = [ NSAttributedStringKey.font: textFont, NSAttributedStringKey.foregroundColor: textColor, ] let image = UIImage() let rect = CGRect(x: 0, y: 0, width: width, height: height) image.draw(in: rect) drawText.draw(in: rect, withAttributes: textFontAttributes) if UIGraphicsGetImageFromCurrentImageContext() != nil { let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() setImage(newImage, for: .normal) } return self } }
mit
66df492414fcd9a3e8f5927e7e7ee845
34.224265
155
0.69283
4.241257
false
false
false
false
coach-plus/ios
Pods/NibDesignable/NibDesignable.swift
1
5510
// // NibDesignable.swift // // Copyright (c) 2014 Morten Bøgh // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public protocol NibDesignableProtocol: NSObjectProtocol { /** Called to load the nib in setupNib(). - returns: UIView instance loaded from a nib file. */ func loadNib() -> UIView /** Called in the default implementation of loadNib(). Default is class name. - returns: Name of a single view nib file. */ func nibName() -> String } extension NibDesignableProtocol { // MARK: - Nib loading /** Called to load the nib in setupNib(). - returns: UIView instance loaded from a nib file. */ public func loadNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: self.nibName(), bundle: bundle) return nib.instantiate(withOwner: self, options: nil)[0] as! UIView // swiftlint:disable:this force_cast } // MARK: - Nib loading /** Called in init(frame:) and init(aDecoder:) to load the nib and add it as a subview. - parameter container: a view that will become the superview of the contents loaded from the Nib */ fileprivate func setupNib(in container: UIView) { let view = self.loadNib() container.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let bindings = ["view": view] container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options:[], metrics:nil, views: bindings)) container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options:[], metrics:nil, views: bindings)) } } extension UIView { /** Called in the default implementation of loadNib(). Default is class name. - returns: Name of a single view nib file. */ open func nibName() -> String { return type(of: self).description().components(separatedBy: ".").last! } } @IBDesignable open class NibDesignable: UIView, NibDesignableProtocol { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib(in: self) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self) } } @IBDesignable open class NibDesignableTableViewCell: UITableViewCell, NibDesignableProtocol { // MARK: - Initializer override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setupNib(in: self.contentView) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self.contentView) } } @IBDesignable open class NibDesignableTableViewHeaderFooterView: UITableViewHeaderFooterView, NibDesignableProtocol { // MARK: - Initializer override public init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.setupNib(in: self) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self) } } @IBDesignable open class NibDesignableControl: UIControl, NibDesignableProtocol { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib(in: self) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self) } } @IBDesignable open class NibDesignableCollectionReusableView: UICollectionReusableView, NibDesignableProtocol { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib(in: self) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self) } } @IBDesignable open class NibDesignableCollectionViewCell: UICollectionViewCell, NibDesignableProtocol { // MARK: - Initializer override public init(frame: CGRect) { super.init(frame: frame) self.setupNib(in: self.contentView) } // MARK: - NSCoding required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNib(in: self.contentView) } }
mit
89f84667d29564ab3d240f90561492a0
29.776536
138
0.685061
4.471591
false
false
false
false
aipeople/PokeIV
Pods/PGoApi/PGoApi/Classes/Unknown6/subFuncD.swift
1
34464
// // subFuncA.swift // Pods // // Created by PokemonGoSucks on 2016-08-10 // // import Foundation public class subFuncD { public func subFuncD(input_: Array<UInt32>) -> Array<UInt32> { var v = Array<UInt32>(count: 545, repeatedValue: 0) var input = input_ v[0] = input[33] v[1] = input[3] let part0 = ((input[130] | input[32])) v[2] = (((part0 ^ input[108]) ^ input[122]) ^ input[41]) v[3] = (v[2] ^ input[33]) v[4] = (v[3] & input[3]) v[5] = (v[2] & v[0]) let part1 = ((input[130] | input[32])) v[6] = (((part1 ^ input[108]) ^ input[122]) ^ input[41]) v[7] = ~v[2] v[8] = (v[7] & v[1]) v[9] = ((v[7] & v[0]) & v[1]) v[10] = v[8] v[11] = (v[6] & ~input[33]) v[12] = (v[6] ^ v[8]) v[13] = (v[6] | input[33]) v[14] = input[13] v[15] = (v[5] & input[3]) v[16] = ~input[25] v[17] = (v[11] ^ input[3]) v[18] = input[25] let part2 = ((v[4] ^ v[5])) v[19] = (part2 & v[16]) v[20] = (v[12] | v[18]) v[21] = ((input[3] & ~v[3]) ^ v[13]) let part3 = ((v[4] ^ v[5])) v[22] = (part3 & v[18]) v[23] = ((v[4] ^ v[5]) | v[18]) v[24] = ((input[37] ^ input[75]) ^ (input[117] & ~input[32])) v[25] = input[33] input[37] = v[24] v[26] = v[24] v[27] = (v[15] | input[25]) input[41] = v[6] input[103] = ((v[4] ^ v[5]) ^ v[19]) v[28] = (v[21] ^ v[22]) input[172] = ((v[9] ^ v[6]) ^ v[20]) v[29] = ((v[10] ^ v[25]) ^ v[27]) v[30] = ((v[15] ^ v[11]) ^ (v[17] & v[16])) v[31] = input[164] v[32] = ~v[24] v[33] = (~v[24] & v[14]) input[161] = (v[21] ^ v[23]) v[34] = (v[14] & ~v[33]) v[35] = (v[24] & v[14]) v[36] = v[31] input[164] = v[28] v[37] = (v[24] ^ v[14]) input[108] = (v[24] & ~v[14]) v[38] = (v[24] | v[14]) v[39] = input[3] input[75] = v[35] v[40] = v[30] v[41] = (v[39] ^ input[27]) v[42] = (v[4] ^ v[6]) v[43] = (input[186] ^ input[104]) v[44] = input[90] v[45] = input[149] input[90] = v[37] v[46] = (v[45] ^ v[44]) v[47] = input[185] v[48] = (input[25] & ~v[12]) let part4 = ((input[27] | input[59])) v[49] = (v[46] ^ part4) v[50] = input[81] v[51] = ~input[61] input[120] = v[29] input[78] = v[38] input[97] = v[40] v[52] = (v[49] & input[43]) v[53] = (v[10] ^ v[47]) v[54] = (v[48] ^ v[42]) v[55] = (((v[50] & input[7]) ^ input[131]) | input[45]) v[56] = input[84] v[57] = (v[42] & v[16]) v[58] = (input[32] | input[112]) v[59] = (input[76] ^ input[1]) v[60] = input[32] input[74] = v[38] v[61] = (v[32] & input[61]) let part5 = ((v[60] | v[56])) v[62] = (v[59] ^ part5) let part6 = ((input[165] | input[32])) v[63] = ((input[19] ^ input[125]) ^ part6) v[64] = ((v[58] ^ input[141]) ^ input[15]) let part7 = ((v[55] ^ input[93])) v[65] = ((input[4] ^ input[166]) ^ (input[29] & ~part7)) let part8 = ((input[165] | input[32])) v[66] = ((input[19] ^ input[125]) ^ part8) v[67] = input[9] v[68] = input[55] v[69] = input[170] v[70] = v[64] input[15] = v[64] v[71] = input[159] input[140] = v[34] input[168] = v[33] input[1] = v[62] input[19] = v[66] v[72] = (v[62] | v[67]) v[73] = input[115] v[74] = (v[65] & ~v[69]) v[75] = (v[62] & v[68]) v[76] = (v[74] ^ v[71]) v[77] = v[65] v[78] = (v[62] | v[68]) v[79] = ((input[169] & v[65]) ^ input[144]) v[80] = ((input[176] & v[65]) ^ v[73]) v[81] = ((input[39] & v[65]) ^ input[135]) v[83] = ((v[65] & ~input[137]) ^ v[73]) v[82] = v[83] v[84] = input[96] v[85] = ((v[65] & ~input[139]) ^ input[124]) let part9 = (((v[83] & v[84]) ^ v[85])) v[86] = (input[12] & ~part9) v[87] = v[85] v[88] = input[12] v[89] = input[178] v[90] = (((input[35] ^ v[76]) ^ (v[84] & ~v[81])) ^ v[86]) v[91] = input[171] v[92] = (~v[90] & input[3]) v[93] = (~v[90] & input[155]) v[94] = ~v[90] v[95] = (~v[90] & input[27]) v[96] = (((input[35] ^ v[76]) ^ (v[84] & ~v[81])) ^ v[86]) v[97] = ((input[6] ^ v[36]) ^ v[52]) v[98] = input[121] v[99] = (v[92] ^ v[41]) v[100] = (v[96] | input[155]) v[101] = (v[96] | v[89]) v[102] = ~input[11] let part10 = ((v[90] | input[3])) v[103] = (part10 ^ input[27]) let part11 = (((v[95] ^ input[3]) | input[11])) v[104] = ((v[100] ^ v[89]) ^ part11) v[105] = (v[96] & ~input[71]) v[106] = (input[56] ^ input[70]) v[107] = input[46] v[108] = (v[96] & ~input[88]) let part12 = (((v[93] ^ v[89]) | input[11])) input[171] = ((v[100] ^ v[91]) ^ part12) v[109] = v[107] v[110] = input[177] input[71] = v[104] v[111] = (v[109] ^ v[110]) v[112] = (v[97] ^ (v[96] & ~v[43])) input[6] = v[112] v[113] = input[58] let part13 = ((v[92] ^ v[41])) v[114] = ((part13 & v[102]) ^ v[103]) input[159] = v[114] let part14 = ((v[96] | v[41])) v[115] = (part14 ^ v[91]) v[116] = input[34] v[117] = v[115] input[58] = v[115] input[34] = (v[116] ^ v[103]) v[118] = (v[106] ^ v[108]) input[56] = (v[106] ^ v[108]) v[119] = (v[111] ^ v[105]) input[46] = (v[111] ^ v[105]) v[120] = ((v[98] ^ v[101]) ^ (v[92] & v[102])) input[115] = v[120] v[121] = (v[74] ^ v[113]) v[122] = input[96] v[123] = ~v[122] v[124] = input[73] v[125] = (v[62] ^ input[55]) v[126] = (~v[62] & input[55]) v[127] = ~v[75] v[128] = input[17] v[129] = ((v[77] & ~input[86]) ^ input[157]) let part15 = ((v[79] | v[122])) let part16 = ((part15 ^ v[121])) v[130] = ((((v[129] & ~v[122]) ^ input[63]) ^ v[80]) ^ (part16 & v[88])) v[131] = (v[130] & ~v[67]) v[132] = (v[130] & ~v[62]) v[133] = (v[130] ^ v[67]) let part17 = ((v[79] | v[122])) let part18 = ((part17 ^ v[121])) v[134] = ((((v[129] & ~v[122]) ^ input[63]) ^ v[80]) ^ (part18 & v[88])) v[135] = ((v[130] & ~v[62]) ^ v[130]) v[136] = (~v[130] & v[67]) v[137] = (v[130] & v[67]) v[138] = (v[136] & ~v[62]) let part19 = (((v[130] | v[62]) | v[128])) v[139] = (part19 ^ v[136]) v[140] = ~v[130] v[141] = (v[135] & ~v[128]) let part20 = ((v[130] | v[62])) let part21 = ((((v[130] & v[67]) ^ part20) | v[128])) v[142] = (part21 ^ v[138]) v[143] = (((v[130] ^ v[67]) ^ input[30]) ^ v[138]) v[144] = (v[130] & ~v[131]) v[145] = (v[130] | v[67]) v[146] = (v[131] & ~v[62]) v[147] = ((v[130] ^ v[67]) | v[62]) v[148] = (v[136] | v[62]) v[149] = (((v[141] ^ v[144]) ^ v[147]) ^ (input[25] & ~v[142])) let part22 = ((v[130] | v[62])) v[150] = (part22 ^ v[130]) v[151] = ((v[130] & ~v[62]) ^ v[136]) v[152] = (v[147] ^ v[145]) let part23 = ((v[135] | v[128])) v[153] = (v[143] ^ part23) let part24 = ((v[139] ^ (v[131] & ~v[62]))) v[154] = (part24 & input[25]) v[155] = (v[150] | v[128]) v[156] = ((v[133] & ~v[62]) ^ v[131]) v[157] = (v[137] ^ input[26]) v[158] = (v[150] & ~v[128]) v[159] = v[131] let part25 = ((v[144] | v[128])) v[160] = (part25 ^ v[72]) let part26 = ((v[136] | v[62])) v[161] = ((part26 ^ v[141]) ^ v[136]) v[162] = (v[131] ^ v[88]) v[163] = ((v[130] & ~v[62]) ^ v[136]) v[164] = (v[163] | v[128]) v[165] = (v[163] & ~v[128]) v[166] = (v[155] ^ v[163]) v[167] = (v[62] | v[145]) let part27 = (((v[145] ^ (v[130] & ~v[62])) | v[128])) v[168] = (part27 ^ v[152]) v[169] = ((v[162] ^ v[148]) ^ v[165]) let part28 = ((v[159] | v[62])) v[170] = (v[157] ^ part28) v[171] = (v[165] ^ v[144]) v[172] = v[170] v[173] = v[164] v[174] = ((v[153] ^ v[154]) ^ (v[149] & input[33])) v[175] = input[25] let part29 = (((v[152] ^ v[158]) ^ (input[25] & v[161]))) let part30 = ((v[173] ^ v[151])) v[176] = ((v[169] ^ (v[175] & ~part30)) ^ (input[33] & ~part29)) v[177] = (~v[75] & v[62]) v[178] = ~input[55] v[179] = (v[62] & v[178]) v[180] = (v[92] ^ input[155]) let part31 = (((input[25] & ~v[168]) ^ v[146])) v[181] = ((((v[175] & ~v[171]) ^ (v[167] & ~v[128])) ^ v[172]) ^ (input[33] & ~part31)) v[182] = (v[96] & ~input[100]) let part32 = ((v[128] | ~v[144])) v[183] = ((v[166] ^ input[40]) ^ (part32 & input[25])) let part33 = ((((input[25] & ~v[160]) ^ v[156]) ^ v[141])) v[184] = (part33 & input[33]) v[185] = (v[134] & ~v[78]) v[186] = (~v[75] & v[134]) v[187] = (input[20] ^ input[150]) input[100] = (input[11] & v[180]) v[188] = (v[187] ^ v[182]) input[20] = (v[187] ^ v[182]) input[30] = v[174] input[149] = (v[174] | v[119]) let part34 = ((v[174] | v[119])) input[135] = (~v[174] & part34) input[88] = (~v[174] & v[119]) let part35 = ((v[174] & v[119])) input[39] = (v[174] & ~part35) input[40] = (v[184] ^ v[183]) v[189] = input[53] input[104] = (v[174] & v[119]) input[137] = (v[174] ^ v[119]) v[190] = ((v[134] & v[75]) ^ v[78]) input[157] = (v[174] & ~v[119]) v[191] = (v[134] ^ v[125]) v[192] = ((v[134] & v[126]) ^ v[75]) v[193] = v[176] input[12] = v[176] input[169] = (v[134] ^ v[125]) v[194] = input[55] v[195] = v[181] input[186] = v[181] input[73] = v[192] v[196] = ((v[125] & v[134]) ^ v[194]) input[141] = v[196] v[197] = ((v[134] & ~v[177]) ^ v[62]) v[198] = v[77] input[110] = v[197] v[199] = (v[186] ^ v[75]) v[200] = (v[77] | input[96]) v[201] = ((v[134] & ~v[78]) ^ v[78]) input[131] = v[201] v[202] = ((v[134] & v[178]) ^ v[62]) v[203] = (v[132] ^ v[78]) input[121] = (v[132] ^ v[78]) v[204] = (((v[62] & v[178]) & v[134]) ^ v[62]) input[165] = v[199] input[125] = v[202] v[205] = input[96] v[206] = input[160] v[207] = v[205] v[208] = (v[205] & ~v[79]) v[209] = (v[207] & ~v[129]) input[111] = v[204] input[76] = v[190] v[210] = (v[80] ^ v[189]) let part36 = ((v[208] ^ v[121])) v[211] = (v[88] & ~part36) v[212] = (v[77] ^ v[206]) v[213] = (v[77] & ~v[206]) let part37 = ((v[198] & ~v[206])) v[214] = (v[198] & ~part37) let part38 = ((input[96] | (v[77] ^ v[206]))) v[215] = ((part38 ^ input[142]) ^ v[214]) v[216] = (v[206] & ~v[77]) input[4] = (v[77] | v[206]) v[217] = ((v[206] & ~v[77]) | input[96]) v[218] = (v[200] ^ (v[77] & ~v[206])) v[219] = (v[214] ^ (v[77] & v[123])) v[220] = ((v[77] & v[206]) & v[123]) let part39 = ((v[198] & ~v[206])) v[221] = (v[198] & ~part39) v[222] = (v[77] & v[206]) let part40 = ((v[198] ^ v[217])) let part41 = ((((v[215] & input[50]) ^ v[219]) ^ (input[42] & ~part40))) let part42 = ((v[200] ^ (v[198] & ~v[206]))) let part43 = ((((part42 & input[42]) ^ (v[198] & v[206])) ^ v[200])) let part44 = ((v[220] ^ v[206])) let part45 = ((v[198] & ~v[206])) let part46 = ((input[96] | (v[198] & ~part45))) v[223] = (((((input[4] ^ input[7]) ^ part46) ^ (input[42] & ~part44)) ^ (input[50] & ~part43)) ^ (input[26] & ~part41)) v[224] = ~input[153] v[225] = (v[223] & v[224]) v[226] = (v[223] & input[153]) v[227] = input[91] v[228] = (v[223] & input[148]) v[229] = (v[228] ^ input[23]) v[230] = (v[228] | input[31]) let part47 = ((v[225] | ~input[31])) let part48 = ((((input[167] & v[223]) ^ input[92]) ^ ((input[31] & v[70]) & v[226]))) let part49 = (((v[225] ^ input[77]) | input[31])) v[231] = (((((v[227] ^ input[28]) ^ v[226]) ^ part49) ^ (part48 & v[51])) ^ (part47 & v[70])) v[232] = (v[223] ^ input[153]) let part50 = (((input[153] ^ v[225]) | input[31])) let part51 = ((input[77] ^ part50)) let part52 = ((v[229] | input[31])) v[233] = (((v[226] ^ input[77]) ^ part52) ^ (v[70] & ~part51)) let part53 = ((v[226] | input[31])) let part54 = (((v[223] & ~input[23]) ^ part53)) v[234] = (((input[23] ^ (v[223] & ~input[23])) ^ v[230]) ^ (v[70] & ~part54)) let part55 = ((v[200] ^ input[4])) v[235] = (part55 & input[42]) let part56 = (((v[77] & v[123]) ^ v[206])) v[236] = ((input[42] & input[50]) & part56) v[237] = (v[226] ^ (input[31] & ~v[226])) v[238] = input[173] v[239] = ~input[31] let part57 = (((input[77] ^ input[83]) ^ (input[107] & v[223]))) v[240] = ((((v[227] ^ input[54]) ^ v[225]) ^ v[230]) ^ (v[70] & ~part57)) v[241] = (((v[232] ^ input[32]) ^ (v[229] & v[239])) ^ (v[237] & v[70])) v[242] = (v[223] & v[51]) v[243] = (v[210] ^ v[209]) v[244] = (v[233] | input[61]) v[245] = (v[234] & v[51]) v[246] = (v[223] | input[61]) v[247] = (v[243] ^ v[211]) v[248] = input[26] input[7] = v[223] let part58 = ((v[236] ^ v[235])) v[249] = (v[248] & ~part58) input[28] = v[231] v[250] = input[4] v[251] = (~v[223] & v[238]) input[85] = v[221] input[114] = v[250] input[123] = v[249] input[91] = (v[112] & v[231]) input[147] = v[212] v[252] = (v[221] ^ input[163]) v[253] = (~v[223] & input[61]) v[254] = v[231] input[174] = v[216] input[54] = (v[240] ^ v[244]) v[255] = input[96] let part59 = ((v[112] & v[231])) input[99] = (v[112] & ~part59) input[181] = (v[222] ^ v[255]) v[256] = (v[241] ^ v[245]) v[257] = (v[223] ^ input[61]) input[163] = v[252] v[258] = (v[246] & ~v[223]) v[259] = (v[253] ^ (v[242] & v[238])) v[260] = ((v[223] & ~input[64]) ^ input[148]) v[261] = (v[223] & input[61]) v[262] = v[256] input[32] = v[256] v[263] = input[16] v[264] = (v[231] ^ v[112]) input[92] = (v[231] ^ v[112]) v[265] = v[247] v[266] = (v[258] ^ v[77]) v[267] = (v[223] ^ v[263]) let part60 = ((((v[223] & v[238]) & v[32]) ^ v[259])) v[268] = ((part60 & v[247]) ^ v[257]) let part61 = (((v[223] & ~v[227]) ^ input[153])) v[269] = (part61 & v[239]) v[270] = (v[223] & input[77]) v[271] = (v[260] | input[31]) v[272] = ((v[232] & v[239]) ^ v[225]) v[273] = ((v[261] & v[238]) ^ v[61]) v[274] = ((v[261] & v[238]) ^ v[261]) v[275] = ((v[257] ^ input[22]) ^ v[251]) v[276] = (v[247] & ~v[273]) v[277] = (v[223] & ~v[261]) v[278] = (v[272] & v[70]) v[279] = ((v[251] ^ v[261]) | v[26]) v[280] = (v[219] & input[42]) let part62 = ((v[261] ^ (v[223] & v[238]))) v[281] = (part62 & v[32]) v[282] = (v[257] & v[238]) v[283] = (v[220] ^ v[222]) let part63 = (((v[212] & v[123]) ^ v[222])) v[284] = (part63 & input[42]) v[285] = (input[42] & ~v[218]) v[286] = (v[217] ^ input[4]) v[287] = v[216] v[288] = ((v[213] & v[123]) ^ v[216]) v[289] = (((input[42] & v[222]) ^ input[4]) ^ (v[287] & v[123])) let part64 = (((v[220] ^ v[213]) ^ v[280])) v[290] = (part64 & input[50]) v[291] = ((v[287] & v[123]) ^ v[212]) v[292] = v[284] input[127] = v[291] v[293] = v[265] v[294] = (v[280] ^ input[136]) v[295] = ((v[238] & ~v[258]) ^ v[257]) v[296] = (((v[257] & v[238]) ^ v[257]) ^ v[281]) v[297] = ((v[258] ^ v[282]) | v[26]) let part65 = ((v[295] | v[26])) v[298] = (v[268] ^ part65) v[299] = (input[50] & ~v[289]) let part66 = ((v[221] ^ v[217])) v[300] = (part66 & input[42]) v[301] = input[107] v[302] = (v[288] ^ v[285]) v[303] = (((v[223] & ~input[72]) ^ v[301]) ^ v[271]) v[304] = (((v[301] ^ input[50]) ^ v[270]) ^ v[269]) let part67 = ((v[223] & v[239])) v[305] = (v[70] & ~part67) v[306] = input[102] let part68 = (((v[251] ^ v[223]) ^ v[279])) let part69 = ((v[296] ^ (part68 & v[265]))) let part70 = ((v[277] | v[26])) let part71 = ((((v[242] & v[238]) ^ v[242]) ^ part70)) let part72 = (((v[277] ^ v[238]) | v[26])) v[307] = ((((part72 ^ v[266]) ^ (v[238] & ~v[277])) ^ (v[265] & ~part71)) ^ (v[306] & ~part69)) let part73 = (((v[223] & v[238]) ^ input[61])) let part74 = (((((v[265] & v[26]) & part73) ^ (v[223] & v[238])) ^ (v[274] & v[26]))) let part75 = ((v[274] | v[26])) v[308] = (((((part75 ^ v[277]) ^ v[238]) ^ input[2]) ^ v[276]) ^ (v[306] & ~part74)) let part76 = (((v[223] ^ v[238]) | v[26])) let part77 = ((part76 ^ v[259])) v[309] = (((((v[246] & v[238]) ^ v[267]) ^ v[297]) ^ (part77 & v[265])) ^ (v[298] & v[306])) let part78 = ((v[246] | v[26])) let part79 = (((part78 ^ v[251]) ^ ((v[238] & v[265]) & ~v[246]))) let part80 = (((v[246] & ~v[223]) | v[26])) let part81 = ((v[246] ^ (v[223] & v[238]))) v[310] = ((((part81 & v[32]) ^ v[275]) ^ (part80 & v[265])) ^ (part79 & v[306])) input[22] = v[310] v[311] = (~v[254] & v[193]) let part82 = (((v[278] ^ v[303]) | input[61])) v[312] = ((v[304] ^ v[305]) ^ part82) v[313] = v[307] v[314] = (v[307] & ~v[311]) let part83 = ((input[4] & v[123])) v[315] = (input[42] & ~part83) v[316] = (v[307] & v[195]) input[167] = (v[254] & ~v[112]) input[133] = (v[310] & v[174]) input[106] = v[312] input[182] = (v[174] & ~v[310]) input[2] = v[308] let part84 = ((v[254] | v[112])) v[317] = (part84 & ~v[112]) let part85 = ((v[308] | v[118])) input[72] = (part85 ^ v[118]) v[318] = (v[310] ^ v[174]) v[319] = (v[310] | v[174]) let part86 = ((v[309] | v[262])) input[116] = (part86 ^ v[309]) input[107] = (~v[308] & v[118]) input[66] = (v[254] | v[112]) v[320] = v[318] input[16] = v[309] input[113] = v[307] input[152] = (v[308] | v[118]) v[321] = (~v[308] & v[195]) input[129] = v[317] input[148] = (~v[254] & v[112]) v[322] = (v[314] ^ v[193]) v[323] = input[95] input[162] = v[318] input[191] = (v[307] ^ v[195]) input[117] = v[321] v[324] = (v[291] ^ v[323]) input[190] = (v[308] | v[195]) input[198] = (v[307] & v[195]) input[77] = (v[307] | v[195]) v[325] = input[50] v[326] = (v[314] ^ v[193]) v[327] = (v[325] & ~v[294]) input[184] = v[319] input[132] = v[319] v[328] = (~v[313] & v[195]) input[118] = v[326] input[199] = (v[313] & ~v[316]) input[187] = (v[300] ^ v[252]) input[201] = v[328] v[329] = input[26] input[95] = v[286] let part87 = (((v[283] ^ v[315]) ^ v[290])) v[330] = (part87 & v[329]) let part88 = ((v[324] ^ v[299])) v[331] = (part88 & v[329]) v[332] = ((v[325] & ~v[302]) ^ input[187]) v[333] = v[6] v[334] = ((input[57] ^ v[292]) ^ v[286]) v[335] = input[3] input[128] = v[332] v[336] = (~v[62] & v[78]) v[337] = ((v[334] ^ v[327]) ^ v[330]) v[338] = (~v[11] & v[6]) v[339] = (v[11] & input[3]) v[340] = (v[134] & v[62]) v[341] = ((v[335] & ~v[13]) ^ v[13]) v[342] = ((~v[11] & input[3]) ^ v[11]) v[343] = ((input[47] ^ v[331]) ^ input[128]) v[344] = (v[134] & ~v[336]) v[345] = ((v[338] ^ (v[333] & v[335])) ^ (v[341] & v[16])) v[346] = (v[132] ^ v[75]) v[347] = (v[344] ^ v[78]) v[348] = ((v[336] ^ (v[134] & v[62])) | v[343]) let part89 = ((v[342] | input[25])) let part90 = ((((v[333] & v[335]) ^ v[333]) ^ v[57])) v[349] = (((~v[337] & part90) ^ part89) ^ v[342]) let part91 = (((v[123] & v[82]) ^ v[87])) v[350] = (((v[76] ^ input[49]) ^ (v[81] & v[123])) ^ (v[88] & ~part91)) v[351] = (v[62] ^ (v[134] & v[62])) v[352] = (v[343] & ~v[347]) v[353] = (input[3] & ~v[338]) v[354] = (v[348] ^ v[347]) v[355] = ((v[343] & v[126]) ^ v[197]) v[356] = (v[125] ^ input[60]) v[357] = (v[343] & ~v[351]) v[358] = (v[134] & input[55]) v[359] = (v[185] ^ v[343]) v[360] = (v[185] ^ v[177]) v[361] = (v[343] & ~v[346]) v[362] = (v[346] & v[343]) v[363] = (v[337] | ((v[333] ^ v[339]) ^ v[19])) v[364] = (v[345] ^ input[18]) v[365] = (v[340] ^ v[179]) v[366] = ((v[179] & v[134]) ^ input[55]) v[367] = (v[344] ^ input[55]) v[368] = (v[353] ^ v[11]) input[86] = ((v[343] & v[140]) ^ v[190]) v[369] = (v[352] ^ v[202]) v[370] = (v[357] ^ v[199]) v[371] = input[31] input[177] = v[370] v[372] = (v[354] | v[371]) v[373] = (v[356] ^ v[186]) v[374] = (v[343] & v[358]) v[375] = (v[359] & v[239]) v[376] = (v[343] & v[365]) input[150] = (v[361] ^ v[201]) v[377] = (v[364] ^ v[363]) v[378] = (v[343] & ~v[126]) v[379] = (v[358] ^ v[177]) let part92 = ((v[134] ^ v[126])) input[144] = ((v[343] & part92) ^ v[196]) v[380] = (v[343] & ~v[367]) v[381] = (v[368] | input[25]) v[382] = (input[86] ^ input[8]) v[383] = ((v[355] & v[239]) ^ input[177]) v[384] = (v[369] | input[31]) v[385] = input[31] v[386] = ((v[343] & ~v[360]) | v[385]) v[387] = ((v[366] & ~v[343]) | v[385]) v[388] = (input[150] ^ v[375]) v[389] = ((v[362] ^ v[192]) | v[385]) v[390] = (v[353] ^ v[5]) v[391] = (v[16] & v[353]) let part93 = ((v[349] | v[350])) v[392] = (v[377] ^ part93) input[176] = (v[376] ^ v[203]) input[179] = (v[378] ^ v[191]) v[393] = (v[372] ^ input[144]) v[394] = ((v[379] ^ input[96]) ^ (v[343] & v[127])) v[395] = (v[382] ^ v[384]) v[396] = (input[153] | v[383]) v[397] = v[395] v[398] = ((v[373] ^ v[374]) ^ v[386]) v[399] = (v[337] | input[69]) v[400] = (v[389] ^ input[176]) input[156] = (v[387] ^ input[179]) v[401] = ((v[399] ^ v[391]) ^ v[390]) v[402] = v[397] v[403] = (v[398] ^ (v[388] & v[224])) v[404] = (v[396] ^ v[402]) let part94 = ((v[204] ^ v[380])) v[405] = (v[394] ^ (part94 & v[239])) let part95 = ((v[195] & v[392])) v[406] = (v[195] & ~part95) v[407] = (v[235] ^ input[4]) v[408] = (v[400] | input[153]) v[409] = ((v[393] & v[224]) ^ input[156]) v[410] = ((v[94] & v[98]) ^ input[27]) v[411] = (input[11] & ~v[103]) input[68] = (v[309] | v[404]) v[412] = (input[27] ^ v[95]) let part96 = (((v[338] ^ v[339]) ^ v[381])) input[183] = ((~v[337] & part96) ^ v[29]) input[57] = v[337] input[82] = (v[262] | v[404]) v[413] = (v[174] & ~v[403]) input[47] = v[343] v[414] = (v[407] & input[50]) input[8] = v[404] v[415] = (v[195] & ~v[392]) v[416] = (v[409] ^ input[10]) input[93] = v[413] let part97 = ((v[195] & v[392])) let part98 = ((v[308] | (v[195] & v[392]))) v[417] = (part98 ^ (v[195] & ~part97)) input[65] = v[414] input[60] = v[403] v[418] = input[80] input[69] = (v[401] | v[350]) v[419] = (v[405] ^ v[408]) input[112] = (v[320] | v[403]) v[420] = (v[93] ^ v[418]) v[421] = v[418] v[422] = input[183] input[18] = v[392] let part99 = ((v[337] | v[53])) let part100 = ((part99 ^ v[40])) input[185] = ((part100 & ~v[350]) ^ v[422]) input[45] = v[409] v[423] = (v[254] & ~v[193]) let part101 = ((v[254] ^ v[193])) v[424] = (v[313] & ~part101) v[425] = ((v[410] & v[102]) ^ v[100]) input[10] = v[416] let part102 = ((v[411] ^ v[412])) v[426] = (((~v[337] & part102) ^ v[411]) ^ v[99]) input[84] = (v[405] ^ v[408]) v[427] = (v[100] ^ input[155]) input[130] = v[406] input[101] = v[417] input[89] = v[415] v[428] = (v[254] & ~v[423]) v[429] = (v[114] ^ input[42]) input[36] ^= input[185] let part103 = (((v[94] & v[421]) | input[11])) v[430] = ((part103 ^ (v[94] & v[98])) ^ v[41]) v[431] = (v[313] & ~v[254]) v[432] = ((v[313] & v[254]) & v[193]) v[433] = (v[432] ^ v[428]) let part104 = ((v[424] ^ v[254])) v[434] = (((v[313] & ~v[193]) ^ (v[254] & v[193])) ^ (input[36] & ~part104)) let part105 = ((v[313] ^ v[428])) v[435] = (input[36] & ~part105) v[436] = input[36] let part106 = ((v[254] ^ v[193])) let part107 = (((v[313] & part106) ^ v[193])) v[437] = (v[436] & ~part107) let part108 = ((v[254] | v[193])) v[438] = (v[424] ^ part108) let part109 = ((v[254] | v[193])) v[439] = (v[432] ^ part109) v[440] = ((v[193] & ~v[313]) & v[436]) v[441] = ((v[313] & v[254]) ^ v[423]) v[442] = (((v[420] & v[102]) ^ v[100]) | v[337]) v[443] = (v[430] ^ input[44]) let part110 = ((v[426] | v[63])) input[166] = (((v[425] & ~v[337]) ^ v[429]) ^ part110) let part111 = ((v[195] | v[392])) input[146] = (part111 & ~v[195]) let part112 = ((v[195] ^ v[392])) v[444] = (~v[308] & part112) let part113 = ((v[313] | v[195])) v[445] = (~v[313] & part113) v[446] = (input[36] & ~v[433]) let part114 = ((v[431] ^ v[193])) v[447] = (input[36] & ~part114) v[448] = input[36] input[180] = (v[435] ^ v[254]) v[449] = ((((v[313] & ~v[428]) ^ v[254]) ^ v[193]) ^ v[440]) v[450] = (((v[313] & ~v[428]) ^ v[193]) ^ (v[439] & v[448])) v[451] = (v[441] ^ v[437]) v[452] = v[449] v[453] = (v[308] | input[146]) v[454] = (((v[313] & v[311]) ^ v[254]) ^ v[193]) let part115 = ((v[308] | v[195])) v[455] = (part115 ^ v[415]) v[456] = (v[338] ^ v[15]) v[457] = (v[412] & v[102]) let part116 = ((v[308] | v[195])) v[458] = (part116 ^ v[195]) let part117 = ((v[195] | v[392])) v[459] = (~v[308] & part117) v[460] = (~v[195] & v[313]) v[461] = (v[308] | (v[195] ^ v[392])) v[462] = ((v[195] & v[392]) ^ v[444]) v[463] = (v[195] ^ v[321]) input[193] = (v[322] ^ v[446]) v[464] = (v[454] ^ v[447]) v[465] = ((v[431] ^ v[254]) ^ (v[448] & ~v[438])) v[466] = (v[453] ^ v[415]) v[467] = (v[455] | v[118]) let part118 = (((~v[337] & v[427]) ^ v[117])) input[44] = (((part118 & ~v[63]) ^ v[443]) ^ v[442]) v[468] = ((v[101] ^ v[124]) | input[11]) v[469] = (v[124] & ~v[94]) v[470] = (input[25] & ~v[456]) v[471] = (v[457] ^ v[427]) v[472] = ~v[118] v[473] = (v[308] & ~v[118]) v[474] = (v[458] & ~v[118]) let part119 = (((~v[308] & v[392]) ^ v[415])) v[475] = (part119 & ~v[118]) v[476] = (v[415] & ~v[308]) let part120 = ((v[308] ^ v[406])) v[477] = (part120 & ~v[118]) v[478] = (input[146] ^ v[461]) input[145] = (v[461] ^ v[392]) v[479] = (v[118] | v[444]) v[480] = (v[118] | v[462]) v[481] = (v[463] & ~v[118]) v[482] = (v[452] | v[419]) v[483] = (v[452] & v[419]) v[484] = ((v[434] & v[419]) ^ input[180]) v[485] = (v[434] & ~v[419]) v[486] = (v[445] | input[166]) v[487] = ~input[166] v[488] = (v[293] ^ v[450]) v[489] = (v[450] ^ v[134]) v[490] = (v[419] & ~v[464]) v[491] = (v[464] & ~v[419]) v[492] = v[118] v[493] = (v[466] | v[118]) v[494] = (v[467] ^ v[455]) v[495] = (v[317] | input[44]) v[496] = (v[390] ^ v[470]) v[497] = (v[469] ^ v[468]) v[498] = (v[471] & ~v[337]) v[499] = (v[458] ^ v[473]) v[500] = (v[458] | v[492]) v[501] = (v[474] ^ v[308]) let part121 = ((v[195] | v[392])) v[502] = (v[321] ^ part121) v[503] = ((v[459] ^ v[406]) | v[492]) v[504] = v[492] v[505] = (v[406] | v[492]) let part122 = ((v[308] | v[392])) input[151] = (part122 ^ v[195]) v[506] = (v[476] ^ v[195]) let part123 = ((((~v[195] & v[392]) & ~v[308]) ^ (v[195] & v[392]))) v[507] = (part123 & v[472]) v[508] = (v[321] ^ (v[195] & v[392])) let part124 = ((v[308] | v[195])) input[188] = ((part124 ^ v[195]) ^ v[392]) v[509] = (v[479] ^ v[321]) let part125 = ((v[308] | v[195])) v[510] = (v[480] ^ part125) v[511] = (v[462] & v[472]) v[512] = (v[481] ^ input[145]) v[513] = input[193] input[194] = (input[193] ^ v[483]) v[514] = v[513] v[515] = input[180] input[195] = (v[514] ^ v[482]) v[516] = (v[485] ^ v[515]) v[517] = ((v[460] & v[487]) ^ v[316]) v[518] = ((v[313] ^ v[195]) | input[166]) let part126 = (((v[419] & ~v[451]) ^ v[465])) v[519] = (part126 & v[188]) let part127 = ((v[451] | v[419])) let part128 = ((part127 ^ v[465])) v[520] = (v[188] & ~part128) v[521] = (v[417] ^ v[493]) let part129 = ((v[478] ^ v[477])) v[522] = (part129 & ~v[416]) v[523] = (input[119] ^ v[99]) let part130 = ((v[337] | v[54])) v[524] = (part130 ^ v[496]) v[525] = (~v[337] & v[497]) v[526] = (v[501] & ~v[416]) v[527] = (input[151] ^ v[505]) v[528] = (v[508] ^ v[503]) v[529] = (v[502] ^ v[480]) v[530] = (v[511] ^ v[478]) v[531] = (v[512] | v[416]) let part131 = ((v[463] | v[504])) v[532] = (part131 ^ input[188]) v[533] = (input[195] ^ v[350]) v[534] = ((v[188] & ~v[484]) ^ input[194]) v[535] = (v[188] & ~v[516]) v[536] = (input[166] | (v[313] & ~v[316])) v[537] = (input[166] | v[313]) v[538] = input[166] input[98] = v[521] v[539] = (v[538] | v[195]) input[49] = (v[313] ^ v[518]) input[202] = (v[316] & v[487]) input[53] = ((v[488] ^ v[490]) ^ v[519]) input[63] = ((v[489] ^ v[491]) ^ v[520]) v[540] = ((v[494] & ~v[416]) ^ v[521]) v[541] = input[44] let part132 = ((v[264] ^ v[495])) input[170] = (part132 & ~input[36]) input[175] = v[540] input[80] = (v[541] & ~v[317]) input[158] = (v[524] | v[350]) input[178] = (v[525] ^ v[523]) v[542] = ~input[44] input[83] = ((~v[254] & v[112]) & v[542]) input[94] = (v[112] & v[542]) input[70] = (v[63] | (v[120] ^ v[498])) let part133 = ((v[499] | v[416])) input[136] = (((v[459] ^ v[392]) ^ v[500]) ^ part133) let part134 = ((v[195] & v[392])) let part135 = (((v[475] ^ (v[195] & ~part134)) | v[416])) input[26] = (v[527] ^ part135) input[138] = ((v[507] ^ v[506]) ^ v[526]) input[79] = (v[528] ^ v[522]) input[196] = (v[533] ^ v[535]) input[122] = v[529] let part136 = ((v[510] | v[416])) input[64] = (part136 ^ v[529]) let part137 = ((v[509] | v[416])) input[189] = (part137 ^ v[530]) let part138 = ((v[486] ^ v[313])) input[29] = (v[419] & ~part138) input[50] = v[530] input[35] = (v[534] ^ v[96]) input[143] = v[532] input[87] = (v[531] ^ v[532]) v[543] = input[202] v[544] = input[49] input[126] = v[534] input[81] = (v[254] & v[542]) input[124] = (v[487] & v[195]) let part139 = ((v[486] ^ v[313])) input[134] = ((v[316] ^ (v[328] & v[487])) ^ (part139 & ~v[419])) input[192] = (v[536] ^ v[445]) input[119] = (v[486] ^ v[313]) input[105] = ((v[313] & ~v[316]) ^ v[537]) let part140 = ((v[313] | v[195])) input[139] = ((part140 & v[419]) ^ (v[460] & v[487])) let part141 = ((v[313] | v[195])) let part142 = ((((part141 & v[487]) ^ v[313]) ^ v[195])) input[142] = (v[518] ^ (part142 & ~v[419])) input[67] = (v[544] & ~v[419]) let part143 = ((v[313] ^ v[195])) input[109] = ((v[460] ^ (~v[419] & v[195])) ^ (part143 & v[487])) input[197] = (v[543] ^ v[313]) input[154] = ((v[313] ^ v[195]) ^ v[539]) let part144 = ((v[316] | v[419])) input[155] = (v[517] ^ part144) input[200] = ((v[419] & ~v[517]) ^ v[316]) return input } }
gpl-3.0
6b62666f1007a6487c22825c7c2ee841
38.03171
127
0.38768
2.395829
false
false
false
false
LQJJ/demo
125-iOSTips-master/Demo/44.自定义带动画效果的模态框/CustomPresentation/ToastViewController.swift
1
2954
// // ToastViewController.swift // CustomPresentation // // Created by Dariel on 2019/2/19. // Copyright © 2019 Dariel. All rights reserved. // import UIKit class ToastViewController: UIViewController { init(title: String) { super.init(nibName: nil, bundle: nil) transitioningDelegate = self modalPresentationStyle = .custom view.backgroundColor = .darkGray let label = UILabel() label.text = title label.font = .systemFont(ofSize: 17, weight: .medium) label.textColor = .white label.numberOfLines = 0 view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: view.topAnchor, constant: 16), label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16), label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ToastViewController: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return ToastPresentationController(presentedViewController: presented, presenting: presenting) } } class ToastPresentationController: PresentationController { override var frameOfPresentedViewInContainerView: CGRect { guard let containerView = containerView, let presentedView = presentedView else { return .zero } let inset: CGFloat = 16 let safeAreaFrame = containerView.bounds .inset(by: containerView.safeAreaInsets) let targetWidth = safeAreaFrame.width - 2 * inset let fittingSize = CGSize( width: targetWidth, height: UIView.layoutFittingCompressedSize.height ) let targetHeight = presentedView.systemLayoutSizeFitting( fittingSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow).height var frame = safeAreaFrame frame.origin.x += inset frame.origin.y += frame.size.height - targetHeight - inset frame.size.width = targetWidth frame.size.height = targetHeight return frame } override func containerViewDidLayoutSubviews() { super.containerViewDidLayoutSubviews() presentedView?.frame = frameOfPresentedViewInContainerView } override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() presentedView?.layer.cornerRadius = 12 } }
apache-2.0
cd2766b59fa4875c174cd000fcf90764
34.578313
161
0.672875
5.812992
false
false
false
false
applivery/applivery-ios-sample-app
AppliveryDemo/ViewController.swift
1
1067
// // ViewController.swift // AppliveryDemo // // Created by Alejandro Jiménez on 26/1/16. // Copyright © 2016 Applivery S.L. All rights reserved. // import UIKit class ViewController: UIViewController { var timer: Timer! var time = 0.0 @IBOutlet weak var labelTime: UILabel! override func viewDidLoad() { super.viewDidLoad() self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerEvent), userInfo: nil, repeats: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if motion == .motionShake { NotificationCenter.default.post(name: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil) } } @objc func timerEvent() { self.time += 0.1 self.labelTime.text = "Time: \(self.time.f1())" } } extension Double { func f1() -> String { return self.format(".1") } func format(_ format: String) -> String { return String(format: "%\(format)f", self) } }
lgpl-3.0
240d2c95c221041a6a59b5ea7488f21e
20.3
131
0.692958
3.424437
false
false
false
false
daltonclaybrook/MCPixelArt-Mac
MCArt-iOS/ViewController.swift
1
3110
// // ViewController.swift // MCArt-iOS // // Created by Dalton Claybrook on 10/28/16. // Copyright © 2016 Claybrook Software, LLC. All rights reserved. // import UIKit let ShowPreview = "ShowPreview" class ViewController: UIViewController { private let loadingView = LoadingView() private var woolImage: WoolImage? //MARK: Superclass override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == ShowPreview, let controller = segue.destination as? PreviewViewController, let woolImage = woolImage { controller.delegate = self controller.configure(with: woolImage) } } //MARK: Actions @IBAction func takeAPhotoButtonPressed(_ sender: Any) { guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return } let imagePicker = UIImagePickerController() imagePicker.allowsEditing = true imagePicker.sourceType = .camera imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } @IBAction func chooseAnImageButtonPressed(_ sender: Any) { guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else { return } let imagePicker = UIImagePickerController() imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } //MARK: Private fileprivate func process(image: UIImage, size: CGSize) { loadingView.showInView(view: view) DispatchQueue(label: "Image Processing").async { [weak self] in let processor = ImageProcessor(transformer: WoolColorTransformer()) if let woolImage = processor.process(image: image, size: size) { DispatchQueue.main.async { self?.loadingView.hide() self?.woolImage = woolImage self?.performSegue(withIdentifier: ShowPreview, sender: nil) } } } } } extension ViewController: PreviewViewControllerDelegate { func previewViewController(_ vc: PreviewViewController, saved image: WoolImage) { dismiss(animated: true, completion: nil) } func previewViewControllerCancelled(_ vc: PreviewViewController) { dismiss(animated: true, completion: nil) } } extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { dismiss(animated: true, completion: nil) guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return } process(image: image, size: CGSize(width: 200, height: 200)) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } }
mit
5483b3c1e1b69f566cca7b21317c47ab
33.544444
133
0.664201
5.287415
false
false
false
false
ask-fm/AFMActionSheet
Pod/Classes/AFMDismissalAnimator.swift
1
2048
// // AFMDismissalAnimator.swift // Pods // // Created by Ilya Alesker on 26/08/15. // Copyright (c) 2015 Ask.fm Europe, Ltd. All rights reserved. // import UIKit open class AFMDismissalAnimator: NSObject, UIViewControllerAnimatedTransitioning { var animator: UIDynamicAnimator? open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.0 } open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! as UIViewController let initialFrame = transitionContext.initialFrame(for: fromViewController) transitionContext.containerView.addSubview(fromViewController.view) let views = Array(fromViewController.view.subviews.reversed()) let viewCount = Double(views.count) var index = 0 let step: Double = self.transitionDuration(using: transitionContext) * 0.5 / viewCount for view in views { let delay = step * Double(index) UIView.animate(withDuration: self.transitionDuration(using: transitionContext) - delay, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.3, options: [], animations: { view.transform = CGAffineTransform(translationX: 0, y: initialFrame.height) }, completion: nil) index += 1 } let backgroundColor = fromViewController.view.backgroundColor! UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: { fromViewController.view.backgroundColor = backgroundColor.withAlphaComponent(0) }, completion: { _ in fromViewController.view.backgroundColor = backgroundColor transitionContext.completeTransition(true) }) } }
mit
5ac348c9720ff04378ce6043e5e61d95
37.641509
137
0.671387
5.785311
false
false
false
false
brave/browser-ios
brave/src/analytics/user-referral-program/UrpLogsViewController.swift
2
1542
/* 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 UrpLog { static let prefsKey = "urpLogs" static func log(_ text: String) { var logs = UserDefaults.standard.string(forKey: prefsKey) ?? "" let date = Date() let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date) guard let year = components.year, let month = components.month, let day = components.day, let hour = components.hour, let minute = components.minute else { return } let time = "\(year)-\(month)-\(day) \(hour):\(minute)" logs.append("[\(time)] \(text)\n") UserDefaults.standard.set(logs, forKey: prefsKey) } } class UrpLogsViewController: UIViewController { lazy var logsTextView: UITextView = { let textView = UITextView() textView.isEditable = false return textView }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(logsTextView) logsTextView.snp.makeConstraints { make in make.top.equalTo(self.topLayoutGuide.snp.bottom).offset(8) make.left.right.bottom.equalTo(self.view).inset(8) } guard let logs = UserDefaults.standard.string(forKey: UrpLog.prefsKey) else { return } logsTextView.text = logs } }
mpl-2.0
05f4bf193d6274fd141d23dfb50716db
33.266667
198
0.637484
4.156334
false
false
false
false
cinco-interactive/BluetoothKit
Example/Vendor/SnapKit/Example-iOS/AppDelegate.swift
2
2557
// // AppDelegate.swift // Example-iOS // // Created by Spiros Gerokostas on 01/03/16. // Copyright © 2016 SnapKit Team. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let listViewController:ListViewController = ListViewController() let navigationController:UINavigationController = UINavigationController(rootViewController: listViewController); self.window!.rootViewController = navigationController; self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
f50a96b179b70507e99a11c9cd4281c3
44.642857
285
0.742175
5.809091
false
false
false
false
luizlopezm/ios-Luis-Trucking
Pods/SwiftForms/SwiftForms/cells/FormTextViewCell.swift
1
3580
// // FormTextViewCell.swift // SwiftForms // // Created by Joey Padot on 12/6/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormTextViewCell : FormBaseCell, UITextViewDelegate { // MARK: Cell views public let titleLabel = UILabel() public let textField = UITextView() // MARK: Properties private var customConstraints: [AnyObject]! // MARK: Class Funcs public override class func formRowCellHeight() -> CGFloat { return 110.0 } // MARK: FormBaseCell public override func configure() { super.configure() selectionStyle = .None titleLabel.translatesAutoresizingMaskIntoConstraints = false textField.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) contentView.addSubview(titleLabel) contentView.addSubview(textField) titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0)) textField.delegate = self } public override func update() { titleLabel.text = rowDescriptor.title textField.text = rowDescriptor.value as? String textField.secureTextEntry = false textField.autocorrectionType = .Default textField.autocapitalizationType = .Sentences textField.keyboardType = .Default } public override func constraintsViews() -> [String : UIView] { var views = ["titleLabel" : titleLabel, "textField" : textField] if self.imageView!.image != nil { views["imageView"] = imageView } return views } public override func defaultVisualConstraints() -> [String] { if self.imageView!.image != nil { if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 { return ["H:[imageView]-[titleLabel]-[textField]-16-|"] } else { return ["H:[imageView]-[textField]-16-|"] } } else { if titleLabel.text != nil && (titleLabel.text!).characters.count > 0 { return ["H:|-16-[titleLabel]-[textField]-16-|"] } else { return ["H:|-16-[textField]-16-|"] } } } // MARK: UITextViewDelegate public func textViewDidChange(textView: UITextView) { let trimmedText = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) rowDescriptor.value = trimmedText.characters.count > 0 ? trimmedText : nil } }
mit
2eb87baa2fe0c8b24dfe1fa77a4a35c0
35.151515
185
0.631182
5.317979
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/RxObjCRuntimeState.swift
3
4286
// // RxObjCRuntimeState.swift // RxTests // // Created by Krunoslav Zaher on 11/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest struct RxObjCRuntimeChange { let dynamicSublasses: Int let swizzledForwardClasses: Int let interceptedClasses: Int let methodsSwizzled: Int let methodsForwarded: Int /** Takes into account default methods that were swizzled while creating dynamic subclasses. */ static func changes(dynamicSubclasses: Int = 0, swizzledForwardClasses: Int = 0, interceptedClasses: Int = 0, methodsSwizzled: Int = 0, methodsForwarded: Int = 0) -> RxObjCRuntimeChange { return RxObjCRuntimeChange( dynamicSublasses: dynamicSubclasses, swizzledForwardClasses: swizzledForwardClasses, interceptedClasses: dynamicSubclasses + interceptedClasses, methodsSwizzled: methodsSwizzled + 1/*class*/ * dynamicSubclasses + 3/*forwardInvocation, respondsToSelector, methodSignatureForSelector*/ * swizzledForwardClasses, methodsForwarded: methodsForwarded ) } } class RxObjCRuntimeState { // total number of dynamically genertated classes let dynamicSublasses: Int // total number of classes that have swizzled forwarding mechanism let swizzledForwardClasses: Int // total number of classes that have at least one selector intercepted by either forwarding or sending messages let interceptingClasses: Int // total numbers of methods that are swizzled, methods used for forwarding (forwardInvocation, respondsToSelector, methodSignatureForSelector, class) also count let methodsSwizzled: Int // total number of methods that are intercepted by forwarding let methodsForwarded: Int init() { #if TRACE_RESOURCES dynamicSublasses = RX_number_of_dynamic_subclasses() swizzledForwardClasses = RX_number_of_forwarding_enabled_classes() interceptingClasses = RX_number_of_intercepting_classes() methodsSwizzled = RX_number_of_swizzled_methods() methodsForwarded = RX_number_of_forwarded_methods() #else dynamicSublasses = 0 swizzledForwardClasses = 0 interceptingClasses = 0 methodsSwizzled = 0 methodsForwarded = 0 #endif } func assertAfterThisMoment(_ previous: RxObjCRuntimeState, changed: RxObjCRuntimeChange) { #if TRACE_RESOURCES let realChangeOfDynamicSubclasses = dynamicSublasses - previous.dynamicSublasses XCTAssertEqual(realChangeOfDynamicSubclasses, changed.dynamicSublasses) if (realChangeOfDynamicSubclasses != changed.dynamicSublasses) { print("dynamic subclasses: real = \(realChangeOfDynamicSubclasses) != expected = \(changed.dynamicSublasses)") } let realSwizzledForwardClasses = swizzledForwardClasses - previous.swizzledForwardClasses XCTAssertEqual(realSwizzledForwardClasses, changed.swizzledForwardClasses) if (realSwizzledForwardClasses != changed.swizzledForwardClasses) { print("forward classes: real = \(realSwizzledForwardClasses) != expected = \(changed.swizzledForwardClasses)") } let realInterceptingClasses = interceptingClasses - previous.interceptingClasses XCTAssertEqual(realInterceptingClasses, changed.interceptedClasses) if (realInterceptingClasses != changed.interceptedClasses) { print("intercepting classes: real = \(realInterceptingClasses) != expected = \(changed.interceptedClasses)") } let realMethodsSwizzled = methodsSwizzled - previous.methodsSwizzled XCTAssertEqual(realMethodsSwizzled, changed.methodsSwizzled) if (realMethodsSwizzled != changed.methodsSwizzled) { print("swizzled methods: real = \(realMethodsSwizzled) != expected = \(changed.methodsSwizzled)") } let realMethodsForwarded = methodsForwarded - previous.methodsForwarded XCTAssertEqual(realMethodsForwarded, changed.methodsForwarded) if (realMethodsForwarded != changed.methodsForwarded) { print("forwarded methods: real = \(realMethodsForwarded) != expected = \(changed.methodsForwarded)") } #endif } }
mit
2124b39316df90179d1323e8f282669e
46.611111
191
0.72182
5.608639
false
false
false
false
CD1212/Doughnut
Doughnut/Views/DownloadCellView.swift
1
1991
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa class DownloadCellView: NSTableCellView, DownloadProgressDelegate { @IBOutlet weak var episodeTitle: NSTextField! @IBOutlet weak var progressBar: NSProgressIndicator! @IBOutlet weak var progressText: NSTextField! let byteFormatter = ByteCountFormatter() var download: DownloadTask? { didSet { download?.progressDelegate = self byteFormatter.allowedUnits = .useMB byteFormatter.countStyle = .file episodeTitle.stringValue = download?.episode.title ?? "" } } func download(progressed download: DownloadTask) { if download.totalBytes > 0 { progressBar.stopAnimation(self) progressBar.minValue = 0 progressBar.maxValue = 1 progressBar.isIndeterminate = false progressBar.doubleValue = download.progressedBytes / download.totalBytes progressText.stringValue = "\(byteFormatter.string(fromByteCount: Int64(download.progressedBytes))) of \(byteFormatter.string(fromByteCount: Int64(download.totalBytes)))" } else { progressBar.startAnimation(self) progressBar.isIndeterminate = true progressBar.doubleValue = 0 progressBar.minValue = 0 progressBar.maxValue = 0 progressText.stringValue = "Unknown" } } }
gpl-3.0
0cc47133c6ab7ff54f60b58c6be37b58
33.327586
176
0.720241
4.786058
false
false
false
false
apple/swift
test/SILGen/back_deploy_attribute_struct_method.swift
2
3281
// RUN: %target-swift-emit-sil -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 -verify // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.50 | %FileCheck %s // RUN: %target-swift-emit-silgen -parse-as-library -module-name back_deploy %s -target %target-cpu-apple-macosx10.60 | %FileCheck %s // REQUIRES: OS=macosx @available(macOS 10.50, *) public struct TopLevelStruct { // -- Fallback definition for TopLevelStruct.trivialMethod() // CHECK-LABEL: sil non_abi [serialized] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> () // CHECK: bb0({{%.*}} : $TopLevelStruct): // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // -- Back deployment thunk for TopLevelStruct.trivialMethod() // CHECK-LABEL: sil non_abi [serialized] [thunk] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> () // CHECK: bb0([[BB0_ARG:%.*]] : $TopLevelStruct): // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[OSVFN:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[AVAIL:%.*]] = apply [[OSVFN]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: cond_br [[AVAIL]], [[AVAIL_BB:bb[0-9]+]], [[UNAVAIL_BB:bb[0-9]+]] // // CHECK: [[UNAVAIL_BB]]: // CHECK: [[FALLBACKFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwB : $@convention(method) (TopLevelStruct) -> () // CHECK: {{%.*}} = apply [[FALLBACKFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> () // CHECK: br [[RETURN_BB:bb[0-9]+]] // // CHECK: [[AVAIL_BB]]: // CHECK: [[ORIGFN:%.*]] = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> () // CHECK: {{%.*}} = apply [[ORIGFN]]([[BB0_ARG]]) : $@convention(method) (TopLevelStruct) -> () // CHECK: br [[RETURN_BB]] // // CHECK: [[RETURN_BB]] // CHECK: [[RESULT:%.*]] = tuple () // CHECK: return [[RESULT]] : $() // -- Original definition of TopLevelStruct.trivialMethod() // CHECK-LABEL: sil [available 10.52] [ossa] @$s11back_deploy14TopLevelStructV13trivialMethodyyF : $@convention(method) (TopLevelStruct) -> () @available(macOS 10.51, *) @_backDeploy(before: macOS 10.52) public func trivialMethod() {} } // CHECK-LABEL: sil hidden [available 10.51] [ossa] @$s11back_deploy6calleryyAA14TopLevelStructVF : $@convention(thin) (TopLevelStruct) -> () // CHECK: bb0([[STRUCT_ARG:%.*]] : $TopLevelStruct): @available(macOS 10.51, *) func caller(_ s: TopLevelStruct) { // -- Verify the thunk is called // CHECK: {{%.*}} = function_ref @$s11back_deploy14TopLevelStructV13trivialMethodyyFTwb : $@convention(method) (TopLevelStruct) -> () s.trivialMethod() }
apache-2.0
18cabcdd8f1a2dcb2a2caffa14745094
59.759259
169
0.654983
3.464625
false
false
false
false
DeliveLee/Custom-TimePicker-for-PopUp
TimePicker/UtilKits/CommonMethod/UIColorExtension.swift
1
2251
// // UIColorExtension.swift // UIColor-Hex-Swift // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit extension UIColor { public convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) let hex = rgba.substring(from: index) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix") } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
mit
f82495f1c3a48dc0a2fe42869f00fee0
40.685185
109
0.464682
4.005338
false
false
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFramework/database/coredata/model/HMCDSections.swift
1
1725
// // HMCDSections.swift // HMRequestFramework // // Created by Hai Pham on 9/1/17. // Copyright © 2017 Holmusk. All rights reserved. // /// Utility class for HMCDSection. public final class HMCDSections { /// Get the object for a particular index path from a Sequence of sections. /// /// - Parameters: /// - sections: A Sequence of HMCDSectionType. /// - indexPath: An IndexPath instance. /// - Returns: A ST.V instance. public static func object<ST,S>(_ sections: S, _ indexPath: IndexPath) -> ST.V? where ST: HMCDSectionType, S: Sequence, S.Element == ST { let sections = sections.map({$0}) let section = indexPath.section let row = indexPath.row return sections.element(at: section)?.objects.element(at: row) } /// Get sliced sections from a Sequence of sections so that the total number /// of objects do not exceed a limit. /// /// - Parameters: /// - sections: A Sequence of sections. /// - limit: An Int value. /// - Returns: An Array of sections. public static func sectionsWithLimit<ST,S>(_ sections: S, _ limit: Int) -> [ST] where ST: HMCDSectionType, S: Sequence, S.Element == ST { var sliced = [ST]() for section in sections { let sectionLimit = limit - sliced.reduce(0, {$1.numberOfObjects + $0}) if sectionLimit > 0 { sliced.append(section.withObjectLimit(sectionLimit)) } else { break } } return sliced } private init() {} }
apache-2.0
96abc4a69558b0ed4e0e25d745ee9706
30.345455
82
0.545824
4.477922
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Data/CNKeyBinding.swift
1
5726
/** * @file CNKeyBinding.swift * @brief Define CNKeyBinding class * @par Copyright * Copyright (C) 2019 Steel Wheels Project */ import Foundation private let ESC: Character = "\u{1b}" // ESC /* * reference: https://www.hcs.harvard.edu/~jrus/site/system-bindings.html */ public enum CNKeyBinding { public enum LeaveMode { case Leave case DoNotLeave } public enum DeleteUnit { case character case word case paragraph } public enum CursorDirection { case left case right case up case down } public enum ScrollDirection { case up case down } public enum ScrollUnit { case page case document } public enum DocumentDirection { case forward case backward } public enum DocumentUnit { case word case line case paragraph case document } case insertNewline(LeaveMode) // true: Leave form box, false: dont leave case insertTab(LeaveMode) // true: Leave form box, false: dont leave case insertBackTab case cycleToNextInputScript case togglePlatformInputSystem case cycleToNextInputKeyboardLayout case deleteBackward(DeleteUnit) case deleteForward(DeleteUnit) case cancel case moveCursor(CursorDirection) case moveTo(DocumentDirection, DocumentUnit) case scroll(ScrollDirection, ScrollUnit) public static func decode(selectorName name: String) -> CNKeyBinding? { let result: CNKeyBinding? switch name { case "insertNewline:": result = .insertNewline(.DoNotLeave) case "insertNewlineIgnoringFieldEditor:": result = .insertNewline(.DoNotLeave) case "insertTab:": result = .insertTab(.DoNotLeave) case "insertTabIgnoringFieldEditor:": result = .insertTab(.DoNotLeave) case "insertBacktab:": result = .insertBackTab case "cycleToNextInputScript:": result = .cycleToNextInputScript case "togglePlatformInputSystem:": result = .togglePlatformInputSystem case "cycleToNextInputKeyboardLayout:": result = .cycleToNextInputKeyboardLayout case "deleteBackward:": result = .deleteBackward(.character) case "deleteWordBackward:": result = .deleteBackward(.word) case "deleteForward:": result = .deleteForward(.character) case "deleteWordForward:": result = .deleteForward(.word) case "cancelOperation:": result = .cancel case "complete:": result = nil // Not supported case "moveUp:", "moveUpAndModifySelection:": result = .moveCursor(.up) case "scrollPageUp:": result = .scroll(.up, .page) case "moveToBeginningOfDocument:", "moveToBeginningOfDocumentAndModifySelection:": result = .moveTo(.backward, .document) case "moveToBeginningOfParagraph:", "moveParagraphBackwardAndModifySelection:": result = .moveTo(.backward, .paragraph) case "moveDown:", "moveDownAndModifySelection:": result = .moveCursor(.down) case "scrollPageDown:": result = .scroll(.down, .page) case "moveToEndOfDocument:" ,"moveToEndOfDocumentAndModifySelection:": result = .moveTo(.forward, .document) case "moveToEndOfParagraph:": result = .moveTo(.forward, .paragraph) case "moveParagraphForwardAndModifySelection:": result = .moveTo(.forward, .paragraph) case "moveLeft:", "moveLeftAndModifySelection:": result = .moveCursor(.left) case "moveToBeginningOfLine:", "moveToBeginningOfLineAndModifySelection:": result = .moveTo(.backward, .line) case "changeBaseWritingDirectionToRTL:", "changeBaseWritingDirectionToLTR:": result = nil // Not supported case "moveWordLeft:", "moveWordLeftAndModifySelection:": result = .moveTo(.backward, .word) case "moveRight:", "moveRightAndModifySelection:": result = .moveCursor(.right) case "moveToEndOfLine:", "moveToEndOfLineAndModifySelection:": result = .moveTo(.forward, .line) case "moveWordRight:", "moveWordRightAndModifySelection:": result = .moveTo(.forward, .word) case "scrollToBeginningOfDocument:": result = .scroll(.up, .document) case "scrollToEndOfDocument:": result = .scroll(.down, .document) case "pageUp:", "pageUpAndModifySelection:": result = .scroll(.up, .page) case "pageDown:", "pageDownAndModifySelection:": result = .scroll(.down, .page) case "moveBackward:": result = .moveCursor(.left) case "moveForward:": result = .moveCursor(.right) case "deleteToEndOfParagraph:": result = .deleteForward(.paragraph) case "centerSelectionInVisibleArea:": result = nil // Not supported case "transpose:": result = nil // Not supported case "yank:": result = nil // Not supported default: result = nil } return result } public func toEscapeCode() -> [CNEscapeCode]? { var result: [CNEscapeCode]? = nil switch self { case .insertNewline(_): result = [.newline] case .insertTab(_): result = [.tab] case .insertBackTab: result = nil // Not supported case .cycleToNextInputScript: result = nil // Not supported case .togglePlatformInputSystem: result = nil // Not supported case .cycleToNextInputKeyboardLayout: result = nil // Not supported case .deleteBackward(let unit): switch unit { case .character: result = [.delete] case .paragraph, .word: result = nil // Not supported } case .deleteForward(let unit): switch unit { case .character: result = [.cursorForward(1), .delete] case .paragraph, .word: result = nil // Not supported } case .cancel: result = [.string("\(ESC)")] case .moveCursor(let dir): switch dir { case .up: result = [.cursorUp(1)] case .down: result = [.cursorDown(1)] case .left: result = [.cursorBackward(1)] case .right: result = [.cursorForward(1)] } case .moveTo(_, _): result = nil // Not supported case .scroll(_, _): result = nil // Not supported } return result } }
lgpl-2.1
c081de55764427963be81056667a91a6
26.931707
84
0.704156
3.536751
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/TabScrollController.swift
3
12596
/* 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 import SnapKit private let ToolbarBaseAnimationDuration: CGFloat = 0.2 class TabScrollingController: NSObject { enum ScrollDirection { case up case down } enum ToolbarState { case collapsed case visible case animating } weak var tab: Tab? { willSet { self.scrollView?.delegate = nil self.scrollView?.removeGestureRecognizer(panGesture) } didSet { self.scrollView?.addGestureRecognizer(panGesture) scrollView?.delegate = self } } // Constraint-based animation is causing PDF docs to flicker. This is used to bypass this animation. var isTabShowingPDF: Bool { return (tab?.mimeType ?? "") == MIMEType.PDF } weak var header: UIView? weak var footer: UIView? weak var urlBar: URLBarView? weak var readerModeBar: ReaderModeBarView? weak var snackBars: UIView? var footerBottomConstraint: Constraint? var headerTopConstraint: Constraint? var toolbarsShowing: Bool { return headerTopOffset == 0 } fileprivate var isZoomedOut: Bool = false fileprivate var lastZoomedScale: CGFloat = 0 fileprivate var isUserZoom: Bool = false fileprivate var headerTopOffset: CGFloat = 0 { didSet { headerTopConstraint?.update(offset: headerTopOffset) header?.superview?.setNeedsLayout() } } fileprivate var footerBottomOffset: CGFloat = 0 { didSet { footerBottomConstraint?.update(offset: footerBottomOffset) footer?.superview?.setNeedsLayout() } } fileprivate lazy var panGesture: UIPanGestureRecognizer = { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) panGesture.maximumNumberOfTouches = 1 panGesture.delegate = self return panGesture }() fileprivate var scrollView: UIScrollView? { return tab?.webView?.scrollView } fileprivate var contentOffset: CGPoint { return scrollView?.contentOffset ?? .zero } fileprivate var contentSize: CGSize { return scrollView?.contentSize ?? .zero } fileprivate var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 } fileprivate var topScrollHeight: CGFloat { guard let headerHeight = header?.frame.height else { return 0 } guard let readerModeHeight = readerModeBar?.frame.height else { return headerHeight } return headerHeight + readerModeHeight } fileprivate var bottomScrollHeight: CGFloat { return footer?.frame.height ?? 0 } fileprivate var snackBarsFrame: CGRect { return snackBars?.frame ?? .zero } fileprivate var lastContentOffset: CGFloat = 0 fileprivate var scrollDirection: ScrollDirection = .down fileprivate var toolbarState: ToolbarState = .visible override init() { super.init() } func showToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) { if toolbarState == .visible { completion?(true) return } toolbarState = .visible let durationRatio = abs(headerTopOffset / topScrollHeight) let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated, duration: actualDuration, headerOffset: 0, footerOffset: 0, alpha: 1, completion: completion) } func hideToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) { if toolbarState == .collapsed { completion?(true) return } toolbarState = .collapsed let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight) let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio) self.animateToolbarsWithOffsets( animated, duration: actualDuration, headerOffset: -topScrollHeight, footerOffset: bottomScrollHeight, alpha: 0, completion: completion) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentSize" { if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing { showToolbars(animated: true, completion: nil) } } } func updateMinimumZoom() { guard let scrollView = scrollView else { return } self.isZoomedOut = roundNum(scrollView.zoomScale) == roundNum(scrollView.minimumZoomScale) self.lastZoomedScale = self.isZoomedOut ? 0 : scrollView.zoomScale } func setMinimumZoom() { guard let scrollView = scrollView else { return } if self.isZoomedOut && roundNum(scrollView.zoomScale) != roundNum(scrollView.minimumZoomScale) { scrollView.zoomScale = scrollView.minimumZoomScale } } func resetZoomState() { self.isZoomedOut = false self.lastZoomedScale = 0 } fileprivate func roundNum(_ num: CGFloat) -> CGFloat { return round(100 * num) / 100 } } private extension TabScrollingController { func tabIsLoading() -> Bool { return tab?.loading ?? true } func isBouncingAtBottom() -> Bool { guard let scrollView = scrollView else { return false } return scrollView.contentOffset.y > (scrollView.contentSize.height - scrollView.frame.size.height) && scrollView.contentSize.height > scrollView.frame.size.height } @objc func handlePan(_ gesture: UIPanGestureRecognizer) { if tabIsLoading() { return } if let containerView = scrollView?.superview { let translation = gesture.translation(in: containerView) let delta = lastContentOffset - translation.y if delta > 0 { scrollDirection = .down } else if delta < 0 { scrollDirection = .up } lastContentOffset = translation.y if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() { let bottomIsNotRubberbanding = contentOffset.y + scrollViewHeight < contentSize.height let topIsRubberbanding = contentOffset.y <= 0 if isTabShowingPDF || ((toolbarState != .collapsed || topIsRubberbanding) && bottomIsNotRubberbanding) { scrollWithDelta(delta) } if headerTopOffset == -topScrollHeight && footerBottomOffset == bottomScrollHeight { toolbarState = .collapsed } else if headerTopOffset == 0 { toolbarState = .visible } else { toolbarState = .animating } } if gesture.state == .ended || gesture.state == .cancelled { lastContentOffset = 0 } } } func checkRubberbandingForDelta(_ delta: CGFloat) -> Bool { return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height && scrollViewHeight < contentSize.height) || contentOffset.y < delta) } func scrollWithDelta(_ delta: CGFloat) { if scrollViewHeight >= contentSize.height { return } var updatedOffset = headerTopOffset - delta headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0) if isHeaderDisplayedForGivenOffset(updatedOffset) { scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta) } updatedOffset = footerBottomOffset + delta footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight) let alpha = 1 - abs(headerTopOffset / topScrollHeight) urlBar?.updateAlphaForSubviews(alpha) readerModeBar?.updateAlphaForSubviews(alpha) } func isHeaderDisplayedForGivenOffset(_ offset: CGFloat) -> Bool { return offset > -topScrollHeight && offset < 0 } func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } func animateToolbarsWithOffsets(_ animated: Bool, duration: TimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, alpha: CGFloat, completion: ((_ finished: Bool) -> Void)?) { guard let scrollView = scrollView else { return } let initialContentOffset = scrollView.contentOffset // If this function is used to fully animate the toolbar from hidden to shown, keep the page from scrolling by adjusting contentOffset, // Otherwise when the toolbar is hidden and a link navigated, showing the toolbar will scroll the page and // produce a ~50px page jumping effect in response to tap navigations. let isShownFromHidden = headerTopOffset == -topScrollHeight && headerOffset == 0 let animation: () -> Void = { if isShownFromHidden { scrollView.contentOffset = CGPoint(x: initialContentOffset.x, y: initialContentOffset.y + self.topScrollHeight) } self.headerTopOffset = headerOffset self.footerBottomOffset = footerOffset self.urlBar?.updateAlphaForSubviews(alpha) self.readerModeBar?.updateAlphaForSubviews(alpha) self.header?.superview?.layoutIfNeeded() } if animated { UIView.animate(withDuration: duration, delay: 0, options: .allowUserInteraction, animations: animation, completion: completion) } else { animation() completion?(true) } } func checkScrollHeightIsLargeEnoughForScrolling() -> Bool { return (UIScreen.main.bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height ?? 0 } } extension TabScrollingController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension TabScrollingController: UIScrollViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if tabIsLoading() || isBouncingAtBottom() { return } if (decelerate || (toolbarState == .animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() { if scrollDirection == .up { showToolbars(animated: !isTabShowingPDF) } else if scrollDirection == .down { hideToolbars(animated: !isTabShowingPDF) } } } func scrollViewDidZoom(_ scrollView: UIScrollView) { // Only mess with the zoom level if the user did not initate the zoom via a zoom gesture if self.isUserZoom { return } //scrollViewDidZoom will be called multiple times when a rotation happens. // In that case ALWAYS reset to the minimum zoom level if the previous state was zoomed out (isZoomedOut=true) if isZoomedOut { scrollView.zoomScale = scrollView.minimumZoomScale } else if roundNum(scrollView.zoomScale) > roundNum(self.lastZoomedScale) && self.lastZoomedScale != 0 { //When we have manually zoomed in we want to preserve that scale. //But sometimes when we rotate a larger zoomScale is appled. In that case apply the lastZoomedScale scrollView.zoomScale = self.lastZoomedScale } } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { self.isUserZoom = true } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self.isUserZoom = false } func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { if toolbarState == .collapsed { showToolbars(animated: true) return false } return true } }
mpl-2.0
8ae98dfe979c492467df489ee8199ee8
36.376855
184
0.63798
5.380607
false
false
false
false
sammyd/VT_InAppPurchase
prototyping/GreenGrocer/GreenGrocer/Product.swift
13
2846
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit private let idKey = "id" private let nameKey = "name" private let priceKey = "price" private let detailsKey = "details" private let photoNameKey = "photoName" typealias ProductID = NSUUID final class Product { let id: ProductID let name: String let price: Int let details: String let photoName: String init(id: ProductID, name: String, price: Int, details: String, photoName: String) { self.id = id self.name = name self.price = price self.details = details self.photoName = photoName } } extension Product { convenience init(name: String, price: Int, details: String, photoName: String) { self.init(id: NSUUID(), name: name, price: price, details: details, photoName: photoName) } } extension Product : Serializable { convenience init?(dict: [String : AnyObject]) { guard let idString = dict[idKey] as? String, let id = NSUUID(UUIDString: idString), let name = dict[nameKey] as? String, let price = dict[priceKey] as? Int, let details = dict[detailsKey] as? String, let photoName = dict[photoNameKey] as? String else { return nil } self.init(id: id, name: name, price: price, details: details, photoName: photoName) } var dictRepresentation : [String : AnyObject] { return [ idKey : id.UUIDString, nameKey : name, priceKey : price, detailsKey : details, photoNameKey : photoName, ] } } extension Product : Equatable { // Free function below } func ==(lhs: Product, rhs: Product) -> Bool { return lhs.id.isEqual(rhs.id) } extension Product : Hashable { var hashValue : Int { return id.UUIDString.hashValue } }
mit
1bd906043239ad6a084a029d1ad5452f
29.945652
93
0.6922
4.054131
false
false
false
false
auth0/Lock.swift
LockTests/Presenters/DatabaseForgotPasswordPresenterSpec.swift
1
11605
// DatabaseForgotPasswordPresenterSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Quick import Nimble @testable import Lock class DatabaseForgotPasswordPresenterSpec: QuickSpec { override func spec() { var interactor: MockForgotInteractor! var presenter: DatabaseForgotPasswordPresenter! var view: DatabaseForgotPasswordView! var messagePresenter: MockMessagePresenter! var connections: OfflineConnections! var navigator: MockNavigator! var options: OptionBuildable! beforeEach { options = LockOptions() navigator = MockNavigator() messagePresenter = MockMessagePresenter() interactor = MockForgotInteractor() connections = OfflineConnections() connections.database(name: connection, requiresUsername: true) presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) presenter.messagePresenter = messagePresenter view = presenter.view as? DatabaseForgotPasswordView } it("should use valid email") { interactor.email = email interactor.validEmail = true presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) let view = (presenter.view as! DatabaseForgotPasswordView).form as! SingleInputView expect(view.value) == email } it("should not use invalid email") { interactor.email = email interactor.validEmail = false presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) let view = (presenter.view as! DatabaseForgotPasswordView).form as! SingleInputView expect(view.value) != email } it("should have button title") { expect(view.primaryButton?.title) == "SEND EMAIL" } describe("forgot") { describe("user input") { it("should clear global message") { messagePresenter.showError(PasswordRecoverableError.emailNotSent) let input = mockInput(.email, value: email) view.form?.onValueChange(input) expect(messagePresenter.error).to(beNil()) expect(messagePresenter.message).to(beNil()) } it("should update email") { let input = mockInput(.email, value: email) view.form?.onValueChange(input) expect(interactor.email) == email } it("should not update if type is not valid for db connection") { let input = mockInput(.phone, value: "+1234567890") view.form?.onValueChange(input) expect(interactor.email).to(beNil()) } it("should hide the field error if value is valid") { let input = mockInput(.email, value: email) view.form?.onValueChange(input) expect(input.valid) == true } it("should show field error if value is invalid") { let input = mockInput(.email, value: "invalid") view.form?.onValueChange(input) expect(input.valid) == false } } describe("request forgot email action") { it("should trigger action on return of last field") { let input = mockInput(.email, value: email) input.returnKey = .done waitUntil { done in interactor.onRequest = { done() return nil } view.form?.onReturn(input) } } it("should not trigger action with nil button") { let input = mockInput(.oneTimePassword, value: "123456") input.returnKey = .done interactor.onRequest = { return .emailNotSent } view.primaryButton = nil view.form?.onReturn(input) expect(messagePresenter.message).toEventually(beNil()) expect(messagePresenter.error).toEventually(beNil()) } it("should show global error message") { interactor.onRequest = { return .noDatabaseConnection } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.error).toEventually(beError(error: PasswordRecoverableError.noDatabaseConnection)) } it("should show global error message") { interactor.onRequest = { return .nonValidInput } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.error).toEventually(beError(error: PasswordRecoverableError.nonValidInput)) } it("should show global error message") { interactor.onRequest = { return .emailNotSent } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.error).toEventually(beError(error: PasswordRecoverableError.emailNotSent)) } it("should show global success message") { interactor.onRequest = { return nil } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.message).toEventuallyNot(beNil()) } it("should trigger request on button press") { waitUntil { done in interactor.onRequest = { done() return nil } view.primaryButton?.onPress(view.primaryButton!) } } it("should set button in progress on button press") { let button = view.primaryButton! waitUntil { done in interactor.onRequest = { expect(button.inProgress) == true done() return nil } button.onPress(button) } } it("should set button to normal after request") { let button = view.primaryButton! button.onPress(button) expect(button.inProgress).toEventually(beFalse()) } context("no login screen") { beforeEach { options.allow = .ResetPassword presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) presenter.messagePresenter = messagePresenter view = presenter.view as? DatabaseForgotPasswordView } it("should not show global success message") { interactor.onRequest = { return nil } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.message).toEventually(beNil()) } it("should show global success message") { options.allow = .ResetPassword options.autoClose = false presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) presenter.messagePresenter = messagePresenter view = presenter.view as? DatabaseForgotPasswordView interactor.onRequest = { return nil } view.primaryButton?.onPress(view.primaryButton!) expect(messagePresenter.message).toEventuallyNot(beNil()) } } } describe("navigation on success") { it("should navigate to .root") { let button = view.primaryButton! interactor.onRequest = { return nil } button.onPress(button) expect(navigator.route).toEventually(equal(Route.root)) } it("should not navigate to .root") { options.allow = .ResetPassword navigator.route = .forgotPassword presenter = DatabaseForgotPasswordPresenter(interactor: interactor, connections: connections, navigator: navigator, options: options) view = presenter.view as? DatabaseForgotPasswordView let button = view.primaryButton! interactor.onRequest = { return nil } button.onPress(button) expect(navigator.route).toEventuallyNot(equal(Route.root)) } } } } } class MockForgotInteractor: PasswordRecoverable { var validEmail: Bool = false var email: String? var onRequest: () -> PasswordRecoverableError? = { return nil } func requestEmail(_ callback: @escaping (PasswordRecoverableError?) -> ()) { callback(onRequest()) } func updateEmail(_ value: String?) throws { guard value != "invalid" else { self.validEmail = false throw NSError(domain: "", code: 0, userInfo: nil) } self.validEmail = true self.email = value } }
mit
511ef6548b549ce23177660071ae701c
39.576923
157
0.538561
6.120781
false
false
false
false
caiobzen/Pomodoro
Pomodoro WatchKit Extension/InterfaceController.swift
1
3546
// // InterfaceController.swift // Pomodoro WatchKit 1 Extension // // Created by Carlos Corrêa on 8/25/15. // Copyright © 2015 Carlos Corrêa. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { //MARK: - Variables and Properties @IBOutlet var table: WKInterfaceTable! @IBOutlet var lblNoTasks: WKInterfaceLabel! @IBOutlet var imgTomato: WKInterfaceImage! var selectedTask: TaskModel? //MARK: - WKInterfaceController lifecycle override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() self.setupTable() //This will animate our tomato. Let's make that pretty dude! self.imgTomato.setImageNamed("tomato") self.imgTomato.startAnimatingWithImagesInRange(NSMakeRange(1, 10), duration: 0.8, repeatCount: 0) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } //MARK: - UI Setup //Loads the TaskModel objects into the WKInterfaceTable. func setupTable() { if let activitiesList = CCCoreDataStack.sharedInstance.allTasks() as [TaskModel]? { self.table.setNumberOfRows(activitiesList.count, withRowType: "TaskRowType") if activitiesList.count != 0 { var i=0 for task in activitiesList { let row = self.table.rowControllerAtIndex(i) as! TaskRowType //task = activitiesList[i] as! TaskModel row.rowDescription.setText(task.name) i++ } self.lblNoTasks.setHidden(true) self.imgTomato.setHidden(true) } else { self.lblNoTasks.setHidden(false) self.imgTomato.setHidden(false) } } } //MARK: - Sending data to TaskController override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? { if segueIdentifier == "TaskDetailsSegue" { if let activitiesList = CCCoreDataStack.sharedInstance.allTasks() as [TaskModel]? { self.table.setNumberOfRows(activitiesList.count, withRowType: "TaskRowType") let task = activitiesList[rowIndex] return task } } return nil } //MARK: - User Input @IBAction func enterActivityNameButtonTapped() { self.presentTextInputControllerWithSuggestions([ "Read a book", "Gym", "Run", "Walk with my dog", "Work"], allowedInputMode: WKTextInputMode.Plain, completion:{(selectedAnswers) -> Void in if selectedAnswers != nil { if let taskName = selectedAnswers!.first as? String { CCCoreDataStack.sharedInstance.createTask(taskName) CCCoreDataStack.sharedInstance.saveContext() self.setupTable() } } }) } } //MARK: - Misc //The row class with a custom WKInterfaceLabel on it. class TaskRowType: NSObject { @IBOutlet weak var rowDescription: WKInterfaceLabel! }
mit
a3264820d231ad299bc96b0e87d07174
35.163265
105
0.605701
5.142235
false
false
false
false
GitHubOfJW/JavenKit
JavenKit/JWProgressHUD/JWProgressHUD.swift
1
21740
// // JWProgressHUD.swift // CarServer // // Created by 朱建伟 on 2016/11/13. // Copyright © 2016年 zhujianwei. All rights reserved. // import UIKit public enum JWProgressHUDType:Int{ case loading//加载中 case message//提示 case success//成功 case error//失败 case dismiss//隐藏 } public class JWProgressHUD: UIView,CAAnimationDelegate { private let duration:TimeInterval = 0.25 private let selfWidth :CGFloat = UIScreen.main.bounds.width private let selfHeight:CGFloat = UIScreen.main.bounds.height private var currentProgressType:JWProgressHUDType = .dismiss private var nextProgressExcuteType:JWProgressHUDType? private var isDismissDelay:Bool = false //背景层View private let bgCoverView:UIButton = UIButton() //弹出模块 private let containerView:UIView = UIView() //提示文字 private let promptLabel:UILabel = UILabel() //加载中的View private let loadingView:JWProgressHUDLoadingView = JWProgressHUDLoadingView() public override init(frame: CGRect) { super.init(frame: frame) //背景 let rgb:CGFloat = 60.0/255.0 bgCoverView.backgroundColor = UIColor(red: rgb, green: rgb, blue: rgb, alpha: 0.5) bgCoverView.addTarget(self, action: #selector(JWProgressHUD.bgBtnClick(bgBtn:)), for: UIControlEvents.touchUpInside) addSubview(bgCoverView) //弹出模块 containerView.backgroundColor = UIColor.white containerView.layer.cornerRadius = 5.0 containerView.layer.masksToBounds = true // containerView.layer.borderColor = UIColor.orange.cgColor // containerView.layer.borderWidth = 0.5 addSubview(containerView) //提示文字 promptLabel.font = UIFont.systemFont(ofSize: 16) promptLabel.numberOfLines = 0 promptLabel.textColor = UIColor.darkGray promptLabel.textAlignment = NSTextAlignment.center containerView.addSubview(promptLabel) //加载View containerView.addSubview(loadingView) // self.isHidden = true } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //dismiss internal func bgBtnClick(bgBtn:UIButton) { if self.currentProgressType == .dismiss{ self.showMessage(message: "", type: JWProgressHUDType.dismiss,complectionClosure: { }) }else { if bgBtn.tag == 1 { bgBtn.tag = 0 self.showMessage(message: "", type: JWProgressHUDType.dismiss,complectionClosure: {}) }else{ bgBtn.tag = 1 } } } private var complectionClosure:(()->Void)? //展示弹出层 public func showMessage(message:String?,type:JWProgressHUDType){ //展示弹出层 self.showMessage(message:message,type:type,complectionClosure: {}) } //展示弹出层 public func showMessage(message:String?,type:JWProgressHUDType,complectionClosure:@escaping (()->Void)){ if self.currentProgressType == type{ return } if let closure = self.complectionClosure{ closure() } self.complectionClosure = complectionClosure let lastWinidow = UIApplication.shared.keyWindow lastWinidow?.addSubview(self) //几个状态 var tempLoadingViewHidden:Bool = true var tempPromptFrame:CGRect = CGRect() var tempPromptHidden:Bool = false var tempContainerViewFrame:CGRect = CGRect() //结状状态 let loadingViewW:CGFloat = 80 let loadingViewH:CGFloat = 80 let edge:UIEdgeInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) //loadingView loadingView.frame = CGRect(x:edge.left, y: edge.top, width:loadingViewW, height: loadingViewH) //提示文字的最大高度 var promptLabelMaxW:CGFloat = 0 var promptLabelY:CGFloat = 0 if type == .loading { tempLoadingViewHidden = false promptLabelMaxW = loadingViewW promptLabelY = loadingView.frame.maxY + 10 }else if(type == .message){ promptLabelMaxW = selfWidth * 0.8 - edge.left - edge.right promptLabelY = edge.top }else{ tempLoadingViewHidden = false promptLabelMaxW = loadingViewW + edge.left + edge.right promptLabelY = loadingView.frame.maxY } tempPromptHidden = true //有值则布局 if let msg = message{ //不为“”则展示 if msg.compare("") != ComparisonResult.orderedSame{ //高度 let promptSize:CGSize = NSString(string: msg).boundingRect(with: CGSize(width:promptLabelMaxW,height:selfHeight), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:promptLabel.font], context: nil).size var promptLabelH:CGFloat = promptSize.height + 2 //当行高度 if promptLabelH < 20 { promptLabelH = 20 } var promptLabelW:CGFloat = promptSize.width if promptLabelW < loadingViewW { promptLabelW = loadingViewW } //提示文字 tempPromptFrame = CGRect(x:edge.left, y: promptLabelY, width: promptLabelW, height: promptLabelH) tempPromptHidden = false } } //计算container宽度 let containerW:CGFloat = tempPromptHidden == false ? (tempPromptFrame.width + edge.left + edge.right):(loadingView.bounds.width + edge.left + edge.right) //计算container高度 let containerH:CGFloat = ( tempPromptHidden ? loadingView.frame.maxY : tempPromptFrame.maxY ) + edge.bottom tempContainerViewFrame = CGRect(x: (selfWidth - containerW)*0.5, y: ((selfHeight) - containerH)*0.5, width: containerW, height: containerH) let animation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale") animation.delegate = self animation.duration = self.duration animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false animation.autoreverses = false let opacityAnim:CABasicAnimation = CABasicAnimation(keyPath: "opacity") opacityAnim.fillMode = kCAFillModeForwards opacityAnim.isRemovedOnCompletion = false opacityAnim.autoreverses = false //清空 self.nextProgressExcuteType = nil self.isDismissDelay = false //如果是dismiss if type == .dismiss && self.currentProgressType != .dismiss{ if self.currentProgressType == .loading{ //缓解dimss的问题 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {//loading 延时消失 if self.isDismissDelay{ self.containerView.layer.removeAllAnimations() //执行弹出 animation.values = [1.0,1.2,1.0,0.5] self.containerView.layer.add(animation, forKey: String(format:"%zd",type.rawValue)) //隐藏 opacityAnim.toValue = 0 self.bgCoverView.layer.add(opacityAnim, forKey: "opacity") self.currentProgressType = .dismiss } }) return; } self.containerView.layer.removeAllAnimations() //执行弹出 animation.values = [1.0,1.2,1.0,0.5] self.containerView.layer.add(animation, forKey: String(format:"%zd",type.rawValue)) //隐藏 opacityAnim.toValue = 0 self.bgCoverView.layer.add(opacityAnim, forKey: "opacity") self.currentProgressType = .dismiss return } //根据当前的类型选择动画 switch self.currentProgressType { case .loading: //如果将要弹出状态不是加载状态 if type != .loading{ //如果是dismiss则隐藏 if type == .dismiss{ //缓解dimss的问题 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {//loading延时消失 if self.isDismissDelay{ self.showMessage(message: "消失", type: JWProgressHUDType.dismiss) } }) return }else{ //延时消失 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {//loading延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { //通知 loadingView 停止loading动画 并切换状态 self.loadingView.loadingType = type self.containerView.layer.removeAllAnimations() self.promptLabel.text = !tempPromptHidden ? message ?? "" : "" self.isHidden = false UIView.animate(withDuration: self.duration, animations: { self.loadingView.isHidden = tempLoadingViewHidden self.promptLabel.frame = tempPromptFrame self.promptLabel.isHidden = tempPromptHidden self.containerView.frame = tempContainerViewFrame }, completion: { (finished) in //如果直接结束的时候出现新的动画 则不能开启dimiss if let nextExcuteType = self.nextProgressExcuteType { self.showMessage(message: message, type: nextExcuteType) return }else{ var delay:TimeInterval = 1.2; if let msg = message{ delay = TimeInterval((msg.characters.count)) * 0.04 } //延时消失 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.duration + delay, execute: {//message延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { self.showMessage(message: "消失", type: JWProgressHUDType.dismiss) } }) } }) } }) } break }else{ self.isDismissDelay = false fallthrough } case .success: fallthrough case .error: fallthrough case .message: //如果将要弹出状态不是加载状态 if type == .loading || type == .success || type == .error{ promptLabel.text = !tempPromptHidden ? message ?? "" : "" self.loadingView.loadingType = type //开启延时隐藏 if type != .loading{ //延时消失 self.isDismissDelay = true var delay:TimeInterval = 1.2; if let msg = message{ delay = TimeInterval((msg.characters.count)) * 0.04 } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.duration + delay, execute: {//message延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { self.isHidden = false self.containerView.layer.removeAllAnimations() UIView.animate(withDuration: self.duration, animations: { self.loadingView.isHidden = tempLoadingViewHidden self.promptLabel.frame = tempPromptFrame self.promptLabel.isHidden = tempPromptHidden self.containerView.frame = tempContainerViewFrame }, completion: { (finished) in //若果直接结束的时候出现新的动画 则不能开启dimiss if let nextExcuteType = self.nextProgressExcuteType { self.showMessage(message: message, type: nextExcuteType) return }else{ //通知 loadingView 开启loading动画 并切换状态 self.loadingView.loadingType = type } }) } }) return } self.isDismissDelay = false self.containerView.layer.removeAllAnimations() //弹出错误或者成功 self.isHidden = false UIView.animate(withDuration: duration, animations: { self.loadingView.isHidden = tempLoadingViewHidden self.promptLabel.frame = tempPromptFrame self.promptLabel.isHidden = tempPromptHidden self.containerView.frame = tempContainerViewFrame }, completion: { (finished) in //若果直接结束的时候出现新的动画 则不能开启dimiss if let nextExcuteType = self.nextProgressExcuteType { self.showMessage(message: message, type: nextExcuteType) return }else{ //通知 loadingView 开启loading动画 并切换状态 self.loadingView.loadingType = type } //开启延时隐藏 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.duration + 1, execute: {//成功失败延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { self.showMessage(message: "消失", type: JWProgressHUDType.dismiss) } }) }) }else if type == .dismiss{ //如果是dismiss 不用操作,自动隐藏 //移除所有的动画 self.containerView.layer.removeAllAnimations() promptLabel.text = !tempPromptHidden ? message ?? "" : "" self.loadingView.loadingType = type //执行弹出 animation.values = [1.0,1.2,1.0,0.5] containerView.layer.add(animation, forKey: String(format:"%zd",type.rawValue)) //隐藏 // opacityAnim.fromValue = 1 opacityAnim.toValue = 0 self.bgCoverView.layer.add(opacityAnim, forKey: "opacity") return }else{ //message //设置好控件的状态 self.loadingView.isHidden = tempLoadingViewHidden self.promptLabel.frame = tempPromptFrame self.promptLabel.isHidden = tempPromptHidden self.containerView.frame = tempContainerViewFrame promptLabel.text = !tempPromptHidden ? message ?? "" : "" self.loadingView.loadingType = type self.containerView.layer.removeAllAnimations() //执行弹出 animation.values = [0.5,1.2,0.8,1.0] containerView.layer.add(animation, forKey: String(format:"%zd",type.rawValue)) //隐藏 // opacityAnim.fromValue = 0 opacityAnim.toValue = 1 self.bgCoverView.layer.add(opacityAnim, forKey: "opacity") self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration + 1, execute: {//成功失败延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { self.showMessage(message: "消失", type: JWProgressHUDType.dismiss) } }) } break case .dismiss://dismiss状态下,直接弹出提示 if type != .dismiss{ //设置好控件的状态 self.loadingView.isHidden = tempLoadingViewHidden self.promptLabel.frame = tempPromptFrame self.promptLabel.isHidden = tempPromptHidden self.containerView.frame = tempContainerViewFrame promptLabel.text = !tempPromptHidden ? message ?? "" : "" self.loadingView.loadingType = type self.containerView.layer.removeAllAnimations() //动画切换 animation.values = [0.5,1.2,0.8,1.0] containerView.layer.add(animation, forKey: String(format:"%zd",type.rawValue)) //隐藏 // opacityAnim.fromValue = 0 opacityAnim.toValue = 1 self.bgCoverView.layer.add(opacityAnim, forKey: "opacity") //如果不等于loading 延时消失 if type != .loading{ //延时消失 self.isDismissDelay = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration + 1, execute: {//成功失败延时消失 //如果当前动画还是dismiss 则执行 if self.isDismissDelay { self.showMessage(message: "消失", type: JWProgressHUDType.dismiss) return } }) }else{ self.isDismissDelay = false } } break } self.currentProgressType = type } public func animationDidStart(_ anim: CAAnimation) { self.isHidden = false } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if self.currentProgressType == .dismiss { self.isHidden = true if let closure = self.complectionClosure{ closure() } }else{ self.isHidden = false } } //布局 override public func layoutSubviews() { super.layoutSubviews() let x:CGFloat = 0 let y:CGFloat = 0 let w:CGFloat = selfWidth let h:CGFloat = selfHeight let rect:CGRect = CGRect(x: x, y: y, width: w, height: h) self.frame = rect//UIScreen.main.bounds bgCoverView.frame = rect// self.bounds } } public let JavenHUD:JWProgressHUD = JWProgressHUD()
mit
56713f565b744c75dd559f1c74dce278
37.480519
257
0.479051
5.611742
false
false
false
false
TG908/iOS
TUM Campus App/MovieDetailTableViewController.swift
1
3880
// // MovieDetailTableViewController.swift // TUM Campus App // // Created by Mathias Quintero on 12/6/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import UIKit import AYSlidingPickerView class MovieDetailTableViewController: UITableViewController, DetailView { @IBOutlet weak var posterView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var runTimeLabel: UILabel! @IBOutlet weak var actorsLabel: UILabel! @IBOutlet weak var genreLabel: UILabel! @IBOutlet weak var directorLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! var pickerView = AYSlidingPickerView() var barItem: UIBarButtonItem? var delegate: DetailViewDelegate? var currentMovie: Movie? { didSet { if let movie = currentMovie { let info = movie.name.components(separatedBy: ": ") titleLabel.text = movie.text dateLabel.text = info[0] title = movie.text yearLabel.text = movie.year.description ratingLabel.text = "★ " + movie.rating.description runTimeLabel.text = movie.runtime.description + " min" genreLabel.text = movie.genre actorsLabel.text = movie.actors directorLabel.text = movie.director descriptionLabel.text = movie.description posterView.image = movie.image tableView.reloadData() } } } var movies = [Movie]() } extension MovieDetailTableViewController: TumDataReceiver { func receiveData(_ data: [DataElement]) { movies.removeAll() for element in data { if let movieElement = element as? Movie { movies.append(movieElement) if currentMovie == nil { currentMovie = movieElement } } } setUpPickerView() } } extension MovieDetailTableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension delegate?.dataManager().getMovies(self) } } extension MovieDetailTableViewController { func showMovies(_ send: AnyObject?) { pickerView.show() barItem?.action = #selector(MovieDetailTableViewController.hideMovies(_:)) barItem?.image = UIImage(named: "collapse") } func hideMovies(_ send: AnyObject?) { pickerView.dismiss() barItem?.action = #selector(MovieDetailTableViewController.showMovies(_:)) barItem?.image = UIImage(named: "expand") } func setUpPickerView() { var items = [AnyObject]() for movie in movies { let item = AYSlidingPickerViewItem(title: movie.name) { (did) in if did { self.currentMovie = movie self.barItem?.action = #selector(MovieDetailTableViewController.showMovies(_:)) self.barItem?.image = UIImage(named: "expand") self.tableView.reloadData() } } items.append(item!) } pickerView = AYSlidingPickerView.sharedInstance() pickerView.mainView = view pickerView.items = items pickerView.selectedIndex = 0 pickerView.closeOnSelection = true barItem = UIBarButtonItem(image: UIImage(named: "expand"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(MovieDetailTableViewController.showMovies(_:))) navigationItem.rightBarButtonItem = barItem } }
gpl-3.0
fbe5f23d23963e3e09f152fa22a4f67b
32.422414
182
0.613877
5.204027
false
false
false
false
cocoascientist/Luna
Luna/View/ContentView.swift
1
3583
// // ContentView.swift // Luna // // Created by Andrew Shepard on 6/9/19. // Copyright © 2019 Andrew Shepard. All rights reserved. // import SwiftUI import Foundation struct ContentView: View { @ObservedObject var provider: ContentProvider var body: some View { StatusView() .background(LinearGradient.lunarGradient) .edgesIgnoringSafeArea(.all) .environmentObject(self.provider) } } struct StatusView: View { @EnvironmentObject var provider: ContentProvider var body: some View { switch self.provider.viewModel { case .loading: return AnyView( LoadingView() ) case .current(let viewModel): return AnyView( LunarView(viewModel: viewModel) ) case .error(let error): return AnyView( ErrorView(error: error) ) } } } struct LoadingView: View { var body: some View { GeometryReader { geometry in return Text("Loading...") .font(.largeTitle) .foregroundColor(Color.white) .frame(width: geometry.size.width, height: geometry.size.height) } } } struct ErrorView: View { let error: Error var body: some View { GeometryReader { geometry in return Text("Error: \(self.error.localizedDescription)") .font(.largeTitle) .foregroundColor(Color.white) .frame(width: geometry.size.width, height: geometry.size.height) } } } struct LunarView: View { let viewModel: ContentViewModel @State private var offset = CGSize.zero var body: some View { return GeometryReader { geometry in ScrollView { VStack(alignment: .leading) { VStack { LunarPhaseView() .frame(width: 175, height: 175) .padding([.bottom], 16) .padding([.leading, .trailing], 90) LunarInfoView(viewModel: self.viewModel.lunarViewModel) } .frame( width: geometry.size.width, height: geometry.size.height - 100, alignment: .center ) LunarRiseSetTimeView(viewModel: self.viewModel.lunarViewModel) .padding([.leading, .trailing, .bottom], 32.0) PhasesView(viewModels: self.viewModel.phaseViewModel) .padding([.bottom], 32.0) } } } } } extension LinearGradient { static var lunarGradient: LinearGradient { let spectrum = Gradient(colors: [ Color(red: 35/255, green: 37/255, blue: 38/255), Color(red: 65/255, green: 67/255, blue: 69/255) ] ) let gradient = LinearGradient(gradient: spectrum, startPoint: .top, endPoint: .bottom) return gradient } } #if DEBUG struct ContentView_Previews : PreviewProvider { var session: URLSession { let configuration = URLSessionConfiguration.configurationWithProtocol(LocalURLProtocol.self) let session = URLSession(configuration: configuration) return session } static var previews: some View { ContentView(viewModel: ContentViewModel(session: session)) } } #endif
mit
07755346c0f75b0543e151d1fbc04f6f
27.887097
100
0.542714
4.988858
false
false
false
false
edx/edx-app-ios
Source/JSONFormBuilderTextEditor.swift
1
3057
// // JSONFormBuilderTextEditor.swift // edX // // Created by Michael Katz on 10/1/15. // Copyright © 2015 edX. All rights reserved. // import Foundation // Server has limit of 300 characters for bio private let BioTextMaxLimit = 300 class JSONFormBuilderTextEditorViewController: UIViewController { let textView = OEXPlaceholderTextView() var text: String { return textView.text } var doneEditing: ((_ value: String)->())? init(text: String?, placeholder: String?) { super.init(nibName: nil, bundle: nil) self.view = UIView() view.backgroundColor = OEXStyles.shared().standardBackgroundColor() navigationItem.backBarButtonItem?.title = " " textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = OEXStyles.shared().standardTextViewInsets textView.typingAttributes = OEXStyles.shared().textAreaBodyStyle.attributes.attributedKeyDictionary() textView.placeholderTextColor = OEXStyles.shared().neutralBase() textView.textColor = OEXStyles.shared().neutralBlackT() textView.placeholder = placeholder ?? "" textView.text = text ?? "" textView.delegate = self setupViews() setAccessibilityIdentifiers() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) OEXAnalytics.shared().trackScreen(withName: OEXAnalyticsScreenEditTextFormValue) } private func setAccessibilityIdentifiers() { view.accessibilityIdentifier = "JSONFormBuilderTextEditorViewController:view" textView.accessibilityIdentifier = "JSONFormBuilderTextEditorViewController:text-view" } private func setupViews() { view.addSubview(textView) textView.snp.makeConstraints { make in make.top.equalTo(view.snp.topMargin).offset(15) make.leading.equalTo(view.snp.leadingMargin) make.trailing.equalTo(view.snp.trailingMargin) make.bottom.equalTo(view.snp.bottomMargin) } } override func willMove(toParent parent: UIViewController?) { if parent == nil { //removing from the hierarchy doneEditing?(textView.text) } } } extension JSONFormBuilderTextEditorViewController : UITextViewDelegate { func textViewShouldEndEditing(_ textView: UITextView) -> Bool { textView.resignFirstResponder() return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let expectedText = (textView.text as NSString).replacingCharacters(in: range, with: text) if expectedText.count > BioTextMaxLimit { let text: NSString = expectedText as NSString textView.text = text.substring(to: BioTextMaxLimit) } return expectedText.count <= BioTextMaxLimit } }
apache-2.0
fdc22313ead60343097554da5f8d6048
33.337079
116
0.679647
5.170897
false
false
false
false
edx/edx-app-ios
Source/CourseOutlineQuerier.swift
1
24735
// // CourseOutlineQuerier.swift // edX // // Created by Akiva Leffert on 5/4/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct BlockCompletionObserver: Equatable { var controller: UIViewController var blockID: CourseBlockID var mode: CourseOutlineMode var delegate: BlockCompletionDelegate static func == (lhs: BlockCompletionObserver, rhs: BlockCompletionObserver) -> Bool { return lhs.blockID == rhs.blockID } } protocol BlockCompletionDelegate { func didCompletionChanged(in blockGroup: CourseOutlineQuerier.BlockGroup, mode: CourseOutlineMode) } private enum TraversalDirection { case Forward case Reverse } public class CourseOutlineQuerier : NSObject { public struct GroupItem { public let block : CourseBlock public let nextGroup : CourseBlock? public let prevGroup : CourseBlock? public let parent : CourseBlockID init(sourceCursor : ListCursor<CourseBlock>, contextCursor : ListCursor<BlockGroup>) { block = sourceCursor.current nextGroup = sourceCursor.hasNext ? nil : contextCursor.peekNext()?.block prevGroup = sourceCursor.hasPrev ? nil : contextCursor.peekPrev()?.block parent = contextCursor.current.block.blockID } } public struct BlockGroup { public let block : CourseBlock public let children : [CourseBlock] } public typealias Environment = OEXConfigProvider private var environment : Environment? public private(set) var courseID : String private let enrollmentManager: EnrollmentManager? private var interface : OEXInterface? private let networkManager : NetworkManager? private let session : OEXSession? private let courseOutline : BackedStream<CourseOutline> = BackedStream() let courseCelebrationModalStream = BackedStream<(CourseCelebrationModel)>() public var needsRefresh : Bool = false private var observers: [BlockCompletionObserver] = [] func add(observer: BlockCompletionObserver) { if let index = observers.firstIndexMatching({ $0.controller === observer.controller && $0.blockID == observer.blockID }) { observers.remove(at: index) } observers.append(observer) } func remove(observer: UIViewController) { let filtered = observers.filter { $0.controller !== observer } observers = [] observers.append(contentsOf: filtered) } private var blocks: [CourseBlockID : CourseBlock] = [:] { didSet { subscribeToBlockCompletion() } } public init(courseID : String, interface : OEXInterface?, enrollmentManager: EnrollmentManager?, networkManager : NetworkManager?, session : OEXSession?, environment: Environment) { self.courseID = courseID self.interface = interface self.enrollmentManager = enrollmentManager self.networkManager = networkManager self.session = session self.environment = environment super.init() addListener() addObservers() } /// Use this to create a querier with an existing outline. /// Typically used for tests public init(courseID : String, outline : CourseOutline) { self.courseOutline.backWithStream(OEXStream(value : outline)) self.courseID = courseID self.enrollmentManager = nil self.interface = nil self.networkManager = nil self.session = nil super.init() addListener() addObservers() } // Use this to create a querier with interface and outline. // Typically used for tests convenience public init(courseID : String, interface : OEXInterface?, outline : CourseOutline) { self.init(courseID: courseID, outline: outline) self.interface = interface } private func subscribeToBlockCompletion() { blocks.forEach { item in let block = item.value guard let parent = parentOfBlockWith(id: block.blockID).firstSuccess().value else { return } handleDiscussionBlockIfNeeded(parent: parent) if case CourseBlockType.Video = block.type { handleVideoBlockIfNeeded(parent: parent) } block.completion.subscribe(observer: self) { [weak self] value, _ in guard let weakSelf = self else { return } let allCompleted = parent.children.allSatisfy { [weak self] childID in return self?.blockWithID(id: childID).firstSuccess().value?.isCompleted ?? false } if allCompleted { if !parent.isCompleted { parent.isCompleted = true } weakSelf.observers.forEach { observer in if observer.blockID == parent.blockID { let children = parent.children.compactMap { [weak self] childID in return self?.blockWithID(id: childID).firstSuccess().value } let blockGroup = BlockGroup(block: parent, children: children) observer.delegate.didCompletionChanged(in: blockGroup, mode: observer.mode) } } } weakSelf.handleVideoBlockIfNeeded(parent: parent) weakSelf.handleDiscussionBlockIfNeeded(parent: parent) } } } private func handleDiscussionBlockIfNeeded(parent: CourseBlock) { if parent.type != .Unit { return } let allBlocksAreCompleted = parent.children.compactMap { blockWithID(id: $0).firstSuccess().value } .allSatisfy { $0.isCompleted } if !allBlocksAreCompleted { let otherBlocks = parent.children.filter { blockID -> Bool in guard let childBlock = blockWithID(id: blockID).value, case CourseBlockType.Discussion = childBlock.type else { return true } return false }.compactMap { blockWithID(id: $0).firstSuccess().value } let discussionBlocks = parent.children.filter { blockID -> Bool in guard let childBlock = blockWithID(id: blockID).value, case CourseBlockType.Discussion = childBlock.type else { return false } return true }.compactMap { blockWithID(id: $0).firstSuccess().value } if !otherBlocks.isEmpty { let otherBlocksAreCompleted = otherBlocks.allSatisfy { $0.isCompleted } if otherBlocksAreCompleted { for block in discussionBlocks { if !block.isCompleted { block.isCompleted = true break } } } } else { for block in discussionBlocks { if !block.isCompleted { block.isCompleted = true break } } } } } private func handleVideoBlockIfNeeded(parent: CourseBlock, observer: BlockCompletionObserver? = nil) { if parent.type != .Unit { return } let childVideoBlocks = parent.children.compactMap { [weak self] item -> CourseBlock? in guard let block = self?.blockWithID(id: item, mode: .video).value else { return nil } if case CourseBlockType.Video = block.type { return block } return nil } if childVideoBlocks.isEmpty { return } let allCompleted = childVideoBlocks.allSatisfy { $0.isCompleted } if allCompleted { if !parent.isCompleted { parent.isCompleted = true } observers.forEach { observer in if observer.blockID == parent.blockID { let blockGroup = BlockGroup(block: parent, children: childVideoBlocks) observer.delegate.didCompletionChanged(in: blockGroup, mode: observer.mode) } } } } private func addObservers() { NotificationCenter.default.oex_addObserver(observer: self, name: NSNotification.Name.OEXSessionStarted.rawValue) { (notification, observer, _) -> Void in observer.needsRefresh = true } } private func addListener() { courseOutline.listen(self, success : {[weak self] outline in self?.loadedNodes(blocks: outline.blocks) }, failure : { _ in } ) } private func loadedNodes(blocks: [CourseBlockID : CourseBlock]) { self.blocks = blocks var videos : [OEXVideoSummary] = [] for (_, block) in blocks { switch block.type { case let .Video(video): videos.append(video) default: break } } interface?.addVideos(videos, forCourseWithID: courseID) } private func loadOutlineIfNecessary() { if (courseOutline.value == nil || needsRefresh) && !courseOutline.active { needsRefresh = false if let enrollment = enrollmentManager?.enrolledCourseWithID(courseID: courseID), let access = enrollment.course.courseware_access, !access.has_access { let stream = OEXStream<CourseOutline>(error: OEXCoursewareAccessError(coursewareAccess: access, displayInfo: enrollment.course.start_display_info)) courseOutline.backWithStream(stream) } else { let request = CourseOutlineAPI.requestWithCourseID(courseID: courseID, username : session?.currentUser?.username, environment: environment as? RouterEnvironment) if let loader = networkManager?.streamForRequest(request, persistResponse: true) { courseOutline.backWithStream(loader) } } loadCelebrationStream() } } private func loadCelebrationStream() { let courseCelebrationModalRequest = CelebratoryAPI.celebrationModalViewedStatus(courseID: courseID) if let celebrationModalStream = networkManager?.streamForRequest(courseCelebrationModalRequest) { courseCelebrationModalStream.backWithStream(celebrationModalStream) } } func updateCelebrationModalStatus(firstSection: Bool) { guard let username = session?.currentUser?.username else { return } let networkRequest = CelebratoryAPI.celebratoryModalViewed(username: username, courseID: courseID, isFirstSectionViewed: false) networkManager?.taskForRequest(networkRequest) {[weak self] _ in self?.loadCelebrationStream() } } public var rootID: OEXStream<CourseBlockID> { loadOutlineIfNecessary() return courseOutline.map { return $0.root } } public func spanningCursorForBlockWithID(blockID: CourseBlockID?, initialChildID: CourseBlockID?, forMode mode: CourseOutlineMode) -> OEXStream<ListCursor<GroupItem>> { loadOutlineIfNecessary() return courseOutline.flatMap { [weak self] outline in if let blockID = blockID, let child = initialChildID ?? self?.blockWithID(id: blockID, inOutline: outline)?.children.first, let groupCursor = self?.cursorForLeafGroupsAdjacentToBlockWithID(blockID: blockID, forMode: mode, inOutline: outline), let flatCursor = self?.flattenGroupCursor(groupCursor: groupCursor, startingAtChild: child) { return Success(v: flatCursor) } else { return Failure(e: NSError.oex_courseContentLoadError()) } } } private func depthOfBlockWithID(blockID: CourseBlockID, inOutline outline: CourseOutline) -> Int? { var depth = 0 var current = blockID while let parent = outline.parentOfBlockWithID(blockID: current), current != outline.root { current = parent depth = depth + 1 } return depth } // Returns all groups before (or after if direction is .Reverse) the given block at its same tree depth private func leafGroupsFromDirection(direction : TraversalDirection, forBlockWithID blockID : CourseBlockID, forMode mode: CourseOutlineMode, inOutline outline : CourseOutline) -> [BlockGroup] { var queue : [(blockID : CourseBlockID, depth : Int)] = [] let root = (blockID : outline.root, depth : 0) queue.append(root) let depth : Int if let d = depthOfBlockWithID(blockID: blockID, inOutline : outline) { depth = d } else { // block not found so just return empty return [] } // Do a basic breadth first traversal var groups : [BlockGroup] = [] while let next = queue.last { queue.removeLast() if next.blockID == blockID { break } if let block = blockWithID(id: next.blockID, inOutline: outline) { if next.depth == depth { // Don't add groups with no children since we don't want to display them if let group = childrenOfBlockWithID(blockID: next.blockID, forMode: mode, inOutline: outline), group.children.count > 0 { // Account for the traversal direction. The output should always be left to right switch direction { case .Forward: groups.append(group) case .Reverse: groups.insert(group, at:0) } } // At the correct depth so skip all our children continue } let children : [CourseBlockID] switch direction { case .Forward: children = block.children case .Reverse: children = Array(block.children.reversed()) } for child in children { let item = (blockID : child, depth : next.depth + 1) queue.insert(item, at: 0) } } } return groups } // Turns a list of block groups into a flattened list of blocks with context information private func flattenGroupCursor(groupCursor : ListCursor<BlockGroup>, startingAtChild startChild: CourseBlockID) -> ListCursor<GroupItem>? { let cursor = ListCursor(list: groupCursor.current.children) {child in child.blockID == startChild} ?? ListCursor(startOfList: groupCursor.current.children) if let cursor = cursor { var before : [GroupItem] = [] var after : [GroupItem] = [] // Add the items from the current group let current = GroupItem(sourceCursor: cursor, contextCursor: groupCursor) let cursorBefore = ListCursor(cursor: cursor) cursorBefore.loopToStartExcludingCurrent {(cursor, _) in let item = GroupItem(sourceCursor: cursor, contextCursor: groupCursor) before.append(item) } let cursorAfter = ListCursor(cursor: cursor) cursorAfter.loopToEndExcludingCurrent {(cursor, _) in let item = GroupItem(sourceCursor: cursor, contextCursor: groupCursor) after.append(item) } // Now go through all the other groups let backCursor = ListCursor(cursor: groupCursor) backCursor.loopToStartExcludingCurrent {(contextCursor, _) in let cursor = ListCursor(endOfList: contextCursor.current.children) cursor?.loopToStart {(cursor, _) in let item = GroupItem(sourceCursor: cursor, contextCursor: contextCursor) before.append(item) } } let forwardCursor = ListCursor(cursor: groupCursor) forwardCursor.loopToEndExcludingCurrent {(contextCursor, _) in let cursor = ListCursor(startOfList: contextCursor.current.children) cursor?.loopToEnd {(cursor, _) in let item = GroupItem(sourceCursor: cursor, contextCursor: contextCursor) after.append(item) } } return ListCursor(before: Array(before.reversed()), current: current, after: after) } return nil } private func cursorForLeafGroupsAdjacentToBlockWithID(blockID: CourseBlockID, forMode mode: CourseOutlineMode, inOutline outline: CourseOutline) -> ListCursor<BlockGroup>? { if let current = childrenOfBlockWithID(blockID: blockID, forMode: mode, inOutline: outline) { let before = leafGroupsFromDirection(direction: .Forward, forBlockWithID: blockID, forMode: mode, inOutline: outline) let after = leafGroupsFromDirection(direction: .Reverse, forBlockWithID: blockID, forMode: mode, inOutline: outline) return ListCursor(before: before, current: current, after: after) } else { return nil } } /// for value of CourseBlockType, expected parameters are Course, Chapter, Section or Unit to iterate recursively to find parent of that type public func parentOfBlockWith(id blockID: CourseBlockID, type: CourseBlockType) -> OEXStream<CourseBlock> { loadOutlineIfNecessary() guard type == .Course || type == .Chapter || type == .Section || type == .Unit else { return OEXStream(error: NSError.oex_courseContentLoadError()) } if let block = blockWithID(id: blockID).firstSuccess().value, block.type == type { // type of current block is the type which is passed as parameter return OEXStream(error: NSError.oex_courseContentLoadError()) } guard let parentBlockID = parentOfBlockWithID(blockID: blockID).firstSuccess().value else { return OEXStream(error: NSError.oex_courseContentLoadError()) } let blockStream = blockWithID(id: parentBlockID).firstSuccess() guard let value = blockStream.value else { return OEXStream(error: NSError.oex_courseContentLoadError()) } return value.type == type ? blockStream : parentOfBlockWith(id: value.blockID, type: type) } /// parentOfBlockWith returns Stream containing CourseBlock public func parentOfBlockWith(id blockID: CourseBlockID) -> OEXStream<CourseBlock> { loadOutlineIfNecessary() return parentOfBlockWithID(blockID: blockID).flatMap { [weak self] id -> Result<CourseBlock> in if let block = self?.blockWithID(id: id).firstSuccess().value { return Success(v: block) } else { return Failure(e: NSError.oex_courseContentLoadError()) } } } /// parentOfBlockWithID returns Stream containing CourseBlockID public func parentOfBlockWithID(blockID: CourseBlockID) -> OEXStream<CourseBlockID?> { loadOutlineIfNecessary() return courseOutline.flatMap {(outline: CourseOutline) -> Result<CourseBlockID?> in if blockID == outline.root { return Success(v: nil) } else { if let blockID = outline.parentOfBlockWithID(blockID: blockID) { return Success(v: blockID) } else { return Failure(e: NSError.oex_courseContentLoadError()) } } } } /// Loads all the children of the given block. /// nil means use the course root. public func childrenOfBlockWithID(blockID: CourseBlockID?, forMode mode: CourseOutlineMode) -> OEXStream<BlockGroup> { loadOutlineIfNecessary() return courseOutline.flatMap { [weak self] (outline : CourseOutline) -> Result<BlockGroup> in let children = self?.childrenOfBlockWithID(blockID: blockID, forMode: mode, inOutline: outline) return children.toResult(NSError.oex_courseContentLoadError()) } } private func childrenOfBlockWithID(blockID: CourseBlockID?, forMode mode: CourseOutlineMode, inOutline outline: CourseOutline) -> BlockGroup? { if let block = blockWithID(id: blockID ?? outline.root, inOutline: outline) { let blocks = block.children.compactMap({ blockWithID(id: $0, inOutline: outline) }) let filtered = filterBlocks(blocks: blocks, forMode: mode) return BlockGroup(block : block, children : filtered) } else { return nil } } private func filterBlocks(blocks: [CourseBlock], forMode mode: CourseOutlineMode) -> [CourseBlock] { switch mode { case .full: return blocks case .video: return blocks.filter {(block : CourseBlock) -> Bool in return (block.blockCounts[CourseBlock.Category.Video.rawValue] ?? 0) > 0 } } } private func flatMapRootedAtBlockWithID<A>(id : CourseBlockID, inOutline outline : CourseOutline, transform : (CourseBlock) -> [A], accumulator : inout [A]) { if let block = blockWithID(id: id, inOutline: outline) { accumulator.append(contentsOf: transform(block)) for child in block.children { flatMapRootedAtBlockWithID(id: child, inOutline: outline, transform: transform, accumulator: &accumulator) } } } public func flatMapRootedAtBlockWithID<A>(id : CourseBlockID, transform : @escaping (CourseBlock) -> [A]) -> OEXStream<[A]> { loadOutlineIfNecessary() return courseOutline.map {[weak self] outline -> [A] in var result : [A] = [] let blockId = id self?.flatMapRootedAtBlockWithID(id: blockId, inOutline: outline, transform: transform, accumulator: &result) return result } } public func flatMapRootedAtBlockWithID<A>(id : CourseBlockID, transform : @escaping (CourseBlock) -> A?) -> OEXStream<[A]> { return flatMapRootedAtBlockWithID(id: id, transform: { block in return transform(block).map { [$0] } ?? [] }) } public func supportedBlockVideos(forCourseID id: String, blockID: String) -> OEXStream<[OEXHelperVideoDownload]> { let videoStream = flatMapRootedAtBlockWithID(id: blockID) { block in (block.type.asVideo != nil) ? block.blockID : nil } let blockVideos = videoStream.map({[weak self] videoIDs -> [OEXHelperVideoDownload] in let videos = self?.interface?.statesForVideos(withIDs: videoIDs, courseID: self?.courseID ?? "") return videos?.filter { video in (video.summary?.isDownloadableVideo ?? false)} ?? [] }) return blockVideos } /// Loads the given block. /// nil means use the course root. public func blockWithID(id: CourseBlockID?, mode: CourseOutlineMode = .full) -> OEXStream<CourseBlock> { loadOutlineIfNecessary() return courseOutline.flatMap { [weak self] outline in let blockID = id ?? outline.root let block = self?.blockWithID(id: blockID, inOutline: outline, forMode: mode) return block.toResult(NSError.oex_courseContentLoadError()) } } private func blockWithID(id: CourseBlockID, inOutline outline: CourseOutline, forMode mode: CourseOutlineMode = .full) -> CourseBlock? { if let block = outline.blocks[id] { return block } return nil } }
apache-2.0
c4ad8fc0630fbdc42fa2f5f25d89ef49
40.501678
198
0.591429
5.266127
false
false
false
false
linweiqiang/WQDouShi
WQDouShi/Pods/Validator/Validator/Validator/Rules/ValidationRuleContains.swift
6
2435
/* ValidationRulePattern.swift Validator Created by @adamwaite. Copyright (c) 2015 Adam Waite. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation /** `ValidationRuleContains` validates a `Sequence` type `S` contains an `Equatable` type `T` in it's elements. */ public struct ValidationRuleContains<T: Equatable, S: Sequence>: ValidationRule where S.Iterator.Element == T { public typealias InputType = T public let error: Error /** A sequence an input should be contained in to pass as valid. */ public var sequence: S /** Initializes a `ValidationRuleContains` with a sequence an input should be contained in to pass as valid, and an error describing a failed validation. - Parameters: - sequence: A sequence an input should be contained in to pass as valid. - error: An error describing a failed validation. */ public init(sequence: S, error: Error) { self.sequence = sequence self.error = error } /** Validates the input. - Parameters: - input: Input to validate. - Returns: true if the sequence contains the input. */ public func validate(input: T?) -> Bool { guard let input = input else { return false } return sequence.contains(input) } }
mit
62fa933785b93a7c24b442ad39342074
27.313953
111
0.69076
4.821782
false
false
false
false
makingsensetraining/mobile-pocs
IOS/SwiftSeedProject/SwiftSeedProject/Application/ViewModels/NewsFeedViewModel.swift
1
1367
// // NewsFeedViewModel.swift // SwiftSeedProject // // Created by Lucas Pelizza on 4/21/17. // Copyright © 2017 Making Sense. All rights reserved. // import Bond class NewsFeedViewModel { private let libraryService: LibraryService! let newsArticles = MutableObservableArray<ArticleViewModel>() init(libraryService: LibraryService) { self.libraryService = libraryService self.setupNotifications() } private func setupNotifications() { // MARK: Library updated notification NotificationCenter .default .reactive .notification(name: libraryService.getNotificationKeyName()) .observeNext { [weak self] _ in guard let strongSelf = self else { return } strongSelf.getArticlesBy(sourceID: "") } .dispose(in: NotificationCenter.default.reactive.bag) } private func getArticlesBy(sourceID: String) { let library: Library? = libraryService.getEntityBy(source: sourceID) if let library = library { newsArticles.replace(with: library.articles!.map { ArticleViewModel(article: $0 as! Article) }) } } func requestNewsArticlesFromServer() { libraryService.updateLocalStoreWithServerInfo() } }
mit
ed61f833e11078d842d8f502df782317
28.695652
107
0.624451
4.967273
false
false
false
false
ReSwift/ReactiveReSwift
Tests/Observable/StoreTests.swift
1
1658
// // ObservableStoreTests.swift // ReactiveReSwift // // Created by Charlotte Tortorella on 25/11/16. // Copyright © 2015 DigiTales. All rights reserved. // import XCTest @testable import ReactiveReSwift class ObservableStoreTests: XCTestCase { /** it deinitializes when no reference is held */ func testDeinit() { var deInitCount = 0 autoreleasepool { _ = DeInitStore(reducer: testReducer, observable: ObservableProperty(TestAppState()), deInitAction: { deInitCount += 1 }) } XCTAssertEqual(deInitCount, 1) } } // Used for deinitialization test class DeInitStore<State>: Store<ObservableProperty<State>> { var deInitAction: (() -> Void)? deinit { deInitAction?() } convenience init(reducer: @escaping Reducer<ObservableProperty<State>.ValueType>, observable: ObservableProperty<State>, middleware: Middleware<ObservableProperty<State>.ValueType> = Middleware(), deInitAction: @escaping () -> Void) { self.init(reducer: reducer, observable: observable, middleware: middleware) self.deInitAction = deInitAction } required init(reducer: @escaping Reducer<ObservableProperty<State>.ValueType>, observable: ObservableProperty<State>, middleware: Middleware<ObservableProperty<State>.ValueType>) { super.init(reducer: reducer, observable: observable, middleware: middleware) } }
mit
196f95783b5fdde0e88a0d68608bc369
28.589286
93
0.600483
5.021212
false
true
false
false
macostea/appcluj-expenses-ios
Expenses/Expenses/ViewController.swift
1
3508
// // ViewController.swift // Expenses // // Created by Mihai Costea on 09/12/14. // Copyright (c) 2014 Mihai Costea. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ViewController: UITableViewController, AddExpenseViewControllerDelegate { var expenses: [Expense]? override func viewDidLoad() { super.viewDidLoad() self.requestExpenses() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "addExpense" { let addExpenseViewController = segue.destinationViewController as AddExpenseViewController addExpenseViewController.delegate = self } } // MARK:- UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.expenses?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("expenseCell", forIndexPath: indexPath) as UITableViewCell if self.expenses != nil { cell.textLabel?.text = self.expenses![indexPath.row].type cell.detailTextLabel?.text = "\(self.expenses![indexPath.row].amount)" } return cell } // MARK:- UITableViewDelegate override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if let expenses = self.expenses { if editingStyle == .Delete { Alamofire.request(Router.DeleteExpense(expenses[indexPath.row].expenseId!)).responseSwiftyJSON({ (request, response, json, error) -> Void in if error != nil { println(error) return } self.requestExpenses() }) } } } // MARK:- AddExpenseViewControllerDelegate func addExpenseViewController(addExpenseViewController: AddExpenseViewController, didCreateExpense expense: Expense) { addExpenseViewController.dismissViewControllerAnimated(true, completion: nil) self.addExpense(expense) } // MARK:- Private private func requestExpenses() { Alamofire.request(Router.GetAll).responseSwiftyJSON { (request, response, json, error) -> Void in if (error != nil) { println(error) return } self.expenses = [Expense]() for item in json { if let expense = Expense.expenseFromJSON(item.1) { self.expenses?.append(expense) } } self.tableView.reloadData() } } private func addExpense(expense: Expense) { Alamofire.request(Router.CreateExpense(expense.toDictionary())).responseSwiftyJSON { (request, response, json, error) -> Void in if (error != nil) { println(error) return } self.requestExpenses() } } // MARK:- Actions @IBAction func editButtonPressed(sender: UIBarButtonItem) { self.tableView.setEditing(!self.tableView.editing, animated: true) } }
mit
c580cb2e934a93f50af3af0ac557800a
31.183486
157
0.597491
5.704065
false
false
false
false
FindGF/_BiliBili
WTBilibili/Other-其他/Extension-扩展/String-Extension.swift
1
1455
// // String-Extension.swift // WTBilibili // // Created by 耿杰 on 16/5/4. // Copyright © 2016年 无头骑士 GJ. All rights reserved. // import Foundation extension String { // MARK: - 正则验证 // MARK: 自己写正则表达式验证 public func matchesRegex(regex: String, options: NSRegularExpressionOptions) -> Bool { do { let pattern = try NSRegularExpression(pattern: regex, options: .CaseInsensitive) return pattern.numberOfMatchesInString(self, options: NSMatchingOptions.Anchored, range: NSRange(location: 0, length: self.characters.count)) > 0 } catch{ print("error\(error)") return false } } // MARK: 是否全是数字 public func matchesAllNumber() -> Bool { return matchesRegex("^\\d*$", options: .CaseInsensitive) } } extension String { public func md5() ->String!{ let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(format: hash as String) } }
apache-2.0
a895ad40cf59a638a73bed5e8b82ad34
27.591837
157
0.625714
4.307692
false
false
false
false
tombuildsstuff/ios-language-love
LanguagePicker/Controllers/Languages/LanguageViewController.swift
1
2717
// // LanguageViewController.swift // LanguagePicker // // Created by Tom Harvey on 13/04/2015. // Copyright (c) 2015 Tom Harvey. All rights reserved. // import UIKit import LanguagePickerCore import Social class LanguageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView : UITableView?; let cellIdentifier = "LanguageCell"; let languagesRepository : ILanguagesRepository = RepositoryFactory.languages(); var languages : [String]?; // MARK: Initialisers required init() { super.init(nibName: "Languages", bundle: nil); } convenience required init(coder: NSCoder) { fatalError("NSCoding not supported") } // MARK: UIViewController override func viewDidLoad() { self.languages = self.languagesRepository.getAll(); self.tableView?.registerNib(UINib(nibName: self.cellIdentifier, bundle: nil), forCellReuseIdentifier: self.cellIdentifier); super.viewDidLoad(); } // MARK: UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath) as! UITableViewCell; if let languageCell = cell as? LanguageCell { if let language = self.languageAtIndexPath(indexPath) { languageCell.configure(language); } } return cell; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.languages?.count ?? 0; } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true); if let language = self.languageAtIndexPath(indexPath) { let viewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter); viewController.setInitialText("Have I ever mentioned how much I *love* \(language)"); self.navigationController?.presentViewController(viewController, animated: true, completion: nil); } } // MARK: Private methods private func languageAtIndexPath(indexPath: NSIndexPath) -> String? { if let languages = self.languages { if languages.count >= indexPath.row { return languages[indexPath.row]; } } return nil; } }
mit
ae4bb4d59fb2f63f1b644b239277dfff
32.54321
131
0.661023
5.533605
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/RequestJoinChatRowItem.swift
1
5055
// // RequestJoinChatRowItem.swift // Telegram // // Created by Mikhail Filimonov on 01.10.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import Postbox import TelegramCore final class RequestJoinChatRowItem : GeneralRowItem { fileprivate let context: AccountContext fileprivate let titleLayout: TextViewLayout fileprivate let statusLayout: TextViewLayout fileprivate let aboutLayout: TextViewLayout? fileprivate let photo: TelegramMediaImageRepresentation? fileprivate let peer: Peer init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, photo: TelegramMediaImageRepresentation?, title: String, about: String?, participantsCount: Int, isChannelOrMegagroup: Bool, viewType: GeneralViewType) { self.context = context self.photo = photo self.titleLayout = TextViewLayout(.initialize(string: title, color: theme.colors.text, font: .medium(.header)), maximumNumberOfLines: 1, truncationType: .middle) self.peer = TelegramGroup(id: PeerId(namespace: Namespaces.Peer.CloudGroup, id: PeerId.Id._internalFromInt64Value(0)), title: title, photo: [photo].compactMap { $0 }, participantCount: 0, role: .member, membership: .Left, flags: [], defaultBannedRights: nil, migrationReference: nil, creationDate: 0, version: 0) let countText: String if isChannelOrMegagroup { countText = strings().peerStatusSubscribersCountable(participantsCount).replacingOccurrences(of: "\(participantsCount)", with: participantsCount.formattedWithSeparator) } else { countText = strings().peerStatusMemberCountable(participantsCount).replacingOccurrences(of: "\(participantsCount)", with: participantsCount.formattedWithSeparator) } self.statusLayout = TextViewLayout(.initialize(string: countText, color: theme.colors.grayText, font: .normal(.text)), alignment: .center) if let about = about { self.aboutLayout = TextViewLayout(.initialize(string: about, color: theme.colors.text, font: .normal(.text)), alignment: .center) } else { self.aboutLayout = nil } super.init(initialSize, stableId: stableId, viewType: viewType) } override var height: CGFloat { let top = self.viewType.innerInset.top var height = top + 80 + top + self.titleLayout.layoutSize.height + self.statusLayout.layoutSize.height + top if let about = aboutLayout { height += top + about.layoutSize.height } return height } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) self.titleLayout.measure(width: blockWidth - viewType.innerInset.left - viewType.innerInset.right) self.statusLayout.measure(width: blockWidth - viewType.innerInset.left - viewType.innerInset.right) self.aboutLayout?.measure(width: blockWidth - viewType.innerInset.left - viewType.innerInset.right) return true } override func viewClass() -> AnyClass { return RequestJoinChatRowView.self } } private final class RequestJoinChatRowView : GeneralContainableRowView { private let avatar: AvatarControl = AvatarControl(font: .avatar(30)) private let titleView = TextView() private let statusView = TextView() private let aboutView = TextView() required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.avatar.setFrameSize(NSMakeSize(80, 80)) addSubview(self.avatar) addSubview(titleView) addSubview(statusView) addSubview(aboutView) titleView.userInteractionEnabled = false titleView.isSelectable = false statusView.userInteractionEnabled = false statusView.isSelectable = false aboutView.userInteractionEnabled = false aboutView.isSelectable = false } override func layout() { super.layout() guard let item = item as? GeneralRowItem else { return } let top = item.viewType.innerInset.top avatar.centerX(y: top) titleView.centerX(y: avatar.frame.maxY + top) statusView.centerX(y: titleView.frame.maxY) aboutView.centerX(y: statusView.frame.maxY + top) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? RequestJoinChatRowItem else { return } self.avatar.setPeer(account: item.context.account, peer: item.peer) self.titleView.update(item.titleLayout) self.statusView.update(item.statusLayout) self.aboutView.update(item.aboutLayout) needsLayout = true } }
gpl-2.0
1689dd1c7fa9a5f405f4adf54905c2aa
38.178295
320
0.673724
4.754468
false
false
false
false
sufangliang/LiangDYZB
LiangDYZB/Classes/Home/ViewModel/RecommendViewModel.swift
1
4660
// // RecommendViewModel.swift // LiangDYZB // // Created by qu on 2017/2/10. // Copyright © 2017年 qu. All rights reserved. // import UIKit class RecommendViewModel: NSObject { // MARK:- 懒加载属性 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() //分组的主播数组 lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup :AnchorGroup = AnchorGroup() } //MARK - 发送网络请求 extension RecommendViewModel{ func requestData(_ finshCallback:@escaping () -> ()) { //定义参数 let parameters = ["limit":"4","offset" : "0", "time" : Date.getCurrentTime()] // 2.创建Group let dGroup = DispatchGroup() // 3.请求第一部分推荐数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime()]) { (result) in // 1.将result转成字典类型 guard let resultDict = result as?[String:NSObject] else{return} print("第一部分推荐数据") // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.遍历字典,并且转成模型对象 // 3.1 设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" for dict in dataArray{ let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } // 3.3.离开组 dGroup.leave() } // 4.请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in print("第二部分推荐数据") // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.遍历字典,并且转成模型对象 // 3.1.设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" // 3.2.获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } // 3.3.离开组 dGroup.leave() } dGroup.enter() NetworkTools.requestData(.get, URLString:"http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in print("第三部分数据") // 1.对界面进行处理 guard let resultDict = result as? [String : Any] else { return } guard let dataArray = resultDict["data"] as? [[String : Any]] else { return } // 2.判断是否分组数据 // 2.1.遍历数组中的字典 for dict in dataArray { self.anchorGroups.append(AnchorGroup(dict: dict)) } dGroup.leave() } // 6.所有的数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finshCallback() } } // 请求无线轮播的数据 func requestCycleData(_ finishCallback : @escaping () -> ()) { NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in print("轮播数据\(result)") // 1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } finishCallback() } } }
mit
87ec4b9fcab8725288427d7a4f6ca8b8
31.19084
158
0.527863
4.573753
false
false
false
false
natecook1000/swift
test/SILGen/functions.swift
3
29023
// RUN: %target-swift-emit-silgen -module-name functions -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -enable-sil-ownership %s | %FileCheck %s import Swift // just for Optional func markUsed<T>(_ t: T) {} typealias Int = Builtin.Int64 typealias Int64 = Builtin.Int64 typealias Bool = Builtin.Int1 var zero = getInt() func getInt() -> Int { return zero } func standalone_function(_ x: Int, _ y: Int) -> Int { return x } func higher_order_function(_ f: (_ x: Int, _ y: Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } func higher_order_function2(_ f: (Int, Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } struct SomeStruct { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc init(x:Int, y:Int) {} mutating func method(_ x: Int) {} static func static_method(_ x: Int) {} func generic_method<T>(_ x: T) {} } class SomeClass { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc // CHECK-LABEL: sil hidden @$S9functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @trivial $@thick SomeClass.Type): // CHECK-LABEL: sil hidden @$S9functions9SomeClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Builtin.Int64, Builtin.Int64, @owned SomeClass) -> @owned SomeClass // CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @owned $SomeClass): init(x:Int, y:Int) {} // CHECK-LABEL: sil hidden @$S9functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @guaranteed $SomeClass): func method(_ x: Int) {} // CHECK-LABEL: sil hidden @$S9functions9SomeClassC13static_method{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Builtin.Int64, @thick SomeClass.Type) -> () // CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $@thick SomeClass.Type): class func static_method(_ x: Int) {} var someProperty: Int { get { return zero } set {} } subscript(x:Int, y:Int) -> Int { get { return zero } set {} } func generic<T>(_ x: T) -> T { return x } } func SomeClassWithBenefits() -> SomeClass.Type { return SomeClass.self } protocol SomeProtocol { func method(_ x: Int) static func static_method(_ x: Int) } struct ConformsToSomeProtocol : SomeProtocol { func method(_ x: Int) { } static func static_method(_ x: Int) { } } class SomeGeneric<T> { init() { } func method(_ x: T) -> T { return x } func generic<U>(_ x: U) -> U { return x } } // CHECK-LABEL: sil hidden @$S9functions5calls{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> () func calls(_ i:Int, j:Int, k:Int) { var i = i var j = j var k = k // CHECK: bb0(%0 : @trivial $Builtin.Int64, %1 : @trivial $Builtin.Int64, %2 : @trivial $Builtin.Int64): // CHECK: [[IBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[IADDR:%.*]] = project_box [[IBOX]] // CHECK: [[JBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[JADDR:%.*]] = project_box [[JBOX]] // CHECK: [[KBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[KADDR:%.*]] = project_box [[KBOX]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @$S9functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: apply [[FUNC]]([[I]], [[J]]) standalone_function(i, j) // -- Curry 'self' onto struct method argument lists. // CHECK: [[ST_ADDR:%.*]] = alloc_box ${ var SomeStruct } // CHECK: [[METATYPE:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%.*]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%.*]] = load [trivial] [[READJ]] // CHECK: [[CTOR:%.*]] = function_ref @$S9functions10SomeStructV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct // CHECK: apply [[CTOR]]([[I]], [[J]], [[METATYPE]]) : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct var st = SomeStruct(x: i, y: j) // -- Use of unapplied struct methods as values. // CHECK: [[THUNK:%.*]] = function_ref @$S9functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F // CHECK: [[THUNK_THICK:%.*]] = thin_to_thick_function [[THUNK]] var stm1 = SomeStruct.method stm1(&st)(i) // -- Curry 'self' onto method argument lists dispatched using class_method. // CHECK: [[CBOX:%[0-9]+]] = alloc_box ${ var SomeClass } // CHECK: [[CADDR:%.*]] = project_box [[CBOX]] // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @$S9functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: [[C:%[0-9]+]] = apply [[FUNC]]([[I]], [[J]], [[META]]) var c = SomeClass(x: i, y: j) // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.method!1 // CHECK: apply [[METHOD]]([[I]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] c.method(i) // -- Curry 'self' onto unapplied methods dispatched using class_method. // CHECK: [[METHOD_CURRY_THUNK:%.*]] = function_ref @$S9functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F // CHECK: apply [[METHOD_CURRY_THUNK]] var cm1 = SomeClass.method(c) cm1(i) // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.method!1 // CHECK: apply [[METHOD]]([[I]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] SomeClass.method(c)(i) // -- Curry the Type onto static method argument lists. // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[META:%.*]] = value_metatype $@thick SomeClass.Type, [[C]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[META]] : {{.*}}, #SomeClass.static_method!1 // CHECK: apply [[METHOD]]([[I]], [[META]]) type(of: c).static_method(i) // -- Curry property accesses. // -- FIXME: class_method-ify class getters. // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[GETTER:%[0-9]+]] = class_method {{.*}} : $SomeClass, #SomeClass.someProperty!getter.1 // CHECK: apply [[GETTER]]([[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] i = c.someProperty // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.someProperty!setter.1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: apply [[SETTER]]([[I]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] c.someProperty = i // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[READK:%.*]] = begin_access [read] [unknown] [[KADDR]] // CHECK: [[K:%[0-9]+]] = load [trivial] [[READK]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[GETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.subscript!getter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64) -> Builtin.Int64, $@convention(method) (Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> Builtin.Int64 // CHECK: apply [[GETTER]]([[J]], [[K]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] i = c[j, k] // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[READK:%.*]] = begin_access [read] [unknown] [[KADDR]] // CHECK: [[K:%[0-9]+]] = load [trivial] [[READK]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[BORROWED_C]] : $SomeClass, #SomeClass.subscript!setter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> (), $@convention(method) (Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: apply [[SETTER]]([[K]], [[I]], [[J]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] c[i, j] = k // -- Curry the projected concrete value in an existential (or its Type) // -- onto protocol type methods dispatched using protocol_method. // CHECK: [[PBOX:%[0-9]+]] = alloc_box ${ var SomeProtocol } // CHECK: [[PADDR:%.*]] = project_box [[PBOX]] var p : SomeProtocol = ConformsToSomeProtocol() // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PADDR]] // CHECK: [[TEMP:%.*]] = alloc_stack $SomeProtocol // CHECK: copy_addr [[READ]] to [initialization] [[TEMP]] // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] p.method(i) // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[PADDR:%.*]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) var sp : SomeProtocol = ConformsToSomeProtocol() sp.method(i) // FIXME: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED:@opened(.*) SomeProtocol]], #SomeProtocol.static_method!1 // FIXME: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // FIXME: apply [[PMETHOD]]([[I]], [[PMETA]]) // Needs existential metatypes //type(of: p).static_method(i) // -- Use an apply or partial_apply instruction to bind type parameters of a generic. // CHECK: [[GBOX:%[0-9]+]] = alloc_box ${ var SomeGeneric<Builtin.Int64> } // CHECK: [[GADDR:%.*]] = project_box [[GBOX]] // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeGeneric<Builtin.Int64>.Type // CHECK: [[CTOR_GEN:%[0-9]+]] = function_ref @$S9functions11SomeGenericC{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@thick SomeGeneric<τ_0_0>.Type) -> @owned SomeGeneric<τ_0_0> // CHECK: apply [[CTOR_GEN]]<Builtin.Int64>([[META]]) var g = SomeGeneric<Builtin.Int64>() // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[READG:%.*]] = begin_access [read] [unknown] [[GADDR]] // CHECK: [[G:%[0-9]+]] = load [copy] [[READG]] // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[TMPI:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_G]] : {{.*}}, #SomeGeneric.method!1 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPI]], [[BORROWED_G]]) // CHECK: end_borrow [[BORROWED_G]] from [[G]] // CHECK: destroy_value [[G]] g.method(i) // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[READG:%.*]] = begin_access [read] [unknown] [[GADDR]] // CHECK: [[G:%[0-9]+]] = load [copy] [[READG]] // CHECK: [[BORROWED_G:%.*]] = begin_borrow [[G]] // CHECK: [[TMPJ:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_G]] : {{.*}}, #SomeGeneric.generic!1 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPJ]], [[BORROWED_G]]) // CHECK: end_borrow [[BORROWED_G]] from [[G]] // CHECK: destroy_value [[G]] g.generic(j) // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[READC:%.*]] = begin_access [read] [unknown] [[CADDR]] // CHECK: [[C:%[0-9]+]] = load [copy] [[READC]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[TMPK:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[BORROWED_C]] : {{.*}}, #SomeClass.generic!1 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPK]], [[BORROWED_C]]) // CHECK: end_borrow [[BORROWED_C]] from [[C]] // CHECK: destroy_value [[C]] c.generic(k) // FIXME: curried generic entry points //var gm1 = g.method //gm1(i) //var gg1 : (Int) -> Int = g.generic //gg1(j) //var cg1 : (Int) -> Int = c.generic //cg1(k) // SIL-level "thin" function values need to be able to convert to // "thick" function values when stored, returned, or passed as arguments. // CHECK: [[FBOX:%[0-9]+]] = alloc_box ${ var @callee_guaranteed (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 } // CHECK: [[FADDR:%.*]] = project_box [[FBOX]] // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @$S9functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: store [[FUNC_THICK]] to [init] [[FADDR]] var f = standalone_function // CHECK: [[READF:%.*]] = begin_access [read] [unknown] [[FADDR]] // CHECK: [[F:%[0-9]+]] = load [copy] [[READF]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[BORROW:%.*]] = begin_borrow [[F]] // CHECK: apply [[BORROW]]([[I]], [[J]]) // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value [[F]] f(i, j) // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @$S9functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[FUNC_THICK]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[HOF:%[0-9]+]] = function_ref @$S9functions21higher_order_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}} // CHECK: apply [[HOF]]([[CONVERT]], [[I]], [[J]]) higher_order_function(standalone_function, i, j) // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @$S9functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%.*]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[FUNC_THICK]] // CHECK: [[READI:%.*]] = begin_access [read] [unknown] [[IADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[READI]] // CHECK: [[READJ:%.*]] = begin_access [read] [unknown] [[JADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[READJ]] // CHECK: [[HOF2:%[0-9]+]] = function_ref @$S9functions22higher_order_function2{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}} // CHECK: apply [[HOF2]]([[CONVERT]], [[I]], [[J]]) higher_order_function2(standalone_function, i, j) } // -- Curried entry points // CHECK-LABEL: sil shared [thunk] @$S9functions10SomeStructV6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@inout SomeStruct) -> @owned @callee_guaranteed (Builtin.Int64) -> () { // CHECK: [[UNCURRIED:%.*]] = function_ref @$S9functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @inout SomeStruct) -> (){{.*}} // user: %2 // CHECK: [[CURRIED:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]] // CHECK: return [[CURRIED]] // CHECK-LABEL: sil shared [thunk] @$S9functions9SomeClassC6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@guaranteed SomeClass) -> @owned @callee_guaranteed (Builtin.Int64) -> () // CHECK: bb0(%0 : @guaranteed $SomeClass): // CHECK: class_method %0 : $SomeClass, #SomeClass.method!1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: %2 = copy_value %0 : $SomeClass // CHECK: %3 = partial_apply [callee_guaranteed] %1(%2) // CHECK: return %3 func return_func() -> (_ x: Builtin.Int64, _ y: Builtin.Int64) -> Builtin.Int64 { // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @$S9functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: return [[FUNC_THICK]] return standalone_function } func standalone_generic<T>(_ x: T, y: T) -> T { return x } // CHECK-LABEL: sil hidden @$S9functions14return_genericBi64_Bi64__Bi64_tcyF func return_generic() -> (_ x:Builtin.Int64, _ y:Builtin.Int64) -> Builtin.Int64 { // CHECK: [[GEN:%.*]] = function_ref @$S9functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [callee_guaranteed] [[GEN]]<Builtin.Int64>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, @guaranteed @callee_guaranteed (@in_guaranteed Builtin.Int64, @in_guaranteed Builtin.Int64) -> @out Builtin.Int64) -> Builtin.Int64 // CHECK: [[T0:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @$S9functions20return_generic_tuple{{[_0-9a-zA-Z]*}}F func return_generic_tuple() -> (_ x: (Builtin.Int64, Builtin.Int64), _ y: (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) { // CHECK: [[GEN:%.*]] = function_ref @$S9functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [callee_guaranteed] [[GEN]]<(Builtin.Int64, Builtin.Int64)>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed @callee_guaranteed (@in_guaranteed (Builtin.Int64, Builtin.Int64), @in_guaranteed (Builtin.Int64, Builtin.Int64)) -> @out (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) // CHECK: [[T0:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @$S9functions16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never func testNoReturnAttr() -> Never {} // CHECK-LABEL: sil hidden @$S9functions20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in_guaranteed T) -> Never func testNoReturnAttrPoly<T>(_ x: T) -> Never {} // CHECK-LABEL: sil hidden @$S9functions21testNoReturnAttrParam{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@noescape @callee_guaranteed () -> Never) -> () func testNoReturnAttrParam(_ fptr: () -> Never) -> () {} // CHECK-LABEL: sil hidden [transparent] @$S9functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 @_transparent func testTransparent(_ x: Bool) -> Bool { return x } // CHECK-LABEL: sil hidden @$S9functions16applyTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 { func applyTransparent(_ x: Bool) -> Bool { // CHECK: [[FUNC:%[0-9]+]] = function_ref @$S9functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 // CHECK: apply [[FUNC]]({{%[0-9]+}}) : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 return testTransparent(x) } // CHECK-LABEL: sil hidden [noinline] @$S9functions15noinline_calleeyyF : $@convention(thin) () -> () @inline(never) func noinline_callee() {} // CHECK-LABEL: sil hidden [always_inline] @$S9functions20always_inline_calleeyyF : $@convention(thin) () -> () @inline(__always) func always_inline_callee() {} // CHECK-LABEL: sil [serialized] [always_inline] @$S9functions27public_always_inline_calleeyyF : $@convention(thin) () -> () @inline(__always) public func public_always_inline_callee() {} protocol AlwaysInline { func alwaysInlined() } // CHECK-LABEL: sil hidden [always_inline] @$S9functions19AlwaysInlinedMemberV06alwaysC0{{[_0-9a-zA-Z]*}}F : $@convention(method) (AlwaysInlinedMember) -> () { // protocol witness for functions.AlwaysInline.alwaysInlined <A : functions.AlwaysInline>(functions.AlwaysInline.Self)() -> () in conformance functions.AlwaysInlinedMember : functions.AlwaysInline in functions // CHECK-LABEL: sil private [transparent] [thunk] [always_inline] @$S9functions19AlwaysInlinedMemberVAA0B6InlineA2aDP06alwaysC0{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AlwaysInline) (@in_guaranteed AlwaysInlinedMember) -> () { struct AlwaysInlinedMember : AlwaysInline { @inline(__always) func alwaysInlined() {} } // CHECK-LABEL: sil hidden [Onone] @$S9functions10onone_funcyyF : $@convention(thin) () -> () @_optimize(none) func onone_func() {} // CHECK-LABEL: sil hidden [Ospeed] @$S9functions11ospeed_funcyyF : $@convention(thin) () -> () @_optimize(speed) func ospeed_func() {} // CHECK-LABEL: sil hidden [Osize] @$S9functions10osize_funcyyF : $@convention(thin) () -> () @_optimize(size) func osize_func() {} struct OptmodeTestStruct { // CHECK-LABEL: sil hidden [Ospeed] @$S9functions17OptmodeTestStructV3fooyyF : @_optimize(speed) func foo() { } // CHECK-LABEL: sil hidden [Ospeed] @$S9functions17OptmodeTestStructVACycfC : @_optimize(speed) init() { } // CHECK-LABEL: sil hidden [Ospeed] @$S9functions17OptmodeTestStructV1xBi64_vg : @_optimize(speed) var x: Int { return getInt() } // CHECK-LABEL: sil hidden [Ospeed] @$S9functions17OptmodeTestStructVyBi64_Bi64_cig : @_optimize(speed) subscript(l: Int) -> Int { return getInt() } } // CHECK-LABEL: sil hidden [_semantics "foo"] @$S9functions9semanticsyyF : $@convention(thin) () -> () @_semantics("foo") func semantics() {} // <rdar://problem/17828355> curried final method on a class crashes in irgen final class r17828355Class { func method(_ x : Int) { var a : r17828355Class var fn = a.method // currying a final method. } } // The curry thunk for the method should not include a class_method instruction. // CHECK-LABEL: sil shared [thunk] @$S9functions14r17828355ClassC6method // CHECK: bb0(%0 : @guaranteed $r17828355Class): // CHECK-NEXT: // function_ref functions.r17828355Class.method(Builtin.Int64) -> () // CHECK-NEXT: %1 = function_ref @$S9functions14r17828355ClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: %2 = copy_value %0 // CHECK-NEXT: partial_apply [callee_guaranteed] %1(%2) : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: return // <rdar://problem/19981118> Swift 1.2 beta 2: Closures nested in closures copy, rather than reference, captured vars. func noescapefunc(f: () -> ()) {} func escapefunc(_ f : @escaping () -> ()) {} func testNoescape() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. var a = 0 noescapefunc { escapefunc { a = 42 } } markUsed(a) } // CHECK-LABEL: functions.testNoescape() -> () // CHECK-NEXT: sil hidden @$S9functions12testNoescapeyyF : $@convention(thin) () -> () // CHECK: function_ref closure #1 () -> () in functions.testNoescape() -> () // CHECK-NEXT: function_ref @$S9functions12testNoescapeyyFyyXEfU_ : $@convention(thin) (@guaranteed { var Int }) -> () // Despite being a noescape closure, this needs to capture 'a' by-box so it can // be passed to the capturing closure.closure // CHECK: closure #1 () -> () in functions.testNoescape() -> () // CHECK-NEXT: sil private @$S9functions12testNoescapeyyFyyXEfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { func testNoescape2() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. This also checks for when the outer closure captures it // in a way that could be used with escape: the union of the two requirements // doesn't allow a by-address capture. var a = 0 noescapefunc { escapefunc { a = 42 } markUsed(a) } markUsed(a) } // CHECK-LABEL: sil hidden @$S9functions13testNoescape2yyF : $@convention(thin) () -> () { // CHECK: // closure #1 () -> () in functions.testNoescape2() -> () // CHECK-NEXT: sil private @$S9functions13testNoescape2yyFyyXEfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: // closure #1 () -> () in closure #1 () -> () in functions.testNoescape2() -> () // CHECK-NEXT: sil private @$S9functions13testNoescape2yyFyyXEfU_yycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { enum PartialApplyEnumPayload<T, U> { case Left(T) case Right(U) } struct S {} struct C {} func partialApplyEnumCases(_ x: S, y: C) { let left = PartialApplyEnumPayload<S, C>.Left let left2 = left(S()) let right = PartialApplyEnumPayload<S, C>.Right let right2 = right(C()) } // CHECK-LABEL: sil shared [transparent] [thunk] @$S9functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F // CHECK: [[UNCURRIED:%.*]] = function_ref @$S9functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]]<T, U>(%0) // CHECK: [[CANONICAL_THUNK:%.*]] = function_ref @$Sx9functions23PartialApplyEnumPayloadOyxq_GIegir_xADIegnr_r0_lTR : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in τ_0_0) -> @out PartialApplyEnumPayload<τ_0_0, τ_0_1>) -> @out PartialApplyEnumPayload<τ_0_0, τ_0_1> // CHECK: [[THUNKED_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK]]<T, U>([[CLOSURE]]) // CHECK: return [[THUNKED_CLOSURE]] // CHECK: } // end sil function '$S9functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil shared [transparent] [thunk] @$S9functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F // CHECK: [[UNCURRIED:%.*]] = function_ref @$S9functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[UNCURRIED]]<T, U>(%0) // CHECK: [[CANONICAL_THUNK:%.*]] = function_ref @$Sq_9functions23PartialApplyEnumPayloadOyxq_GIegir_q_ADIegnr_r0_lTR : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_1, @guaranteed @callee_guaranteed (@in τ_0_1) -> @out PartialApplyEnumPayload<τ_0_0, τ_0_1>) -> @out PartialApplyEnumPayload<τ_0_0, τ_0_1> // CHECK: [[THUNKED_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK]]<T, U>([[CLOSURE]]) // CHECK: return [[THUNKED_CLOSURE]] // CHECK: } // end sil function '$S9functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F'
apache-2.0
fe2a5dabf4117ff12d54026ade2ce511
47.97973
330
0.615464
3.199382
false
false
false
false
AlwaysRightInstitute/mustache
Sources/Mustache/MustacheRenderingContext.swift
1
2323
// // MustacheRenderingContext.swift // Noze.io // // Created by Helge Heß on 6/7/16. // Copyright © 2016 ZeeZide GmbH. All rights reserved. // public typealias MustacheRenderingFunction = ( String, ( String ) -> String ) -> String public typealias MustacheSimpleRenderingFunction = ( String ) -> String public protocol MustacheRenderingContext { // MARK: - Content Generation var string : String { get } func append(string s: String) // MARK: - Cursor var cursor : Any? { get } func enter(scope ctx: Any?) func leave() // MARK: - Value func value(forTag tag: String) -> Any? // MARK: - Lambda Context (same stack, empty String) func newLambdaContext() -> MustacheRenderingContext // MARK: - Partials func retrievePartial(name n: String) -> MustacheNode? } public extension MustacheRenderingContext { func value(forTag tag: String) -> Any? { return KeyValueCoding.value(forKeyPath: tag, inObject: cursor) } func retrievePartial(name n: String) -> MustacheNode? { return nil } } open class MustacheDefaultRenderingContext : MustacheRenderingContext { public var string : String = "" public var stack = [ Any? ]() // #linux-public public init(_ root: Any?) { if let a = root { stack.append(a) } } public init(context: MustacheDefaultRenderingContext) { stack = context.stack } // MARK: - Content Generation public func append(string s: String) { string += s } // MARK: - Cursor public func enter(scope ctx: Any?) { stack.append(ctx) } public func leave() { _ = stack.removeLast() } public var cursor : Any? { guard let last = stack.last else { return nil } return last } // MARK: - Value open func value(forTag tag: String) -> Any? { let check = stack.reversed() for c in check { if let v = KeyValueCoding.value(forKeyPath: tag, inObject: c) { return v } } return nil } // MARK: - Lambda Context (same stack, empty String) open func newLambdaContext() -> MustacheRenderingContext { return MustacheDefaultRenderingContext(context: self) } // MARK: - Partials open func retrievePartial(name n: String) -> MustacheNode? { return nil } }
apache-2.0
32622c40ff91fe7b5eef195cf9946462
19.539823
71
0.631624
4.029514
false
false
false
false
oskarpearson/rileylink_ios
RileyLink/KeychainManager+RileyLink.swift
2
1019
// // KeychainManager+Loop.swift // // Created by Nate Racklyeft on 6/26/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation private let NightscoutAccount = "NightscoutAPI" extension KeychainManager { func setNightscoutURL(_ url: URL?, secret: String?) { do { let credentials: InternetCredentials? if let url = url, let secret = secret { credentials = InternetCredentials(username: NightscoutAccount, password: secret, url: url) } else { credentials = nil } try replaceInternetCredentials(credentials, forAccount: NightscoutAccount) } catch { } } func getNightscoutCredentials() -> (url: URL, secret: String)? { do { let credentials = try getInternetCredentials(account: NightscoutAccount) return (url: credentials.url, secret: credentials.password) } catch { return nil } } }
mit
3c6fb4cc857e6920cac5ff078297b7f0
24.45
106
0.604126
4.824645
false
false
false
false
anfema/Mockingbird
src/mockingbird.swift
1
10790
// // nsurlcache.swift // mockingbird // // Created by Johannes Schriewer on 01/12/15. // Copyright © 2015 anfema. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the conditions of the 3-clause // BSD license (see LICENSE.txt for full license text) import Foundation import DEjson internal struct MockBundleEntry { var url:String! var queryParameters = [String:String?]() var requestMethod = "GET" var responseCode:Int = 200 var responseHeaders = [String:String]() var responseFile:String? var responseMime:String? init(json: JSONObject) throws { guard case .jsonDictionary(let dict) = json, (dict["request"] != nil && dict["response"] != nil), case .jsonDictionary(let request) = dict["request"]!, request["url"] != nil, case .jsonDictionary(let response) = dict["response"]!, response["code"] != nil, case .jsonString(let url) = request["url"]!, case .jsonNumber(let code) = response["code"]! else { throw MockingBird.MBError.invalidBundleDescriptionFile } self.url = url self.responseCode = Int(code) if let q = request["parameters"], case .jsonDictionary(let query) = q { for item in query { if case .jsonString(let value) = item.1 { self.queryParameters[item.0] = value } else if case .jsonNull = item.1 { self.queryParameters[item.0] = nil as String? } else { print("Query parameter \(item.0) has invalid value!") } } } if let q = request["method"], case .jsonString(let method) = q { self.requestMethod = method } if let q = response["headers"], case .jsonDictionary(let headers) = q { for item in headers { if case .jsonString(let value) = item.1 { self.responseHeaders[item.0] = value } } } if let q = response["file"], case .jsonString(let file) = q { self.responseFile = file } if let q = response["mime_type"], case .jsonString(let mime) = q { self.responseMime = mime } } } open class MockingBird: URLProtocol { static var currentMockBundle: [MockBundleEntry]? static var currentMockBundlePath: String? // If this is true, we'll claim to answer all URL requests. // If this is false, URLs that don't match will be passed on // through to normal handlers. public static var handleAllRequests: Bool = false public enum MBError: Error { case mockBundleNotFound case invalidMockBundle case invalidBundleDescriptionFile } /// Register MockingBird with a NSURLSession /// /// - parameter session: the session to mock open class func register(inSession session: URLSession) { self.register(inConfig: session.configuration) } /// Register MockingBird in a NSURLSessionConfiguration /// /// - parameter config: session configuration to mock open class func register(inConfig config: URLSessionConfiguration) { var protocolClasses = config.protocolClasses if protocolClasses == nil { protocolClasses = [AnyClass]() } protocolClasses!.insert(MockingBird.self, at: 0) config.protocolClasses = protocolClasses } /// Set mock bundle to use /// /// - parameter bundlePath: path to the bundle /// - throws: MockingBird.Error when bundle could not be loaded open class func setMockBundle(withPath bundlePath: String?) throws { guard let bundlePath = bundlePath else { self.currentMockBundle = nil self.currentMockBundlePath = nil return } do { var isDir = ObjCBool(false) if FileManager.default.fileExists(atPath: bundlePath, isDirectory: &isDir) && isDir.boolValue { let jsonString = try String(contentsOfFile: "\(bundlePath)/bundle.json") let jsonObject = JSONDecoder(jsonString).jsonObject if case .jsonArray(let array) = jsonObject { self.currentMockBundle = try array.map { item -> MockBundleEntry in return try MockBundleEntry(json: item) } } else { throw MockingBird.MBError.invalidBundleDescriptionFile } } else { throw MockingBird.MBError.mockBundleNotFound } } catch MockingBird.MBError.invalidBundleDescriptionFile { throw MockingBird.MBError.invalidBundleDescriptionFile } catch { throw MockingBird.MBError.invalidMockBundle } self.currentMockBundlePath = bundlePath } } // MARK: - URL Protocol overrides extension MockingBird { open override class func canInit(with request: URLRequest) -> Bool { // we can only answer if we have a mockBundle if self.currentMockBundle == nil { return false } // we can answer all http and https requests if let _ = self.getBundleItem(inURL: request.url!, method: request.httpMethod!) { return true } return self.handleAllRequests } open override class func canonicalRequest(for request: URLRequest) -> URLRequest { // canonical request is same as request return request } open override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { // nothing is cacheable return false } open override func startLoading() { // fetch item guard let entry = MockingBird.getBundleItem(inURL: self.request.url!, method: self.request.httpMethod!) else { if MockingBird.handleAllRequests { // We're handling all requests, but no bundle item found // so reply with server error 501 and no data var headers = [String: String]() headers["Content-Type"] = "text/plain" let errorMsg = "Mockingbird response not available. Please add a response to the bundle at \(MockingBird.currentMockBundlePath ?? "nil")." let data = errorMsg.data(using: String.Encoding.utf8) if let data = data { headers["Content-Length"] = "\(data.count)" } let response = HTTPURLResponse(url: self.request.url!, statusCode: 501, httpVersion: "HTTP/1.1", headerFields: headers)! // send response self.client!.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) // send response data if available if let data = data { self.client!.urlProtocol(self, didLoad: data) } // finish up self.client!.urlProtocolDidFinishLoading(self) } else { self.client!.urlProtocol(self, didFailWithError: NSError.init(domain: "mockingbird", code: 1000, userInfo:nil)) } return } // set mime type var mime: String? = nil if let m = entry.responseMime { mime = m } // load data var data: Data? = nil if let f = entry.responseFile { do { data = try Data(contentsOf: URL(fileURLWithPath: "\(MockingBird.currentMockBundlePath!)/\(f)"), options: .mappedIfSafe) } catch { data = nil } } // construct response var headers = entry.responseHeaders headers["Content-Type"] = mime if let data = data { headers["Content-Length"] = "\(data.count)" } let response = HTTPURLResponse(url: self.request.url!, statusCode: entry.responseCode, httpVersion: "HTTP/1.1", headerFields: headers)! // send response self.client!.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) // send response data if available if let data = data { self.client!.urlProtocol(self, didLoad: data) } // finish up self.client!.urlProtocolDidFinishLoading(self) } open override func stopLoading() { // do nothing } fileprivate class func getBundleItem(inURL inUrl: URL, method: String) -> MockBundleEntry? { let url = URLComponents(url: inUrl, resolvingAgainstBaseURL: false)! // find entry that matches for entry in MockingBird.currentMockBundle! { // url match and request method match var urlPart = "://\(url.host!)\(url.path)" if let port = url.port { urlPart = "://\(url.host!):\(port)\(url.path)" } if entry.url == urlPart && entry.requestMethod == method { // components var valid = true if let queryItems = url.queryItems { for component in queryItems { var found = false for q in entry.queryParameters { if component.name == q.0 && q.1 == nil { found = true break } else if component.name == q.0 && component.value == q.1 { found = true break } } if !found { valid = false break } } } else { // no components if entry.queryParameters.count != 0 { valid = false } } if valid { return entry } } } return nil } }
bsd-3-clause
3cd9d6b91c555ab13796f8960243d5f4
35.449324
155
0.525628
5.335806
false
false
false
false
Jnosh/swift
test/IRGen/objc_protocols.swift
6
10824
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import gizmo import objc_protocols_Bas // -- Protocol "Frungible" inherits only objc protocols and should have no // out-of-line inherited witnesses in its witness table. // CHECK: [[ZIM_FRUNGIBLE_WITNESS:@_T014objc_protocols3ZimCAA9FrungibleAAWP]] = hidden constant [1 x i8*] [ // CHECK: i8* bitcast (void (%T14objc_protocols3ZimC*, %swift.type*, i8**)* @_T014objc_protocols3ZimCAA9FrungibleA2aDP6frungeyyFTW to i8*) // CHECK: ] protocol Ansible { func anse() } class Foo : NSRuncing, NSFunging, Ansible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func anse() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Foo = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC:@[0-9]+]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC5runceyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC5fungeyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3FooC3fooyyFTo to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 class Bar { func bar() {} } // -- Bar does not directly have objc methods... // CHECK-NOT: @_INSTANCE_METHODS_Bar extension Bar : NSRuncing, NSFunging { @objc func runce() {} @objc func funge() {} @objc func foo() {} func notObjC() {} } // -- ...but the ObjC protocol conformances on its extension add some // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC14objc_protocols3Bar_$_objc_protocols" = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC5runceyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC5fungeyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3BarC3fooyyFTo to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // -- The runce() implementation comes from the original definition. @objc public func foo() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas3Bas_$_objc_protocols" = private constant { i32, i32, [1 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 1, // CHECK; [1 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas0C0C0a1_B0E3fooyyFTo to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // -- Swift protocol refinement of ObjC protocols. protocol Frungible : NSRuncing, NSFunging { func frunge() } class Zim : Frungible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func frunge() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Zim = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC5runceyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC5fungeyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T014objc_protocols3ZimC3fooyyFTo to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // class Zang from objc_protocols_Bas module extension Zang : Frungible { @objc public func runce() {} // funge() implementation from original definition of Zang @objc public func foo() {} func frunge() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas4Zang_$_objc_protocols" = private constant { i32, i32, [2 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas4ZangC0a1_B0E5runceyyFTo to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_T018objc_protocols_Bas4ZangC0a1_B0E3fooyyFTo to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 @objc protocol BaseProtocol { } protocol InheritingProtocol : BaseProtocol { } // -- Make sure that base protocol conformance is registered // CHECK: @_PROTOCOLS__TtC14objc_protocols17ImplementingClass {{.*}} @_PROTOCOL__TtP14objc_protocols12BaseProtocol_ class ImplementingClass : InheritingProtocol { } // -- Force generation of witness for Zim. // CHECK: define hidden swiftcc { %objc_object*, i8** } @_T014objc_protocols22mixed_heritage_erasure{{[_0-9a-zA-Z]*}}F func mixed_heritage_erasure(_ x: Zim) -> Frungible { return x // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* {{%.*}}, 0 // CHECK: insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[ZIM_FRUNGIBLE_WITNESS]], i32 0, i32 0), 1 } // CHECK-LABEL: define hidden swiftcc void @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T) {{.*}} { func objc_generic<T : NSRuncing>(_ x: T) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK-LABEL: define hidden swiftcc void @_T014objc_protocols05call_A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object*, %swift.type* %T) {{.*}} { // CHECK: call swiftcc void @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F(%objc_object* %0, %swift.type* %T) func call_objc_generic<T : NSRuncing>(_ x: T) { objc_generic(x) } // CHECK-LABEL: define hidden swiftcc void @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F(%objc_object*) {{.*}} { func objc_protocol(_ x: NSRuncing) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK: define hidden swiftcc %objc_object* @_T014objc_protocols0A8_erasure{{[_0-9a-zA-Z]*}}F(%TSo7NSSpoonC*) {{.*}} { func objc_erasure(_ x: NSSpoon) -> NSRuncing { return x // CHECK: [[RES:%.*]] = bitcast %TSo7NSSpoonC* {{%.*}} to %objc_object* // CHECK: ret %objc_object* [[RES]] } // CHECK: define hidden swiftcc void @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F(%objc_object*) func objc_protocol_composition(_ x: NSRuncing & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // CHECK: define hidden swiftcc void @_T014objc_protocols0A27_swift_protocol_composition{{[_0-9a-zA-Z]*}}F(%objc_object*, i8**) func objc_swift_protocol_composition (_ x: NSRuncing & Ansible & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) /* TODO: Abstraction difference from ObjC protocol composition to * opaque protocol x.anse() */ x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // TODO: Mixed class-bounded/fully general protocol compositions. @objc protocol SettableProperty { var reqt: NSRuncing { get set } } func instantiateArchetype<T: SettableProperty>(_ x: T) { let y = x.reqt x.reqt = y } // rdar://problem/21029254 @objc protocol Appaloosa { } protocol Palomino {} protocol Vanner : Palomino, Appaloosa { } struct Stirrup<T : Palomino> { } func canter<T : Palomino>(_ t: Stirrup<T>) {} func gallop<T : Vanner>(_ t: Stirrup<T>) { canter(t) }
apache-2.0
2cf0cb60349fa5b6e29f0cddfed3ed8b
50.298578
288
0.616962
2.85669
false
false
false
false
huonw/swift
test/SILGen/function_conversion.swift
1
35973
// RUN: %target-swift-emit-silgen -module-name function_conversion -enable-sil-ownership -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-ir -module-name function_conversion -enable-sil-ownership -primary-file %s // Check SILGen against various FunctionConversionExprs emitted by Sema. // ==== Representation conversions // CHECK-LABEL: sil hidden @$S19function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$SS2iIetCyd_S2iIegyd_TR // CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0) // CHECK: return [[FUNC]] func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int { return arg } // CHECK-LABEL: sil hidden @$S19function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int // CHECK: return [[COPY]] func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int { return arg } // ==== Throws variance // CHECK-LABEL: sil hidden @$S19function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> ()): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> () to $@callee_guaranteed () -> @error Error // CHECK: return [[FUNC]] // CHECK: } // end sil function '$S19function_conversion12funcToThrowsyyyKcyycF' func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () { return x } // CHECK-LABEL: sil hidden @$S19function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error // CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error // CHECK: return [[FUNC]] : $@convention(thin) () -> @error Error func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () { return x } // FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs /* func thinFunc() {} func thinToThrows() { let _: @convention(thin) () -> () = thinFunc } */ // ==== Class downcasts and upcasts class Feral {} class Domesticated : Feral {} // CHECK-LABEL: sil hidden @$S19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> @owned Domesticated): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> @owned Domesticated to $@callee_guaranteed () -> @owned Feral // CHECK: return [[FUNC]] // CHECK: } // end sil function '$S19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF' func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral { return x } // CHECK-LABEL: sil hidden @$S19function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@guaranteed @callee_guaranteed (@guaranteed Feral) -> ()) -> @owned @callee_guaranteed (@guaranteed Domesticated) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed (@guaranteed Feral) -> () to $@callee_guaranteed (@guaranteed Domesticated) -> (){{.*}} // CHECK: return [[FUNC]] func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () { return x } // ==== Optionals struct Trivial { let n: Int8 } class C { let n: Int8 init(n: Int8) { self.n = n } } struct Loadable { let c: C var n: Int8 { return c.n } init(n: Int8) { c = C(n: n) } } struct AddrOnly { let a: Any var n: Int8 { return a as! Int8 } init(n: Int8) { a = n } } // CHECK-LABEL: sil hidden @$S19function_conversion19convOptionalTrivialyyAA0E0VADSgcF func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) { // CHECK: function_ref @$S19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR // CHECK: partial_apply let _: (Trivial) -> Trivial? = t1 // CHECK: function_ref @$S19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR // CHECK: partial_apply let _: (Trivial?) -> Trivial? = t1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: [[ENUM:%.*]] = enum $Optional<Trivial> // CHECK-NEXT: apply %1([[ENUM]]) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR : $@convention(thin) (Optional<Trivial>, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil hidden @$S19function_conversion20convOptionalLoadableyyAA0E0VADSgcF func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) { // CHECK: function_ref @$S19function_conversion8LoadableVSgACIeggo_AcDIeggo_TR // CHECK: partial_apply let _: (Loadable) -> Loadable? = l1 // CHECK: function_ref @$S19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR // CHECK: partial_apply let _: (Loadable?) -> Loadable? = l1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR : $@convention(thin) (@guaranteed Optional<Loadable>, @guaranteed @callee_guaranteed (@guaranteed Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Loadable> // CHECK-NEXT: return // CHECK-LABEL: sil hidden @$S19function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) { // CHECK: function_ref @$S19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR // CHECK: partial_apply let _: (AddrOnly?) -> AddrOnly? = a1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR : $@convention(thin) (@in_guaranteed Optional<AddrOnly>, @guaranteed @callee_guaranteed (@in_guaranteed Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly> // CHECK: [[TEMP:%.*]] = alloc_stack $AddrOnly // CHECK-NEXT: apply %2([[TEMP]], %1) // CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly // CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly // CHECK-NEXT: return // ==== Existentials protocol Q { var n: Int8 { get } } protocol P : Q {} extension Trivial : P {} extension Loadable : P {} extension AddrOnly : P {} // CHECK-LABEL: sil hidden @$S19function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) { // CHECK: function_ref @$S19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial) -> P = t2 // CHECK: function_ref @$S19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial?) -> P = t3 // CHECK: function_ref @$S19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR // CHECK: partial_apply let _: (P) -> P = t2 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: alloc_stack $Q // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: switch_enum // CHECK: bb1([[TRIVIAL:%.*]] : @trivial $Trivial): // CHECK: init_existential_addr // CHECK: init_enum_data_addr // CHECK: copy_addr // CHECK: inject_enum_addr // CHECK: bb2: // CHECK: inject_enum_addr // CHECK: bb3: // CHECK: apply // CHECK: init_existential_addr // CHECK: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: [[TMP:%.*]] = alloc_stack $Q // CHECK-NEXT: open_existential_addr immutable_access %1 : $*P // CHECK-NEXT: init_existential_addr [[TMP]] : $*Q // CHECK-NEXT: copy_addr {{.*}} to [initialization] {{.*}} // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: destroy_addr // CHECK: return // ==== Existential metatypes // CHECK-LABEL: sil hidden @$S19function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) { // CHECK: function_ref @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type) -> P.Type = em // CHECK: function_ref @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type?) -> P.Type = em // CHECK: function_ref @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR // CHECK: partial_apply let _: (P.Type) -> P.Type = em } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR : $@convention(thin) (@thin Trivial.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: [[META:%.*]] = metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype [[META]] : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: switch_enum %0 : $Optional<@thin Trivial.Type> // CHECK: bb1([[META:%.*]] : @trivial $@thin Trivial.Type): // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb2: // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb3({{.*}}): // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR : $@convention(thin) (@thick P.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type // CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply %1 // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // ==== Class metatype upcasts class Parent {} class Child : Parent {} // Note: we add a Trivial => Trivial? conversion here to force a thunk // to be generated // CHECK-LABEL: sil hidden @$S19function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type, c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) { // CHECK: function_ref @$S19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c4 // CHECK: function_ref @$S19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c5 // CHECK: function_ref @$S19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR // CHECK: partial_apply let _: (Child.Type?, Trivial) -> Parent.Type? = c5 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type> // CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: return // ==== Function to existential -- make sure we maximally abstract it // CHECK-LABEL: sil hidden @$S19function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$SypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[ARG_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$S19function_conversion19convFuncExistentialyyS2icypcF' func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) { let _: (@escaping (Int) -> Int) -> Any = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> @out Any { // CHECK: alloc_stack $Any // CHECK: function_ref @$SS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[COPIED_VAL:%.*]] = copy_value // CHECK-NEXT: partial_apply [callee_guaranteed] {{%.*}}([[COPIED_VAL]]) // CHECK-NEXT: init_existential_addr %3 : $*Any, $(Int) -> Int // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK: function_ref @$SS2iIegyd_S2iIegnr_TR // CHECK-NEXT: partial_apply // CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int // CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_guaranteed (@in_guaranteed Int) -> @out Int // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SS2iIegyd_S2iIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Int) -> @out Int // CHECK: [[LOADED:%.*]] = load [trivial] %1 : $*Int // CHECK-NEXT: apply %2([[LOADED]]) // CHECK-NEXT: store {{.*}} to [trivial] %0 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] // ==== Class-bound archetype upcast // CHECK-LABEL: sil hidden @$S19function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) { // CHECK: function_ref @$S19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR // CHECK: partial_apply let _: (T) -> (Parent, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@guaranteed T, @guaranteed @callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>) // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, [[CLOSURE:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)): // CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent // CHECK: [[RESULT:%.*]] = apply %1([[CASTED_ARG]]) // CHECK: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]] : $(T, Trivial) // CHECK: [[FIRST_RESULT:%.*]] = tuple_extract [[BORROWED_RESULT]] : $(T, Trivial), 0 // CHECK: [[COPIED_FIRST_RESULT:%.*]] = copy_value [[FIRST_RESULT]] // CHECK: tuple_extract [[BORROWED_RESULT]] : $(T, Trivial), 1 // CHECK: destroy_value [[RESULT]] // CHECK: [[CAST_COPIED_FIRST_RESULT:%.*]] = upcast [[COPIED_FIRST_RESULT]] : $T to $Parent // CHECK: enum $Optional<Trivial> // CHECK: [[RESULT:%.*]] = tuple ([[CAST_COPIED_FIRST_RESULT]] : $Parent, {{.*}} : $Optional<Trivial>) // CHECK: return [[RESULT]] // CHECK-LABEL: sil hidden @$S19function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) { // CHECK: function_ref @$S19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR // CHECK: partial_apply let _: (T.Type) -> (Parent.Type, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @guaranteed @callee_guaranteed (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>) // CHECK: upcast %0 : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: apply // CHECK-NEXT: tuple_extract // CHECK-NEXT: tuple_extract // CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: tuple // CHECK-NEXT: return // ==== Make sure we destructure one-element tuples // CHECK-LABEL: sil hidden @$S19function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF // CHECK: function_ref @$S19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$S19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$SSi_SitSgIegy_S2iIegyy_TR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S19function_conversion1Q_pIegn_AA1P_pIegn_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> ()) -> () // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSi_SitSgIegy_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (Optional<(Int, Int)>) -> ()) -> () func convTupleScalar(_ f1: @escaping (Q) -> (), f2: @escaping (_ parent: Q) -> (), f3: @escaping (_ tuple: (Int, Int)?) -> ()) { let _: (P) -> () = f1 let _: (P) -> () = f2 let _: (Int, Int) -> () = f3 } func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? { return f } // CHECK-LABEL: sil hidden @$S19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$SS3iIegydd_S2i_SitSgIegyd_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[FN]]) // CHECK-NEXT: return [[THUNK]] // CHECK-NEXT: } // end sil function '$S19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF' // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SS3iIegydd_S2i_SitSgIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> Optional<(Int, Int)> // CHECK: bb0(%0 : @trivial $Int, %1 : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[RESULT:%.*]] = apply %1(%0) // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int) // CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt.1, [[RESULT]] // CHECK-NEXT: return [[OPTIONAL]] func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? { return f } // CHECK-LABEL: sil hidden @$S19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out Optional<(T, T)> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$SxxxIegnrr_xx_xtSgIegnr_lTR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T>([[FN]]) // CHECK-NEXT: return [[THUNK]] // CHECK-NEXT: } // end sil function '$S19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF' // CHECK: sil shared [transparent] [serializable] [reabstraction_thunk] @$SxxxIegnrr_xx_xtSgIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @out Optional<(T, T)> // CHECK: bb0(%0 : @trivial $*Optional<(T, T)>, %1 : @trivial $*T, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)): // CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 1 // CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1) // CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? { return f } // ==== Make sure we support AnyHashable erasure // CHECK-LABEL: sil hidden @$S19function_conversion15convAnyHashable1tyx_ts0E0RzlF // CHECK: function_ref @$S19function_conversion15convAnyHashable1tyx_ts0E0RzlFSbs0dE0V_AFtcfU_ // CHECK: function_ref @$Ss11AnyHashableVABSbIegnnd_xxSbIegnnd_s0B0RzlTR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$Ss11AnyHashableVABSbIegnnd_xxSbIegnnd_s0B0RzlTR : $@convention(thin) <T where T : Hashable> (@in_guaranteed T, @in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed AnyHashable, @in_guaranteed AnyHashable) -> Bool) -> Bool // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$Ss21_convertToAnyHashableys0cD0Vxs0D0RzlF // CHECK: apply {{.*}}<T> // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$Ss21_convertToAnyHashableys0cD0Vxs0D0RzlF // CHECK: apply {{.*}}<T> // CHECK: return func convAnyHashable<T : Hashable>(t: T) { let fn: (T, T) -> Bool = { (x: AnyHashable, y: AnyHashable) in x == y } } // ==== Convert exploded tuples to Any or Optional<Any> // CHECK-LABEL: sil hidden @$S19function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF // CHECK: function_ref @$SIeg_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$SIeg_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$SS2iIegdd_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$SS2iIegdd_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$SypIegn_S2iIegyy_TR // CHECK: partial_apply // CHECK: function_ref @$SypSgIegn_S2iIegyy_TR // CHECK: partial_apply func convTupleAny(_ f1: @escaping () -> (), _ f2: @escaping () -> (Int, Int), _ f3: @escaping (Any) -> (), _ f4: @escaping (Any?) -> ()) { let _: () -> Any = f1 let _: () -> Any? = f1 let _: () -> Any = f2 let _: () -> Any? = f2 let _: ((Int, Int)) -> () = f3 let _: ((Int, Int)) -> () = f4 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SIeg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any // CHECK: init_existential_addr %0 : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SIeg_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Optional<Any> // CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SS2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any // CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0 // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SS2iIegdd_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Optional<Any> { // CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0 // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: apply %2([[ANY_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[ANY_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypSgIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Optional<Any>) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any> // CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [initialization] [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: apply %2([[OPTIONAL_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // ==== Support collection subtyping in function argument position protocol Z {} class A: Z {} func foo_arr<T: Z>(type: T.Type, _ fn: ([T]?) -> Void) {} func foo_map<T: Z>(type: T.Type, _ fn: ([Int: T]) -> Void) {} func rdar35702810() { let fn_arr: ([Z]?) -> Void = { _ in } let fn_map: ([Int: Z]) -> Void = { _ in } // CHECK: function_ref @$Ss15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> // CHECK: apply %5<A, Z>(%6) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> foo_arr(type: A.self, fn_arr) // CHECK: function_ref @$Ss17_dictionaryUpCastys10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %2<Int, A, Int, Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %1(%4) : $@callee_guaranteed (@guaranteed Dictionary<Int, Z>) -> () foo_map(type: A.self, fn_map) } protocol X: Hashable {} class B: X { var hashValue: Int { return 42 } static func == (lhs: B, rhs: B) -> Bool { return lhs.hashValue == rhs.hashValue } } func bar_arr<T: X>(type: T.Type, _ fn: ([T]?) -> Void) {} func bar_map<T: X>(type: T.Type, _ fn: ([T: Int]) -> Void) {} func bar_set<T: X>(type: T.Type, _ fn: (Set<T>) -> Void) {} func rdar35702810_anyhashable() { let fn_arr: ([AnyHashable]?) -> Void = { _ in } let fn_map: ([AnyHashable: Int]) -> Void = { _ in } let fn_set: (Set<AnyHashable>) -> Void = { _ in } // CHECK: [[FN:%.*]] = function_ref @$SSays11AnyHashableVGSgIegg_Say19function_conversion1BCGSgIegg_TR : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Optional<Array<B>>) -> () to $@noescape @callee_guaranteed (@guaranteed Optional<Array<B>>) -> () bar_arr(type: B.self, fn_arr) // CHECK: [[FN:%.*]] = function_ref @$Ss10DictionaryVys11AnyHashableVSiGIegg_ABy19function_conversion1BCSiGIegg_TR : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () to $@noescape @callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () bar_map(type: B.self, fn_map) // CHECK: [[FN:%.*]] = function_ref @$Ss3SetVys11AnyHashableVGIegg_ABy19function_conversion1BCGIegg_TR : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Set<B>) -> () to $@noescape @callee_guaranteed (@guaranteed Set<B>) -> () bar_set(type: B.self, fn_set) } // ==== Function conversion with parameter substToOrig reabstraction. struct FunctionConversionParameterSubstToOrigReabstractionTest { typealias SelfTy = FunctionConversionParameterSubstToOrigReabstractionTest class Klass: Error {} struct Foo<T> { static func enum1Func(_ : (T) -> Foo<Error>) -> Foo<Error> { // Just to make it compile. return Optional<Foo<Error>>.none! } } static func bar<T>(t: T) -> Foo<T> { // Just to make it compile. return Optional<Foo<T>>.none! } static func testFunc() -> Foo<Error> { return Foo<Klass>.enum1Func(SelfTy.bar) } }
apache-2.0
7815116476690304179e7c3efca24864
52.890555
361
0.644791
3.355583
false
false
false
false
michaelsabo/hammer
Hammer/Classes/ViewControllers/DisplayViewController.swift
1
13683
// // DisplayViewController.swift // Hammer // // Created by Mike Sabo on 10/5/15. // Copyright © 2015 FlyingDinosaurs. All rights reserved. // import UIKit import MobileCoreServices import ChameleonFramework import NVActivityIndicatorView import RxSwift import RxCocoa import Regift import Gifu import Font_Awesome_Swift import MMPopupView // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class DisplayViewController: UIViewController, UINavigationBarDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: GIFImageView! @IBOutlet weak var videoSizeLabel: UILabel! { didSet { videoSizeLabel.isHidden = true } } @IBOutlet weak var gifSizeLabel: UILabel! { didSet { gifSizeLabel.isHidden = true } } var tags: [Tag]? var tagLabels: [PaddedTagLabel]? = [PaddedTagLabel]() var displayGifViewModel: DisplayViewModel! var newTagButton : UIButton! var tagsAddedToView = false let tagHeight:CGFloat = 34 var shareButton: UIBarButtonItem? var disposeBag:DisposeBag! = DisposeBag() var videoSize:Int = 0 var gifVideoSize:Int = 0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init() { self.init(nibName: "DisplayViewController", bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() setupView() bindViewModel() } func setupView() { self.view.backgroundColor = ColorThemes.getBackgroundColor() self.view.clipsToBounds = true self.configureNavigationBar() let loadingFrame = CGRect(x: 0, y: 0, width: 60.0, height: 60.0) let loadingView = NVActivityIndicatorView(frame: loadingFrame, type: .lineScalePulseOut, color: ColorThemes.subviewsColor()) loadingView.tag = kLoadingAnimationTag loadingView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(loadingView) self.view.addConstraint(NSLayoutConstraint.init(item: loadingView, attribute: .centerY, relatedBy: .equal, toItem: self.imageView, attribute: .centerY, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint.init(item: loadingView, attribute: .centerX, relatedBy: .equal, toItem: self.imageView, attribute: .centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint.init(item: loadingView, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60)) self.view.addConstraint(NSLayoutConstraint.init(item: loadingView, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 60)) loadingView.startAnimating() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func bindViewModel() { shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(DisplayViewController.shareButtonClicked)) self.displayGifViewModel.gifRequestSignal .asObservable() .filter({$0}) .observeOn(MainScheduler.instance) .subscribe({ [weak self] _ in guard let selfie = self else { return } let animation = selfie.view.viewWithTag(kLoadingAnimationTag) as? NVActivityIndicatorView animation?.stopAnimating() animation?.removeFromSuperview() selfie.imageView.prepareForAnimation(withGIFData: selfie.displayGifViewModel.gifData) selfie.imageView.startAnimatingGIF() selfie.imageView.gifData = selfie.displayGifViewModel.gifData selfie.imageView.isUserInteractionEnabled = true selfie.navigationItem.rightBarButtonItem = selfie.shareButton selfie.videoSizeLabel.isHidden = false selfie.videoSizeLabel.attributedText = "download size: \(selfie.displayGifViewModel.videoSize.fileSize)".styled(with:ColorThemes.fileInfoStyle()) selfie.gifSizeLabel.isHidden = false selfie.gifSizeLabel.attributedText = "gif size: \(selfie.displayGifViewModel.gifData.count.fileSize)".styled(with:ColorThemes.fileInfoStyle()) selfie.imageView.enableLongPress() }).addDisposableTo(disposeBag) self.displayGifViewModel.tagRequestSignal .asObservable() .subscribeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] _ in guard let selfie = self else { return } selfie.removeTagsAndButton() selfie.displayNewTagButton() selfie.horizonalTagLayout() }).addDisposableTo(disposeBag) self.displayGifViewModel.createTagRequestSignal .asObservable() .subscribeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] success in if (success) { UserDefaults.incrementTagsAdded() self?.displayGifViewModel.startTagSignal() } }).addDisposableTo(disposeBag) } func removeTagsAndButton() { for subview in view.subviews { if subview.tag == 200 || subview.tag == 10005 { subview.removeFromSuperview() } } } func displayNewTagButton() { newTagButton = PaddedButton(frame: CGRect(x: 0,y: 0,width: 126,height: tagHeight)).newButton(withTitle: "new tag", target: self, selector: #selector(DisplayViewController.displayTagAlert), forControlEvent: .touchUpInside) newTagButton.setFAText(prefixText: "", icon: FAType.FATag, postfixText: " add new tag!", size: 16, forState: .normal) newTagButton.tag = 10005 self.view.addSubview(newTagButton) self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: tagHeight)) self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 126)) } func displayTagAlert() { let alertConfig = MMAlertViewConfig.global() alertConfig?.defaultConfig() alertConfig?.defaultTextConfirm = "I WILL!" alertConfig?.defaultTextCancel = "You Won't" let alertView = MMAlertView.init(inputTitle: "New Tag", detail: self.displayGifViewModel.alertDetail, placeholder: "lingo here..", handler: { tagText in if (tagText?.characters.count > 2) { self.displayGifViewModel.startCreateTagSignalRequest((tagText?.lowercased())!) } else { } }) alertView?.attachedView = self.view alertView?.show() } func horizonalTagLayout() { self.tagLabels = [PaddedTagLabel]() for tag in self.displayGifViewModel.tags.value { let label = PaddedTagLabel.init(text: tag.name) label.setFAText(prefixText: "", icon: FAType.FATag, postfixText: " \(label.text!)", size: 16) self.view.addSubview(label) self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: tagHeight)) label.setNeedsDisplay() self.tagLabels?.append(label) } tagsAddedToView = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard tagsAddedToView else { return } addConstraintsForTags() } func addConstraintsForTags() { let maxWidth = Screen.screenWidth let xPadding : CGFloat = 4.0 let yPadding : CGFloat = 5.0 let zeroPadding : CGFloat = 0.0 var rowTupleArray = [(row: 0, firstItemIndex: 0, lastItemIndex: 0, currentWidth: CGFloat(0.0))] for (index, label) in (self.tagLabels?.enumerated())! { let objWidth = label.frame.size.width if (index == 0) { self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: self.videoSizeLabel, attribute: .bottom, multiplier: 1, constant: yPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: xPadding)) rowTupleArray[rowTupleArray.count-1].currentWidth = objWidth + xPadding } else { for (i, row) in rowTupleArray.enumerated() { if ((row.currentWidth + objWidth) < maxWidth) { let previousView = (self.tagLabels?[rowTupleArray[i].lastItemIndex])! as PaddedTagLabel self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: previousView, attribute: .top, multiplier: 1, constant: zeroPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .left, relatedBy: .equal, toItem: previousView, attribute: .right, multiplier: 1, constant: xPadding)) rowTupleArray[i].currentWidth += objWidth + xPadding rowTupleArray[i].lastItemIndex = index break } else if (i < rowTupleArray.count-1) { continue } else { let viewAbove = (self.tagLabels?[rowTupleArray[i].firstItemIndex])! as PaddedTagLabel self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .top, relatedBy: .equal, toItem: viewAbove, attribute: .bottom, multiplier: 1, constant: yPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: label, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: xPadding)) rowTupleArray.append((rowTupleArray.count, index, index, (objWidth + xPadding))) break } } } } guard self.tagLabels?.count > 0 else { self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .top, relatedBy: .equal, toItem: self.videoSizeLabel, attribute: .bottom, multiplier: 1, constant: yPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: xPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: self.view, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: newTagButton, attribute: .rightMargin, multiplier: 1, constant: xPadding)) return } let buttonWidth = newTagButton.frame.size.width if ((rowTupleArray[rowTupleArray.count-1].currentWidth + buttonWidth) > maxWidth) { let labelAbove = (self.tagLabels?[rowTupleArray[rowTupleArray.count-1].firstItemIndex])! as PaddedTagLabel self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .top, relatedBy: .equal, toItem: labelAbove, attribute: .bottom, multiplier: 1, constant: yPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: xPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: self.view, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: newTagButton, attribute: .rightMargin, multiplier: 1, constant: xPadding)) } else { let lastLabel = (self.tagLabels?[rowTupleArray[rowTupleArray.count-1].lastItemIndex])! as PaddedTagLabel self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .top, relatedBy: .equal, toItem: lastLabel, attribute: .top, multiplier: 1, constant: zeroPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: newTagButton, attribute: .left, relatedBy: .equal, toItem: lastLabel, attribute: .right, multiplier: 1, constant: xPadding)) self.view.addConstraint(NSLayoutConstraint.init(item: self.view, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: newTagButton, attribute: .rightMargin, multiplier: 1, constant: xPadding)) } tagsAddedToView = false } func shareButtonClicked() { if let copiedGif = self.displayGifViewModel.gifData { let vc = UIActivityViewController(activityItems: [copiedGif], applicationActivities: []) if (vc.responds(to: #selector(getter: UIViewController.popoverPresentationController))) { vc.popoverPresentationController?.sourceView = self.view vc.popoverPresentationController?.barButtonItem = self.shareButton } vc.completionWithItemsHandler = { activityType, completed, items, error in if !completed { return } else { UserDefaults.incrementTotalShares() } } present(vc, animated: true, completion: nil) } else { let ac = UIAlertController(title: "Woahhhh", message: "Something went wrong when processing. Let's do this again", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction.init(title: "OK", style: UIAlertActionStyle.default, handler: nil) ac.addAction(okAction) present(ac, animated: true, completion: nil) } } deinit { self.displayGifViewModel.stopServiceSignals() print("deiniting") } }
mit
e8ad48e91ca8d410b6ce590b2e77a423
44.304636
225
0.711226
4.365667
false
false
false
false
MarcoSero/PolyglotApp
PolyglotAddressBook/Swift Front End/ContactTableViewCell.swift
1
1315
// // Created by Marco Sero on 22/03/15. // Copyright (c) 2015 Marco Sero. All rights reserved. // import UIKit class ContactTableViewCell: UITableViewCell { @IBOutlet weak var contactNameLabel: UILabel! @IBOutlet weak var contactPhoneNumber: UILabel! @IBOutlet weak var contactImageView: UIImageView! var imageDownloadTask: NSURLSessionDataTask? func setup(#contact: Contact, session: NSURLSession, cache: ImageCache) { self.contactNameLabel.text = contact.fullName self.contactPhoneNumber.text = contact.phoneNumber let cacheKey = contact.fullName let cachedData = cache.imageForKey(cacheKey) if (cachedData != nil && cachedData?.length > 0) { self.contactImageView.image = UIImage(data: cachedData) return } self.imageDownloadTask = session.dataTaskWithURL(contact.imageURL, completionHandler: { data, response, error in if error != nil { return } let image = UIImage(data: data) cache.saveImageForKey(cacheKey, imageData: data) self.contactImageView.image = image }) self.imageDownloadTask?.resume() } override func prepareForReuse() { self.imageDownloadTask?.cancel() } }
mit
ebc8524454de7807ffc8855f7165de08
32.717949
120
0.645627
4.981061
false
false
false
false
barteljan/VISPER
VISPER-Wireframe/Classes/Wireframe/DefaultRoutingDelegate.swift
1
3777
// // DefaultRoutingPresenterDelegate.swift // Pods-VISPER-Wireframe_Example // // Created by bartel on 22.11.17. // import Foundation import VISPER_Core import VISPER_Objc open class DefaultRoutingDelegate : RoutingDelegate { public init(){} /// An instance observing controllers before they are presented open var routingObserver: RoutingObserver? /// Event that indicates that a view controller will be presented /// /// - Parameters: /// - controller: The view controller that will be presented /// - routePattern: The route pattern triggering the presentation /// - routingOption: The RoutingOption describing how the controller will be presented /// - parameters: The parameters (data) extraced from the route, or given by the sender /// - routingPresenter: The RoutingPresenter responsible for presenting the controller /// - wireframe: The wireframe presenting the view controller open func willPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) throws { let routeResultObjc = ObjcWrapper.wrapperProvider.routeResult(routeResult: routeResult) controller.routeResultObjc = routeResultObjc if let routingObserver = self.routingObserver { try routingObserver.willPresent(controller: controller, routeResult: routeResult, routingPresenter: routingPresenter, wireframe: wireframe) } controller.willRoute(ObjcWrapper.wrapperProvider.wireframe(wireframe: wireframe), routeResult: routeResultObjc) //notify vc if it should be aware of it if let viewController = controller as? RoutingAwareViewController { viewController.willRoute(wireframe: wireframe, routeResult: routeResult) } } /// Event that indicates that a view controller was presented /// /// - Parameters: /// - controller: The view controller that will be presented /// - routePattern: The route pattern triggering the presentation /// - routingOption: The RoutingOption describing how the controller will be presented /// - parameters: The parameters (data) extraced from the route, or given by the sender /// - routingPresenter: The RoutingPresenter responsible for presenting the controller /// - wireframe: The wireframe presenting the view controller open func didPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { if let routingObserver = self.routingObserver { routingObserver.didPresent(controller: controller, routeResult: routeResult, routingPresenter: routingPresenter, wireframe: wireframe) } controller.didRoute(ObjcWrapper.wrapperProvider.wireframe(wireframe: wireframe), routeResult: ObjcWrapper.wrapperProvider.routeResult(routeResult: routeResult)) //notify vc if it should be aware of it if let viewController = controller as? RoutingAwareViewController { viewController.didRoute(wireframe: wireframe, routeResult: routeResult) } } }
mit
4c6cbb023fdc56db53be663cc9877298
41.438202
107
0.612391
6.305509
false
false
false
false
nerdishbynature/octokit.swift
OctoKit/Time.swift
1
976
import Foundation public enum Time { /** A date formatter for RFC 3339 style timestamps. Uses POSIX locale and GMT timezone so that date values are parsed as absolutes. - [https://tools.ietf.org/html/rfc3339](https://tools.ietf.org/html/rfc3339) - [https://developer.apple.com/library/mac/qa/qa1480/_index.html](https://developer.apple.com/library/mac/qa/qa1480/_index.html) - [https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html) */ public static var rfc3339DateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter }() }
mit
87cd2caa56b2332b25816fb830bfd74e
56.411765
251
0.718238
3.873016
false
false
false
false
varunparashar921/KataExercise
VendingMachine/Model/VendingMachine.swift
1
5893
// // VendingMachine.swift // VendingMachine // // Created by Dulio Denis on 5/29/17. // Copyright © 2017 Mallikarjuna. All rights reserved. // import UIKit // MARK: - Vending Machine Protocol // Protocol defining requirements for what a Vending Machine could be // A concrete vending machine would implement these to vend different // items protocol VendingMachineType { // the selection of items to vend var selection: [VendingSelection] { get } // a selection inventory that the machine contains that conform to the ItemType protocol var inventory: [VendingSelection: ItemType] { get set } // the machine needs to keep track of how much money the user can use to buy things var amountDeposited: Double { get set } // machine needs to set itself up from a fully constructed inventory source init(inventory: [VendingSelection: ItemType]) // when vending there are many error conditions where things can go wrong // so we'll need to create a throwing function func vend(_ selection: VendingSelection, quantity: Double) throws // add cash to the vending machine func deposit(_ amount: Double) // convenience function to return the correct item or nil func itemForCurrentSelection(_ selection: VendingSelection) -> ItemType? } // MARK: - Item Type Protocol // Protocol representing what a Vending Item could be protocol ItemType { // price of the item which can not change var price: Double { get } // quantity of items which can change var quantity: Double { get set } } // MARK: - Error Types enum InventoryError: Error { case invalidResource case conversionError case invalidKey } enum VendingMachineError: Error { case invalidSelection case outOfStock // associated value to let user know how much they need to complete case insufficientFunds(required: Double) } // MARK: - Helper Classes class PlistConverter { // class or type method class func dictionaryFromFile(_ name: String, ofType type: String) throws -> [String:AnyObject] { guard let path = Bundle.main.path(forResource: name, ofType: type) else { throw InventoryError.invalidResource } guard let dictionary = NSDictionary(contentsOfFile: path), let castedDictionary = dictionary as? [String:AnyObject] else { throw InventoryError.conversionError } return castedDictionary } } class InventoryUnarchiver { class func vendingInventoryFromDictionary(_ dictionary: [String : AnyObject]) throws -> [VendingSelection : ItemType] { var inventory: [VendingSelection:ItemType] = [ : ] // variable initialized to an empty dictionary for (key, value) in dictionary { if let itemDictionary = value as? [String : Double], let price = itemDictionary["price"], let quantity = itemDictionary["quantity"] { let item = VendingItem(price: price, quantity: quantity) guard let matchedKey = VendingSelection(rawValue: key) else { throw InventoryError.invalidKey } inventory.updateValue(item, forKey: matchedKey) } } return inventory } } // MARK: - Concrete Vending Selection Enum // The enum encapsulating the various selection options in a vending machine enum VendingSelection: String { case Soda case DietSoda case Chips case Cookie case Sandwich case Wrap case CandyBar case PopTart case Water case FruitJuice case SportsDrink case Gum func icon() -> UIImage { if let image = UIImage(named: self.rawValue) { return image } return UIImage(named: "Default")! } } // MARK: - Vending Item Struct // The Object to represent a Vending Item which conforms to the ItemType Protocol struct VendingItem: ItemType { var price: Double var quantity: Double } // MARK: - Vending Machine Class // The concrete implementation of a Vending Machine conforming to the VendingMachineType Protocol // This works best as a class that models state and we can maintain a reference to the values class VendingMachine: VendingMachineType { var selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum] var inventory: [VendingSelection: ItemType] var amountDeposited: Double = 10.0 required init(inventory: [VendingSelection : ItemType]) { self.inventory = inventory } func vend(_ selection: VendingSelection, quantity: Double) throws { guard var item = inventory[selection] else { throw VendingMachineError.invalidSelection } guard item.quantity > 0 else { throw VendingMachineError.outOfStock } // figure out the required amount (unit price * how much they want) let totalPrice = item.price * quantity // if the user can afford it then purchase it if amountDeposited >= totalPrice { amountDeposited -= totalPrice item.quantity -= quantity inventory.updateValue(item, forKey: selection) } else { // otherwise let them know how much more they need let amountRequired = totalPrice - amountDeposited throw VendingMachineError.insufficientFunds(required: amountRequired) } } // convenience method to return the correct item or nil func itemForCurrentSelection(_ selection: VendingSelection) -> ItemType? { return inventory[selection] } func deposit(_ amount: Double) { amountDeposited += amount } }
mit
10060ecb56114f036bccb91b95837387
29.6875
155
0.659029
4.813725
false
false
false
false