repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
luckymore0520/GreenTea
Loyalty/Cards/ViewModel/LoyaltyCoinDataSource.swift
1
1285
// // LoyaltyCoinDataSource.swift // Loyalty // // Created by WangKun on 16/4/18. // Copyright © 2016年 WangKun. All rights reserved. // import UIKit class LoyaltyCoinDataSource: NSObject,RatioPresentable { var currentCount: Int var totalCount: Int init(collectionView:UICollectionView,ratioPresentable:RatioPresentable) { self.currentCount = ratioPresentable.currentCount self.totalCount = ratioPresentable.totalCount super.init() collectionView.dataSource = self collectionView.registerReusableCell(MoneyCollectionViewCell.self) } } extension LoyaltyCoinDataSource:UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.totalCount } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(indexPath: indexPath) as MoneyCollectionViewCell cell.updateLabelState(indexPath.row + 1, isCollected: indexPath.row <= self.currentCount - 1) return cell } }
mit
samirahmed/iosRadialMenu
RadialMenuTests/CircleHelpersTests.swift
1
1493
// // CircleHelpersTests.swift // RadialMenu // // Created by Brad Jasper on 6/7/14. // Copyright (c) 2014 Brad Jasper. All rights reserved. // import XCTest class CircleHelpersTests: XCTestCase { func testDeegreesToRadians() { XCTAssertEqual(degreesToRadians(0), 0) XCTAssertEqual(degreesToRadians(180), M_PI) XCTAssertEqual(degreesToRadians(360), M_PI*2) } func testRadiansToDegreese() { XCTAssertEqual(radiansToDegrees(0), 0) XCTAssertEqual(radiansToDegrees(M_PI), 180) XCTAssertEqual(radiansToDegrees(M_PI*2), 360) } func testIsFullCircle() { XCTAssertTrue(isFullCircle(180, 540)) XCTAssertTrue(isFullCircle(0, 360)) XCTAssertTrue(isFullCircle(180.0, 540.0)) XCTAssertTrue(isFullCircle(0.1, 360.1)) XCTAssertTrue(isFullCircle(180, 900)) } func testGetPointAlongCircle() { let max = 10, minAngle = 0.0, maxAngle = 360.0, radius = 100.0 let firstPoint = getPointAlongCircle(0, max, minAngle, maxAngle, radius) XCTAssertEqual(firstPoint.x, 100.0) XCTAssertEqual(firstPoint.y, 0) // better way to check this? let secondPoint = getPointAlongCircle(1, max, minAngle, maxAngle, radius) XCTAssertTrue(secondPoint.x > 80 && secondPoint.x < 81, "X pos is wrong \(secondPoint.x)") XCTAssertTrue(secondPoint.y > 58 && secondPoint.y < 59, "Y pos is wrong \(secondPoint.y)") } }
mit
marinehero/LeetCode-Solutions-in-Swift
Solutions/Solutions/Easy/Easy_008_String_to_Integer_atoi.swift
3
2994
/* https://oj.leetcode.com/problems/string-to-integer-atoi/ #8 String to Integer (atoi) Level: easy Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. Inspired by @yuruofeifei at https://oj.leetcode.com/discuss/8886/my-simple-solution */ // Helper private extension String { subscript (index: Int) -> Character { return self[self.startIndex.advancedBy(index)] } } class Easy_008_String_to_Integer_atoi { // O (N) class func atoi(str: String) -> Int { var sign: Bool = true, len: Int = str.characters.count, base: Int = 0 for j in 0..<len { let zeroString: String = String("0") let zeroValue: Int = Int(zeroString.utf8[zeroString.utf8.startIndex]) if base == 0 && str[j] == " " || str[j] == "+" { continue } else if base == 0 && str[j] == "-" { sign = false continue } else { let integerValue: Int = Int(str.utf8[str.utf8.startIndex.advancedBy(j)]) - zeroValue if integerValue >= 0 && integerValue <= 9 { if base > Int.max/10 || (base == Int.max/10 && integerValue > 7) { if sign { return Int.max } else { return Int.min } } base = integerValue + 10 * base } } } if sign { return base } else { return 0 - base } } }
mit
joao-parana/udemy-swift-course
Programacao-sem-Complicacao/PsC/playgrounds/Licao-01.playground/section-14.swift
3
89
var 🔓 = "DESPROTEGIDO" var 🔒 = "BLOQUEADO" let reload = "🔄" let play = "▶️"
mit
Ben21hao/edx-app-ios-new
Source/TDUserCenterViewController/Views/TDUserCenterView.swift
1
7301
// // TDUserCenterView.swift // edX // // Created by Elite Edu on 17/4/14. // Copyright © 2017年 edX. All rights reserved. // import UIKit class TDUserCenterView: UIView,UITableViewDataSource { internal let tableView = UITableView() internal var score = Double()//宝典 internal var statusCode = Int() //认证状态 400 未认证,200 提交成功 ,201 已认证,202 认证失败 internal var coupons = Double()//优惠券 internal var orders = Double()//订单 private let toolModel = TDBaseToolModel.init() private var isHidePuchase = true //默认隐藏内购 typealias clickHeaderImageBlock = () -> () var clickHeaderImageHandle : clickHeaderImageBlock? var userProfile: UserProfile? var networkManager: NetworkManager? override init(frame: CGRect) { super.init(frame: frame) setViewConstraint() toolModel.showPurchase() toolModel.judHidePurchseHandle = {(isHide:Bool?)in //yes 不用内购;no 使用内购 self.isHidePuchase = isHide! } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: UI func setViewConstraint() { self.backgroundColor = OEXStyles.sharedStyles().baseColor5() self.tableView.backgroundColor = OEXStyles.sharedStyles().baseColor6() self.tableView.tableFooterView = UIView.init() self.tableView.dataSource = self self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0) self.addSubview(self.tableView) self.tableView.snp_makeConstraints { (make) in make.left.right.top.bottom.equalTo(self) } } func populateFields(profile: UserProfile, editable : Bool, networkManager : NetworkManager) { //认证状态 -- 400 未认证,200 提交成功 ,201 已认证,202 认证失败 statusCode = profile.statusCode! self.userProfile = profile self.networkManager = networkManager self.score = profile.remainscore! //学习宝典 self.coupons = profile.coupon! //优惠券 self.orders = profile.order! //未支付订单 self.tableView.reloadData() } //MARK: tableview Datasource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else if section == 1 { if self.isHidePuchase == true { return 3 } else { return 1 } } else { return 2 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //邮箱或手机 let baseTool = TDBaseToolModel.init() if indexPath.section == 0 { let cell = TDUserMessageCell.init(style: .Default, reuseIdentifier: "UserMessageCell") cell.accessoryType = .DisclosureIndicator cell.selectionStyle = .None let tap = UITapGestureRecognizer.init(target: self, action: #selector(gotoAuthenVc)) cell.headerImageView.addGestureRecognizer(tap) if self.userProfile != nil { //用户名 if self.userProfile!.nickname != nil { cell.nameLabel.text = self.userProfile!.nickname } else { if self.userProfile!.name != self.userProfile!.username { cell.nameLabel.text = self.userProfile!.name } else { cell.nameLabel.text = Strings.noName } } if self.userProfile!.phone != nil { let newStr = baseTool.setPhoneStyle(self.userProfile!.phone) cell.acountLabel.text = newStr } else { let newStr = baseTool.setEmailStyle(self.userProfile!.email) cell.acountLabel.text = newStr } if self.networkManager != nil { cell.headerImageView.remoteImage = self.userProfile?.image(self.networkManager!) } if statusCode == 400 || statusCode == 202 { cell.statusLabel.text = Strings.tdUnvertified cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor6() cell.statusLabel.textColor = OEXStyles.sharedStyles().baseColor8() } else if statusCode == 200 { cell.statusLabel.text = Strings.tdProcessing cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor2() cell.statusLabel.textColor = UIColor.whiteColor() } else if statusCode == 201 { cell.statusLabel.text = Strings.tdVertified cell.statusLabel.backgroundColor = OEXStyles.sharedStyles().baseColor4() cell.statusLabel.textColor = UIColor.whiteColor() } } return cell } else { let cell = TDUserCeterCell.init(style: .Default, reuseIdentifier: "UserCenterCell") cell.accessoryType = .DisclosureIndicator var imageStr : String var titleStr : String if indexPath.section == 1 { switch indexPath.row { case 0: titleStr = Strings.studyCoins cell.messageLabel.attributedText = baseTool.setDetailString(Strings.nowHave(count: String(format: "%.2f",score)), withFont: 12, withColorStr: "#A7A4A4") imageStr = "baodian" case 1: titleStr = Strings.couponPaper cell.messageLabel.text = Strings.couponNumber(count:String(format: "%.0f",coupons)) imageStr = "coupons" default: titleStr = Strings.courseOrder cell.messageLabel.text = Strings.orderCount(count: String(format: "%.0f",orders)) imageStr = "Page" } } else { switch indexPath.row { case 0: titleStr = "讲座" cell.messageLabel.text = "讲座预约报名" imageStr = "lecture_image" default: titleStr = "助教服务" cell.messageLabel.text = "助教服务订单列表" imageStr = "assistant_image" } } cell.titleLabel.text = titleStr cell.iconImageView.image = UIImage.init(named: imageStr) return cell } } func gotoAuthenVc() { if (clickHeaderImageHandle != nil) { clickHeaderImageHandle!() } } }
apache-2.0
jianghongbing/APIReferenceDemo
Swift/Syntax/Number.playground/Contents.swift
1
2946
//: Playground - noun: a place where people can play import UIKit //Swift中的数字类型 //1.整型:在32位系统中等同于Int32,在64位系统中等同于Int64,自动根据处理器的架构来确定整型的长度 let age = 10 //1.1 获取整型的最大值和最小值 let intMax = Int.max let intMin = Int.min //1.2 其他整型 Int8, Int16,UInt8等,使用方式和Int类似,只是在内存中所占据的字节数不同,因此它们的大小范围也不相同 let int8: Int8 = 14 let int16: Int16 = 16 //2.双精度浮点型Double:双进度类型的大小为64位.如果没有显示指明浮点数的类型,系统默认会自动推断为Double类型 let weight = 70.5 //隐式声明一个Double类型的常量,自动推断为double类型,而不是float类型 let height: Double = 170.50 //3.单精度浮点型:如果需要申明一个Float类型的数,需要显示申明 let distance: Float = 100.5 //4.浮点类型数的一些操作 //4.1四舍五入 var testValue = 1.56 var roundedValue = testValue.rounded() testValue.rounded() //对自己做四舍五入,自己的值会变为四舍五入后的值 var testValueTwo = 2.5 roundedValue = testValueTwo.rounded(.awayFromZero) //去最近的那个大于或者等于自己的整数作为最后的结果 roundedValue = testValueTwo.rounded(.down) //向下取整,相当于C中的floor函数的功能 roundedValue = testValueTwo.rounded(.up) //想上取整,想当于C中的ceil函数的功能 roundedValue = testValueTwo.rounded(.toNearestOrAwayFromZero)//取离自己最近且被允许范围内的整数作为最后的结果,如果到某两个数的距离相等,去较大的那个.eg:2.5到2和到3的距离相等,结果为3 roundedValue = testValueTwo.rounded(.toNearestOrEven)//取离自己最近且被允许范围内的整数作为最后的结果,如果到某两个数的距离相等,去为偶数的那个 eg:2.5,结果为2, 3.5结果为4 roundedValue = testValueTwo.rounded(.towardZero) //去最近的那个小于或等于自己的整数作为最后的结果 //testValueTwo.round(.awayFromZero) //同rounded一样,只不过将最后的结果做为自己 //4.1其他的操作 let nan = Double.nan; //not a number let infinity = Double.infinity //无穷大 let pi = Double.pi //圆周率 let isZero = 0.0.isZero let isNan = nan.isNaN let isEqual = 5.0.isEqual(to: 4.0) //等同于 5.0 == 4.0 let isInfinity = pi.isInfinite //是不是一个无穷大的数 let isFinity = pi.isFinite //是不是一个有限数 let squreRoot = 25.0.squareRoot() //平方根 let absValue = (-1.0).magnitude //绝对值 //5浮点数之间的比较 ==等于, >大于,>=大于或等于, <小于,<=小于或者等于,比较和其他语言差不多 //6.数字类型之间的四则运算:由于Swift是强语言类型,为了确保类型的安全,不同类型之间不能进行四则运算,在进行四则运算之前,必须将他们转换成相同的类型,四则运算和其他语言中基本一致
mit
kylehickinson/FastImage
FastImage/Size Decoders/JPGSizeDecoder.swift
1
4352
// // JPGSizeDecoder.swift // FastImage // // Created by Kyle Hickinson on 2019-03-23. // Copyright © 2019 Kyle Hickinson. All rights reserved. // import Foundation /// JPEG Size decoder /// /// File structure: http://www.fileformat.info/format/jpeg/egff.htm /// JPEG Tags: https://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html final class JPGSizeDecoder: ImageSizeDecoder { static var imageFormat: FastImage.ImageFormat { return .jpg } static func isDecoder(for data: Data) throws -> Bool { let signature: [UInt8] = [0xFF, 0xD8] return try data.readBytes(0..<2) == signature } private enum SearchState { case findHeader case determineFrameType case skipFrame case foundSOF case foundEOI } static func size(for data: Data) throws -> CGSize { var searchState: SearchState = .findHeader var offset = 2 var imageOrientation: UIImage.Orientation? while offset < data.count { switch searchState { case .findHeader: while try data.read(offset) != 0xFF { offset += 1 } searchState = .determineFrameType case .determineFrameType: // We've found a data marker, now we determine what type of data we're looking at. // FF E0 -> FF EF are 'APPn', and include lots of metadata like EXIF, etc. // // What we want to find is one of the SOF (Start of Frame) header, cause' it includes // width and height (what we want!) // // JPEG Metadata Header Table // http://www.xbdev.net/image_formats/jpeg/tut_jpg/jpeg_file_layout.php // Each of these SOF data markers have the same data structure: // struct { // UInt16 header; // e.g. FFC0 // UInt16 frameLength; // UInt8 samplePrecision; // UInt16 imageHeight; // UInt16 imageWidth; // ... // we only care about this part // } let sample = try data.read(offset) offset += 1 // Technically we should check if this has EXIF data here (looking for FFE1 marker)… // Maybe TODO later switch sample { case 0xE1: let exifLength = CFSwapInt16BigToHost(try data.read(from: offset, length: 2)) let exifString = String(bytes: try data.readBytes(offset+2..<offset+6), encoding: .ascii) if exifString == "Exif" { let exifData = data.advanced(by: offset + 8) if let exif = try? Exif(data: exifData), imageOrientation == nil { #if swift(>=5.0) imageOrientation = exif.orientation #else imageOrientation = exif?.orientation #endif } } offset += Int(exifLength) searchState = .findHeader case 0xE0...0xEF: // Technically we should check if this has EXIF data here (looking for FFE1 marker)… searchState = .skipFrame case 0xC0...0xC3, 0xC5...0xC7, 0xC9...0xCB, 0xCD...0xCF: searchState = .foundSOF case 0xFF: searchState = .determineFrameType case 0xD9: // We made it to the end of the file somehow without finding the size? Likely a corrupt file searchState = .foundEOI default: // Since we don't handle every header case default to skipping an unknown data marker searchState = .skipFrame } case .skipFrame: let frameLength = Int(CFSwapInt16BigToHost(try data.read(offset..<offset+2) as UInt16)) offset += frameLength - 1 searchState = .findHeader case .foundSOF: offset += 3 let height = try data.read(offset..<offset+2) as UInt16 let width = try data.read(offset+2..<offset+4) as UInt16 if let orientation = imageOrientation, orientation.rawValue >= 5 { // Rotated return CGSize( width: CGFloat(CFSwapInt16BigToHost(height)), height: CGFloat(CFSwapInt16BigToHost(width)) ) } return CGSize( width: CGFloat(CFSwapInt16BigToHost(width)), height: CGFloat(CFSwapInt16BigToHost(height)) ) case .foundEOI: throw SizeNotFoundError(data: data) } } throw SizeNotFoundError(data: data) } }
mit
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Profile/Setting/C/QRCodeViewController.swift
1
15381
// // QRCodeViewController.swift // ProductionReport // // Created by i-Techsys.com on 16/12/29. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit import MobileCoreServices class QRCodeViewController: UIViewController { fileprivate lazy var isHiddenNavBar: Bool = false // 是否隐藏导航栏 fileprivate lazy var imageView: UIImageView = { let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) imageView.isUserInteractionEnabled = true imageView.center = self.view.center imageView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(QRCodeViewController.longClick(longPress:)))) imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(QRCodeViewController.tapClick(tap:)))) self.view.addSubview(imageView) return imageView }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.orange setUpMainView() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let label = UILabel(frame: CGRect(x: 20, y: 80, width: 300, height: 100)) label.text = "我说:不知道为什么,水平菜" label.sizeToFit() label.frame.size.width += CGFloat(30) label.frame.size.height += CGFloat(30) label.layer.cornerRadius = 20 label.layer.masksToBounds = true label.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) let attrStr = NSMutableAttributedString(string: label.text!) attrStr.setAttributes([NSAttributedString.Key.backgroundColor: UIColor.red], range: NSMakeRange(0, attrStr.length)) attrStr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], range: NSMakeRange(0, 3)) attrStr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.blue], range: NSMakeRange(3, 10)) // UIColor(red: 32, green: 43, blue: 120, alpha: 0.5) label.textAlignment = .center label.attributedText = attrStr self.view.addSubview(label) isHiddenNavBar = !isHiddenNavBar UIView.animate(withDuration: 1.0) { self.navigationController?.setNavigationBarHidden(self.isHiddenNavBar, animated: true) } } } // MARK: - 设置UI extension QRCodeViewController { fileprivate func setUpMainView() { let backBtn = UIButton(type: .custom) backBtn.showsTouchWhenHighlighted = true backBtn.setTitle("❎", for: .normal) backBtn.sizeToFit() backBtn.frame.origin = CGPoint(x: 20, y: 30) backBtn.addTarget(self, action: #selector(QRCodeViewController.backBtnClick), for: .touchUpInside) if self.navigationController == nil { self.view.addSubview(backBtn) } self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(takePhotoFromAlbun)) imageView.image = creatQRCByString(QRCStr: "https://github.com/LYM-mg/MGDYZB", QRCImage: "placehoderImage") } @objc fileprivate func backBtnClick() { self.dismiss(animated: true, completion: nil) } } // MARK: - 扫描系统相片中二维码和录制视频 extension QRCodeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate { @objc fileprivate func takePhotoFromAlbun() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in } let OKAction = UIAlertAction(title: "拍照", style: .default) { (action) in self.openCamera(.camera) } let videotapeAction = UIAlertAction(title: "录像", style: .default) { (action) in self.openCamera(.camera, title: "录像") } let destroyAction = UIAlertAction(title: "从相册上传", style: .default) { (action) in print(action) self.openCamera(.photoLibrary) } alertController.addAction(cancelAction) alertController.addAction(OKAction) alertController.addAction(videotapeAction) alertController.addAction(destroyAction) // 判断是否为pad 弹出样式 present(alertController, animated: true, completion: nil) } /** * 打开照相机/打开相册 */ func openCamera(_ type: UIImagePickerController.SourceType,title: String? = "") { if !UIImagePickerController.isSourceTypeAvailable(type) { self.showInfo(info: "Camera不可用") return } let ipc = UIImagePickerController() ipc.sourceType = type ipc.allowsEditing = true ipc.delegate = self if title == "录像" { ipc.videoMaximumDuration = 60 * 3 ipc.videoQuality = .typeIFrame1280x720 ipc.mediaTypes = [(kUTTypeMovie as String)] // 可选,视频最长的录制时间,这里是20秒,默认为10分钟(600秒) ipc.videoMaximumDuration = 20 // 可选,设置视频的质量,默认就是TypeMedium // ipc.videoQuality = UIImagePickerControllerQualityType.typeMedium } present(ipc, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { let mediaType = info[UIImagePickerController.InfoKey.mediaType] as! String //判读是否是视频还是图片 if mediaType == kUTTypeMovie as String { let moviePath = info[UIImagePickerController.InfoKey.mediaURL] as? URL //获取路径 let moviePathString = moviePath!.relativePath if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePathString){ UISaveVideoAtPathToSavedPhotosAlbum(moviePathString, self, #selector(QRCodeViewController.video(_:didFinishSavingWithError:contextInfo:)), nil) } print("视频") } else { print("图片") let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage imageView.image = image getQRCodeInfo(image: image!) } picker.dismiss(animated: true, completion: nil) } @objc func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) { guard error == nil else{ self.showMessage(info: "保存视频失败") return } self.showMessage(info: "保存视频成功") } } // MARK: - 生成二维码和手势点击 extension QRCodeViewController { /// 生成一张二维码图片 /** - parameter QRCStr:网址URL - parameter QRCImage:图片名称 */ fileprivate func creatQRCByString(QRCStr: String?, QRCImage: String?) -> UIImage? { if let QRCStr = QRCStr { let stringData = QRCStr.data(using: .utf8, allowLossyConversion: false) // 创建一个二维码滤镜 guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } // 恢复滤镜的默认属性 filter.setDefaults() filter.setValue(stringData, forKey: "inputMessage") filter.setValue("H", forKey: "inputCorrectionLevel") let qrCIImage = filter.outputImage // 创建一个颜色滤镜,黑白色 guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil } colorFilter.setDefaults() colorFilter.setValue(qrCIImage, forKey: "inputImage") let r = CGFloat(arc4random_uniform(256))/255.0 let g = CGFloat(arc4random_uniform(256))/255.0 let b = CGFloat(arc4random_uniform(256))/255.0 colorFilter.setValue(CIColor(red: r, green: g, blue: b), forKey: "inputColor0") colorFilter.setValue(CIColor(red: b, green: g, blue: r), forKey: "inputColor1") let codeImage = UIImage(ciImage: (colorFilter.outputImage! .transformed(by: CGAffineTransform(scaleX: 5, y: 5)))) // 通常,二维码都是定制的,中间都会放想要表达意思的图片 if let QRCImage = UIImage(named: QRCImage!) { let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height) // 开启上下文 let context = UIGraphicsGetCurrentContext() UIGraphicsBeginImageContextWithOptions(rect.size, true, 1.0) codeImage.draw(in: rect) let iconSize = CGSize(width: codeImage.size.width*0.25, height: codeImage.size.height*0.25) let iconOrigin = CGPoint(x: (codeImage.size.width-iconSize.width)/2, y: (codeImage.size.height-iconSize.height)/2) QRCImage.draw(in: CGRect(origin: iconOrigin, size: iconSize)) guard let resultImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil } context?.setFillColor(red: 0, green: 0, blue: 0, alpha: 0.8) context?.addEllipse(in: rect) context?.drawPath(using: CGPathDrawingMode.fill) // 结束上下文 UIGraphicsEndImageContext() return resultImage } return codeImage } return nil } @objc fileprivate func longClick(longPress: UILongPressGestureRecognizer) { showAlertVc(ges: longPress) } @objc fileprivate func tapClick(tap: UITapGestureRecognizer) { showAlertVc(ges: tap) } fileprivate func showAlertVc(ges: UIGestureRecognizer) { let alertVc = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let qrcAction = UIAlertAction(title: "保存图片", style: .default) { (action) in self.saveImage() } let saveAction = UIAlertAction(title: "识别图中二维码", style: .default) {[unowned self] (action) in self.getQRCodeInfo(image: self.imageView.image!) } let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) alertVc.addAction(qrcAction) alertVc.addAction(saveAction) alertVc.addAction(cancelAction) // 判断是否为pad 弹出样式 if let popPresenter = alertVc.popoverPresentationController { popPresenter.sourceView = ges.view; popPresenter.sourceRect = (ges.view?.bounds)! } DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.present(alertVc, animated: true, completion: nil) } } /// 取得图片中的信息 fileprivate func getQRCodeInfo(image: UIImage) { // 1.创建扫描器 guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) else { return } // 2.扫描结果 guard let ciImage = CIImage(image: image) else { return } let features = detector.features(in: ciImage) // 3.遍历扫描结果 for f in features { guard let feature = f as? CIQRCodeFeature else { return } if (feature.messageString?.isEmpty)! { return } // 如果是网址就跳转 if feature.messageString!.contains("http://") || feature.messageString!.contains("https://") { let url = URL(string: feature.messageString!) if UIApplication.shared.canOpenURL(url!) { UIApplication.shared.openURL(url!) } } else { // 其他信息 弹框显示 debugPrint(feature.messageString) } } } fileprivate func saveImage() { // UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil) // 将图片保存到相册中 // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(QRCodeViewController.image(_:didFinishSavingWithError:contextInfo:)), nil) } // MARK:- 保存图片的方法 @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) { guard error == nil else{ self.showMessage(info: "保存图片失败") return } self.showMessage(info: "保存图片成功") } fileprivate func showMessage(info: String) { let alertView = UIAlertView(title: nil, message: info, delegate: nil, cancelButtonTitle: "好的") alertView.show() } } // MARK: - 生成条形码 extension QRCodeViewController { /// 生成一张条形码方法 /** - parameter QRCStr:网址URL - parameter QRCImage:图片名称 */ fileprivate func barCodeImageWithInfo(info: String?) -> UIImage? { // 创建条形码 // 创建一个二维码滤镜 guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else { return nil } // 恢复滤镜的默认属性 filter.setDefaults() // 将字符串转换成NSData let data = info?.data(using: .utf8) // 通过KVO设置滤镜inputMessage数据 filter.setValue(data, forKey: "inputMessage") // 获得滤镜输出的图像 let outputImage = filter.outputImage // 将CIImage 转换为UIImage let image = UIImage(cgImage: outputImage as! CGImage) // 如果需要将image转NSData保存,则得用下面的方式先转换为CGImage,否则NSData 会为nil // CIContext *context = [CIContext contextWithOptions:nil]; // CGImageRef imageRef = [context createCGImage:outputImage fromRect:outputImage.extent]; // // UIImage *image = [UIImage imageWithCGImage:imageRef]; return image } } func resizeQRCodeImage(_ image: CIImage, withSize size: CGFloat) -> UIImage { let extent = image.extent.integral let scale = min(size / extent.width, size / extent.height) let width = extent.width*scale let height = extent.height*scale let colorSpaceRef: CGColorSpace? = CGColorSpaceCreateDeviceGray() let contextRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpaceRef!, bitmapInfo: CGBitmapInfo.init(rawValue: 0).rawValue) let context = CIContext(options: nil) let imageRef: CGImage = context.createCGImage(image, from: extent)! contextRef!.interpolationQuality = CGInterpolationQuality.init(rawValue: 0)! contextRef?.scaleBy(x: scale, y: scale) contextRef?.draw(imageRef, in: extent) let imageRefResized: CGImage = contextRef!.makeImage()! return UIImage(cgImage: imageRefResized) }
mit
vgatto/protobuf-swift
src/ProtocolBuffers/ProtocolBuffersTests/ProtocolBuffersTests.swift
5
2829
// // ProtocolBuffersTests.swift // ProtocolBuffersTests // // Created by Alexey Khokhlov on 15.09.14. // Copyright (c) 2014 alexeyxo. All rights reserved. // import Foundation import XCTest import ProtocolBuffers class ProtocolBuffersTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPerformance() { // var originalBuilder = PBPerfomance.Builder() // originalBuilder.setInts(Int32(-32)) // .setInts64(Int64(-64)) // .setDoubles(Double(12.12)) // .setFloats(Float(123.123)) // .setStr("string") // let original = originalBuilder.build() // // let original2 = PBPerfomance.parseFromData(original.data()) // var builder = PBPerfomanceBatch.Builder() // // for _ in 0...2 { // builder.batch += [original] // } // // var user:PBUser! = nil // var group = PBGroup.Builder() // // group.getOwnerBuilder().setGroupName("asdfasdf") // // var bazBuilder = PBBaz.Builder() // bazBuilder.getBarBuilder().getFooBuilder().setVal(10) // let build = builder.build() // self.measureBlock() { // var baz = bazBuilder.build() // var gg = group.build() // println(baz) // println(gg) } } // // func testPerformanceJson() // { // // var dict:NSMutableDictionary = NSMutableDictionary() // // dict.setObject(NSNumber(int: 32), forKey: "ints") // // dict.setObject(NSNumber(integer: 64), forKey: "ints64") // // dict.setObject(NSNumber(float: 123.123), forKey: "floats") // // dict.setObject(NSNumber(double: 12.12), forKey: "double") // // dict.setObject("string", forKey: "string") // // var arr:Array<NSMutableDictionary> = [] // for _ in 0...10000 // { // arr += [dict] // } // // var res:NSMutableDictionary = NSMutableDictionary() // // res.setObject(arr, forKey: "object") // // var error:NSError? // // var jsonobject = NSJSONSerialization.dataWithJSONObject(res, options: NSJSONWritingOptions.PrettyPrinted, error:&error) // // self.measureBlock() { // // for _ in 0...1 { // // var jsonErrorOptional:NSError? // let clone2: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonobject!, options: NSJSONReadingOptions(0), error: &jsonErrorOptional) // } // // } // // } }
apache-2.0
ErokRuyam/Logger_in_Swift
Logging/Logging/ViewController.swift
1
1431
// // ViewController.swift // Logging // // Created by Mayur on 05/10/17. // Copyright © 2017 Mayur. All rights reserved. // import UIKit import Logger class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let logConfig = LogConfiguration.init(logDirectory: nil, logFilename: "MyAppLogs", logMessageDateFormat: "yyyy-MM-dd hh:mm:ss a", logLevel: Log.Level.debug, logFileSize: nil, logFileRotateCount: 10) Log.sharedInstance.initializeWithConfiguration(logConfig) Log.sharedInstance.logInfo(#file, message: "Info") Log.sharedInstance.logDebug(#file, message: "Debug") Log.sharedInstance.logWarning(#file, message: "Warning") Log.sharedInstance.logError(#file, message: "Error") Log.sharedInstance.logFunction(#function) if Log.sharedInstance.appDidCrashLastTime() { Log.sharedInstance.logInfo(#file, message: "Do handle the crash logs.") Log.sharedInstance.clearCrashFlag() } let logDir = Log.sharedInstance.getLogDirectory() Log.sharedInstance.logInfo(#file, message: "\(logDir)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
benlangmuir/swift
test/Generics/trivial_reduction.swift
6
675
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // CHECK-LABEL: trivial_reduction.(file).P1@ // CHECK-LABEL: Requirement signature: <Self where Self == Self.[P1]C.[P1]C, Self.[P1]C : P1, Self.[P1]C == Self.[P1]R> protocol P1 { associatedtype R : P1 where R.R == Self associatedtype C : P1 where C.C == Self, C.R == Self, R.C.R.C == Self } // CHECK-LABEL: trivial_reduction.(file).P2@ // CHECK-LABEL: Requirement signature: <Self where Self == Self.[P2]C, Self.[P2]C == Self.[P2]R> protocol P2 { associatedtype R : P2 where R.R == Self associatedtype C : P2 where C.C.C == Self, C.C.R.C.C.R == Self, R.C.R.C.R.C == Self }
apache-2.0
fedtuck/Spine
Spine/ResourceCollection.swift
1
6960
// // ResourceCollection.swift // Spine // // Created by Ward van Teijlingen on 30-12-14. // Copyright (c) 2014 Ward van Teijlingen. All rights reserved. // import Foundation import BrightFutures /** A ResourceCollection represents a collection of resources. It contains a URL where the resources can be fetched. For collections that can be paginated, pagination data is stored as well. */ public class ResourceCollection: NSObject, NSCoding { /// Whether the resources for this collection are loaded public var isLoaded: Bool /// The URL of the current page in this collection. public var resourcesURL: NSURL? /// The URL of the next page in this collection. public var nextURL: NSURL? /// The URL of the previous page in this collection. public var previousURL: NSURL? /// The loaded resources public internal(set) var resources: [ResourceProtocol] = [] // MARK: Initializers public init(resources: [ResourceProtocol], resourcesURL: NSURL? = nil) { self.resources = resources self.resourcesURL = resourcesURL self.isLoaded = !isEmpty(resources) } // MARK: NSCoding public required init(coder: NSCoder) { isLoaded = coder.decodeBoolForKey("isLoaded") resourcesURL = coder.decodeObjectForKey("resourcesURL") as? NSURL resources = coder.decodeObjectForKey("resources") as! [ResourceProtocol] } public func encodeWithCoder(coder: NSCoder) { coder.encodeBool(isLoaded, forKey: "isLoaded") coder.encodeObject(resourcesURL, forKey: "resourcesURL") coder.encodeObject(resources, forKey: "resources") } // MARK: Subscript and count /// Returns the loaded resource at the given index. public subscript (index: Int) -> ResourceProtocol { return resources[index] } /// Returns a loaded resource identified by the given type and id, /// or nil if no loaded resource was found. public subscript (type: String, id: String) -> ResourceProtocol? { return resources.filter { $0.id == id && $0.type == type }.first } /// Returns how many resources are loaded. public var count: Int { return resources.count } /** Calls the passed callback if the resources are loaded. :param: callback A function taking an array of Resource objects. :returns: This collection. */ public func ifLoaded(callback: ([ResourceProtocol]) -> Void) -> Self { if isLoaded { callback(resources) } return self } /** Calls the passed callback if the resources are not loaded. :param: callback A function :returns: This collection */ public func ifNotLoaded(callback: () -> Void) -> Self { if !isLoaded { callback() } return self } } extension ResourceCollection: SequenceType { public typealias Generator = IndexingGenerator<[ResourceProtocol]> public func generate() -> Generator { return resources.generate() } } /** A LinkedResourceCollection represents a collection of resources that is linked from another resource. The main differences with ResourceCollection is that it is mutable, and the addition of `linkage`, and a self `URL` property. A LinkedResourceCollection keeps track of resources that are added to and removed from the collection. This allows Spine to make partial updates to the collection when it is persisted. */ public class LinkedResourceCollection: ResourceCollection { /// The type/id pairs of resources present in this link. public var linkage: [ResourceIdentifier]? /// The URL of the link object of this collection. public var linkURL: NSURL? /// Resources added to this linked collection, but not yet persisted. public internal(set) var addedResources: [ResourceProtocol] = [] /// Resources removed from this linked collection, but not yet persisted. public internal(set) var removedResources: [ResourceProtocol] = [] public required init() { super.init(resources: [], resourcesURL: nil) } public init(resourcesURL: NSURL?, linkURL: NSURL?, linkage: [ResourceIdentifier]?) { super.init(resources: [], resourcesURL: resourcesURL) self.linkURL = linkURL self.linkage = linkage } public convenience init(resourcesURL: NSURL?, linkURL: NSURL?, homogenousType: ResourceType, IDs: [String]) { self.init(resourcesURL: resourcesURL, linkURL: linkURL, linkage: IDs.map { ResourceIdentifier(type: homogenousType, id: $0) }) } public required init(coder: NSCoder) { super.init(coder: coder) linkURL = coder.decodeObjectForKey("linkURL") as? NSURL addedResources = coder.decodeObjectForKey("addedResources") as! [ResourceProtocol] removedResources = coder.decodeObjectForKey("removedResources") as! [ResourceProtocol] if let encodedLinkage = coder.decodeObjectForKey("linkage") as? [NSDictionary] { linkage = encodedLinkage.map { ResourceIdentifier(dictionary: $0) } } } public override func encodeWithCoder(coder: NSCoder) { super.encodeWithCoder(coder) coder.encodeObject(linkURL, forKey: "linkURL") coder.encodeObject(addedResources, forKey: "addedResources") coder.encodeObject(removedResources, forKey: "removedResources") if let linkage = linkage { let encodedLinkage = linkage.map { $0.toDictionary() } coder.encodeObject(encodedLinkage, forKey: "linkage") } } // MARK: Mutators /** Adds the given resource to this collection. This marks the resource as added. :param: resource The resource to add. */ public func addResource(resource: ResourceProtocol) { resources.append(resource) addedResources.append(resource) removedResources = removedResources.filter { $0 !== resource } } /** Adds the given resources to this collection. This marks the resources as added. :param: resources The resources to add. */ public func addResources(resources: [ResourceProtocol]) { for resource in resources { addResource(resource) } } /** Removes the given resource from this collection. This marks the resource as removed. :param: resource The resource to remove. */ public func removeResource(resource: ResourceProtocol) { resources = resources.filter { $0 !== resource } addedResources = addedResources.filter { $0 !== resource } removedResources.append(resource) } /** Adds the given resource to this collection, but does not mark it as added. :param: resource The resource to add. */ internal func addResourceAsExisting(resource: ResourceProtocol) { resources.append(resource) removedResources = removedResources.filter { $0 !== resource } addedResources = addedResources.filter { $0 !== resource } } } extension LinkedResourceCollection: ExtensibleCollectionType { public var startIndex: Int { return resources.startIndex } public var endIndex: Int { return resources.endIndex } public func reserveCapacity(n: Int) { resources.reserveCapacity(n) } public func append(newElement: ResourceProtocol) { addResource(newElement) } public func extend<S : SequenceType where S.Generator.Element == ResourceProtocol>(seq: S) { for element in seq { addResource(element) } } }
mit
JiLiZART/InAppValidator
Sources/InAppValidator/Protocols/ReceiptProtocol.swift
1
199
import Foundation public protocol ReceiptProtocol { //associatedtype PurchaseItem; var code: Int { get } var receipt: String { get } var purchases: [PurchaseItemProtocol] { get } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/27480-void.swift
13
259
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d{{enum b{let e=1 {{struct a{func i{e=c
apache-2.0
ngageoint/geopackage-mapcache-ios
mapcache-ios/data/MCTileServerRepository.swift
1
20916
// // MCWMSUtil.swift // mapcache-ios // // Created by Tyler Burgett on 9/28/20. // Copyright © 2020 NGA. All rights reserved. // import Foundation @objc class MCTileServerRepository: NSObject, XMLParserDelegate, URLSessionDelegate { @objc static let shared = MCTileServerRepository() private override init() { super.init() self.loadUserDefaults() } var tileServers: [String:MCTileServer] = [:] var layers: [MCLayer] = [] // Objects for keeping track of which tile server and or layer are being used as basemaps managed by the settings view controller and displayed on the map. /** Object for keeping track of the user basemap. */ @objc var baseMapServer:MCTileServer = MCTileServer.init(); /** In the case of a WMS server you will also need to set which layer the user wanted to use as a basemap. Not needed and can be left as default for XYZ servers. */ @objc var baseMapLayer:MCLayer = MCLayer.init(); // URL query parameters let getCapabilities = "request=GetCapabilities" let getMap = "request=GetMap" let service = "service=WMS" let version = "version=1.3.0" let bboxTemplate = "bbox={minLon},{minLat},{maxLon},{maxLat}" let webMercatorEPSG = "crs=EPSG:3857" // a few constants that identify what element names we're looking for inside the XML let layerKey = "Layer" let getMapKey = "GetMap" let formatKey = "Format" let dictionaryKeys = Set<String>(["CRS", "Name", "Title", "Name", "Format"]) let userDefaults = UserDefaults.standard; var layerDictionary = NSMutableDictionary() var formats: [String] = [] var currentValue = String() // the current value that the parser is handling var currentTag = String() var parentTag = String() var topLevelLayer = MCLayer() var currentLayer = MCLayer() var urlString = "" var level = 0 var tagStack: [String] = [] var layerTitleStack: [String] = [] var username = "" var password = "" @objc func tileServerForURL(urlString: String) -> MCTileServer { if let tileServer:MCTileServer = self.tileServers[urlString] { return tileServer } return MCTileServer.init(serverName: "") } @objc func isValidServerURL(urlString: String, completion: @escaping (MCTileServerResult) -> Void) { self.isValidServerURL(urlString: urlString, username: "", password: "", completion: completion) } @objc func isValidServerURL(urlString: String, username:String, password:String, completion: @escaping (MCTileServerResult) -> Void) { var tryXYZ = false; var tryWMS = false; var editedURLString = urlString let tileServer = MCTileServer.init(serverName: urlString) tileServer.url = urlString; if (urlString.contains("{z}") && urlString.contains("{y}") && urlString.contains("{x}")) { editedURLString.replaceSubrange(editedURLString.range(of: "{x}")!, with: "0") editedURLString.replaceSubrange(editedURLString.range(of: "{y}")!, with: "0") editedURLString.replaceSubrange(editedURLString.range(of: "{z}")!, with: "0") tryXYZ = true } else { tryWMS = true } guard let url:URL = URL.init(string: editedURLString) else { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: "Invalid URL", errorType: MCServerErrorType.MCURLInvalid)) completion(result) return } if (tryXYZ) { URLSession.shared.downloadTask(with: url) { (location, response, error) in do { if let e = error { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: e.localizedDescription, errorType: MCServerErrorType.MCTileServerNoResponse)) completion(result) return } guard let tile = UIImage.init(data: try Data.init(contentsOf: location!)) else { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: "Unable to get tile", errorType: MCServerErrorType.MCNoData)) completion(result) return } tileServer.serverType = .xyz completion(MCTileServerResult.init(tileServer, self.generateError(message: "No error", errorType: MCServerErrorType.MCNoError))) } catch { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: "No response from server", errorType: MCServerErrorType.MCTileServerNoResponse)) completion(result) } }.resume() } else if (tryWMS) { self.getCapabilites(url: urlString, username: username, password: password, completion: completion) } else { tileServer.serverType = .error let error:MCServerError = MCServerError.init(domain: "MCTileServerRepository", code: MCServerErrorType.MCURLInvalid.rawValue, userInfo: ["message" : "Invalid URL"]) completion(MCTileServerResult.init(tileServer, error)) } } @objc public func getCapabilites(url:String, completion: @escaping (MCTileServerResult) -> Void) { self.getCapabilites(url: url, username: "", password: "", completion: completion) } @objc public func getCapabilites(url:String, username:String, password:String, completion: @escaping (MCTileServerResult) -> Void) { self.username = username self.password = password let tileServer = MCTileServer.init(serverName: self.urlString) tileServer.url = url guard let wmsURL:URL = URL.init(string: url) else { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: "Invalid URL", errorType: MCServerErrorType.MCURLInvalid)) completion(result) return } if wmsURL.host == nil || wmsURL.scheme == nil { tileServer.serverType = .error let result = MCTileServerResult.init(tileServer, self.generateError(message: "Invalid URL", errorType: MCServerErrorType.MCURLInvalid)) completion(result) return } var baseURL:String = wmsURL.scheme! + "://" + wmsURL.host! if let port = wmsURL.port { baseURL = baseURL + ":\(port)" } if wmsURL.path != "" { baseURL = baseURL + wmsURL.path } var builtURL = URLComponents(string: baseURL) builtURL?.queryItems = [ URLQueryItem(name: "request", value: "GetCapabilities"), URLQueryItem(name: "service", value: "WMS"), URLQueryItem(name: "version", value: "1.3.0") ] let builtURLString = builtURL!.string! tileServer.builtURL = builtURLString self.layers = [] let sessionConfig = URLSessionConfiguration.default var urlRequest = URLRequest.init(url: (builtURL?.url)!) urlRequest.httpMethod = "GET" if username != "" && password != "" { let loginString = String(format: "%@:%@", username, password) let loginData = loginString.data(using: String.Encoding.utf8)! let base64LoginString = loginData.base64EncodedString() sessionConfig.httpAdditionalHeaders = ["Authorization":"Basic \(base64LoginString)"] } let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: .main) let task = session.dataTask(with: urlRequest) { data, response, error in if let error = error { print("Connection Error \(error.localizedDescription)") completion(MCTileServerResult.init(tileServer, self.generateError(message: error.localizedDescription, errorType: .MCNoError))) } if let urlResponse = response as? HTTPURLResponse { if urlResponse.statusCode == 401 { completion(MCTileServerResult.init(tileServer, self.generateError(message: error?.localizedDescription ?? "Login to download tiles", errorType: .MCUnauthorized))) return } else if urlResponse.statusCode != 200 { completion(MCTileServerResult.init(tileServer, self.generateError(message: error?.localizedDescription ?? "Server error", errorType: .MCTileServerParseError))) return } else { } } guard let data = data, error == nil else { completion(MCTileServerResult.init(tileServer, self.generateError(message: error?.localizedDescription ?? "Server error", errorType: .MCTileServerParseError))) return } let parser = XMLParser(data: data) parser.delegate = self if parser.parse() { print("have \(self.layers.count) layers") for layer in self.layers { print("Title: \(layer.title)") print("Name: \(layer.name)") print("CRS: \(layer.crs)") print("Format: \(layer.format)\n\n") } tileServer.serverType = .wms tileServer.builtURL = (builtURL?.string)! tileServer.layers = self.layers self.layers = [] completion(MCTileServerResult.init(tileServer, self.generateError(message: "No error", errorType: MCServerErrorType.MCNoError))) } else if (parser.parserError != nil) { print("Parser error") tileServer.serverType = .error self.layers = [] let error:MCServerError = MCServerError.init(domain: "MCTileServerRepository", code: MCServerErrorType.MCURLInvalid.rawValue, userInfo: ["message" : "invalid URL"]) completion(MCTileServerResult.init(tileServer, error)) } } task.resume() } func buildMapCacheURLs(url:String) { if var components = URLComponents(string: url) { print("building url..") for layer in layers { components.queryItems = [ URLQueryItem(name: "service", value: "WMS"), URLQueryItem(name: "request", value: "GetMap"), URLQueryItem(name: "layers", value: layer.name), URLQueryItem(name: "styles", value: ""), URLQueryItem(name: "format", value: layer.format), URLQueryItem(name: "transparent", value: "true"), URLQueryItem(name: "version", value: "1.3.0"), URLQueryItem(name: "width", value: "256"), URLQueryItem(name: "height", value: "256"), URLQueryItem(name: "crs", value: "3857"), URLQueryItem(name: "bbox", value: "{minLon},{minLat},{maxLon},{maxLat}") ] print(components.url!.absoluteString) } } } // MARK: URLSessionDelegate func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { //let credentials = URLCredential(user: self.username, password: self.password, persistence: .forSession) completionHandler(.useCredential, URLCredential()) } // MARK: WMS XML parsing func parserDidStartDocument(_ parser: XMLParser) { print("parserDidStartDocument") } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { level += 1 tagStack.append(elementName) if elementName == layerKey { if (topLevelLayer.title == "") { topLevelLayer = currentLayer layers.append(topLevelLayer) } currentLayer = MCLayer() } currentValue = "" } func parser(_ parser: XMLParser, foundCharacters string: String) { currentValue += string } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { level -= 1 if elementName == layerKey { if (currentLayer.title != "") { currentLayer.titles = self.layerTitleStack layers.append(currentLayer) self.layerTitleStack.popLast() } else { if (self.layerTitleStack.count > 0) { self.layerTitleStack.popLast() } } currentLayer = MCLayer() } else if dictionaryKeys.contains(elementName) { if elementName == "CRS" { currentLayer.crs = "EPSG:3857" } else if elementName == "Title" { if (tagStack.count > 2 && tagStack[tagStack.count - 2] == "Layer"){ print("topLevelLayer.title: \(self.topLevelLayer.title) currentValue: \(currentValue)") currentLayer.title = currentValue self.layerTitleStack.append(currentValue) } } else if elementName == "Name" { if (tagStack.count > 2 && tagStack[tagStack.count - 2] == "Layer"){ currentLayer.name = currentValue } } else if elementName == "Format" && currentLayer.format == "" { if currentValue == "image/jpeg" { currentLayer.format = "image/jpeg" } else if currentValue == "image/png" { currentLayer.format = "image/png" } } else { //print("hmm, something unexpected found \(currentValue)") } } else if elementName == formatKey { formats.append(currentValue) } currentValue = String() tagStack.popLast() } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { print(parseError) currentValue = String() } func generateError(message:String, errorType: MCServerErrorType) -> MCServerError { return MCServerError.init(domain: "MCTileServerRepository", code: errorType.rawValue, userInfo: ["message" : message]) } @objc func saveToUserDefaults(serverName:String, url:String, tileServer:MCTileServer) -> Bool { tileServer.serverName = serverName if var savedServers = self.userDefaults.dictionary(forKey: MC_SAVED_TILE_SERVER_URLS) { savedServers[serverName] = url self.userDefaults.setValue(savedServers, forKey: MC_SAVED_TILE_SERVER_URLS) self.tileServers[serverName] = tileServer return true } else if self.userDefaults.dictionary(forKey: MC_SAVED_TILE_SERVER_URLS) == nil { let savedServers = NSMutableDictionary() savedServers[serverName] = url self.userDefaults.setValue(savedServers, forKey: MC_SAVED_TILE_SERVER_URLS) self.tileServers[serverName] = tileServer return true } return false } @objc func setBasemap(tileServer:MCTileServer?, layer:MCLayer?) { if let updatedServer = tileServer, let updatedLayer = layer { self.baseMapServer = updatedServer self.baseMapLayer = updatedLayer saveBasemapToUserDefaults(serverName: updatedServer.serverName, layerName: updatedLayer.name) } else { saveBasemapToUserDefaults(serverName: "", layerName: "") self.baseMapServer = MCTileServer() self.baseMapLayer = MCLayer() } } @objc func saveBasemapToUserDefaults(serverName:String, layerName:String) { self.userDefaults.setValue(serverName, forKey: MC_USER_BASEMAP_SERVER_NAME) self.userDefaults.setValue(layerName, forKey: MC_USER_BASEMAP_LAYER_NAME) self.userDefaults.synchronize() } @objc func removeTileServerFromUserDefaults(serverName:String) { // get the defaults if var savedServers = self.userDefaults.dictionary(forKey: MC_SAVED_TILE_SERVER_URLS) { savedServers.removeValue(forKey: serverName) self.tileServers.removeValue(forKey: serverName) self.userDefaults.setValue(savedServers, forKey: MC_SAVED_TILE_SERVER_URLS) } // check if the server that was deleted was a being used as a basemap, and if so delete it if let currentBasemap:String = self.userDefaults.object(forKey: MC_USER_BASEMAP_SERVER_NAME) as? String { if (currentBasemap.elementsEqual(serverName)) { self.saveBasemapToUserDefaults(serverName: "", layerName: "") } } } // Load or refresh the tile server list from UserDefaults. @objc func loadUserDefaults() { let savedBasemapServerName = self.userDefaults.string(forKey: MC_USER_BASEMAP_SERVER_NAME) let savedBasemapLayerName = self.userDefaults.string(forKey: MC_USER_BASEMAP_LAYER_NAME) if let savedServers = self.userDefaults.dictionary(forKey: MC_SAVED_TILE_SERVER_URLS) { for serverName in savedServers.keys { if let serverURL = savedServers[serverName] { print("\(serverName) \(serverURL)") self.isValidServerURL(urlString: serverURL as! String) { (tileServerResult) in let serverError:MCServerError = tileServerResult.failure as! MCServerError if (serverError.code == MCServerErrorType.MCNoError.rawValue) { print("MCTileServerRepository:loadUserDefaults - Valid URL") if let tileServer = tileServerResult.success as? MCTileServer { tileServer.serverName = serverName self.tileServers[serverName] = tileServer if tileServer.serverName == savedBasemapServerName { self.baseMapServer = tileServer if tileServer.serverType == MCTileServerType.wms { for layer in tileServer.layers { if layer.name == savedBasemapLayerName { self.baseMapLayer = layer } } } } NotificationCenter.default.post(name: Notification.Name(MC_USER_BASEMAP_LOADED_FROM_DEFAULTS), object: nil) } } else if serverError.code == MCServerErrorType.MCUnauthorized.rawValue { let tileServer = tileServerResult.success as? MCTileServer tileServer?.serverName = serverName tileServer?.serverType = .authRequired self.tileServers[serverName] = tileServer } else { let tileServer = tileServerResult.success as? MCTileServer tileServer?.serverName = serverName tileServer?.serverType = .error self.tileServers[serverName] = tileServer } } } } } } @objc func getTileServers() -> [String:MCTileServer] { return self.tileServers } }
mit
khizkhiz/swift
test/Interpreter/enum_resilience.swift
2
8916
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -c %S/../Inputs/resilient_enum.swift -I %t/ -o %t/resilient_enum.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -c %S/../Inputs/resilient_enum.swift -I %t/ -o %t/resilient_enum.o // RUN: %target-build-swift %s -Xlinker %t/resilient_struct.o -Xlinker %t/resilient_enum.o -I %t -L %t -o %t/main // RUN: %target-run %t/main // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif import resilient_enum import resilient_struct var ResilientEnumTestSuite = TestSuite("ResilientEnum") ResilientEnumTestSuite.test("ResilientEmptyEnum") { let e = ResilientEmptyEnum.X let n: Int switch e { case .X: n = 0 default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientSingletonEnum") { let o: AnyObject = ArtClass() let e = ResilientSingletonEnum.X(o) let n: Int switch e { case .X(let oo): n = 0 expectTrue(o === oo) default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientSingletonGenericEnum") { let o = ArtClass() let e = ResilientSingletonGenericEnum.X(o) let n: Int switch e { case .X(let oo): n = 0 expectEqual(o === oo, true) default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientNoPayloadEnum") { let a: [ResilientNoPayloadEnum] = [.A, .B, .C] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 default: return -1 } } expectEqual(b, [0, 1, 2]) } ResilientEnumTestSuite.test("ResilientSinglePayloadEnum") { let o = ArtClass() let a: [ResilientSinglePayloadEnum] = [.A, .B, .C, .X(o)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(o === oo) return 3 default: return -1 } } expectEqual(b, [0, 1, 2, 3]) } ResilientEnumTestSuite.test("ResilientSinglePayloadGenericEnum") { let o = ArtClass() let a: [ResilientSinglePayloadGenericEnum<ArtClass>] = [.A, .B, .C, .X(o)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(o === oo) return 3 default: return -1 } } expectEqual(b, [0, 1, 2, 3]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnum") { let a: [ResilientMultiPayloadEnum] = [.A, .B, .C, .X(1), .Y(2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let x): expectEqual(x, 1) return 3 case .Y(let y): expectEqual(y, 2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumRoundTrip") { let a = [0, 1, 2, 3, 4] let b = a.map { makeResilientMultiPayloadEnum(1122, i: $0) } let c: [Int] = b.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let x): expectEqual(x, 1122) return 3 case .Y(let y): expectEqual(y, 1122) return 4 default: return -1 } } expectEqual(c, a) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBits") { let o1 = ArtClass() let o2 = ArtClass() let a: [ResilientMultiPayloadEnumSpareBits] = [.A, .B, .C, .X(o1), .Y(o2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo1): expectTrue(oo1 === o1) return 3 case .Y(let oo2): expectTrue(oo2 === o2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBitsRoundTrip") { let o = ArtClass() let a = [0, 1, 2, 3, 4] let b = a.map { makeResilientMultiPayloadEnumSpareBits(o, i: $0) } let c: [Int] = b.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(oo === o) return 3 case .Y(let oo): expectTrue(oo === o) return 4 default: return -1 } } expectEqual(c, a) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBitsAndExtraBits") { let o = ArtClass() let s: SevenSpareBits = (false, 1, 2, 3, 4, 5, 6, 7) let a: [ResilientMultiPayloadEnumSpareBitsAndExtraBits] = [.P1(s), .P2(o), .P3(o), .P4(o), .P5(o), .P6(o), .P7(o), .P8(o)] let b: [Int] = a.map { switch $0 { case .P1(let ss): // FIXME: derive Equatable conformances for arbitrary tuples :-) expectEqual(ss.0, s.0) expectEqual(ss.1, s.1) expectEqual(ss.2, s.2) expectEqual(ss.3, s.3) expectEqual(ss.4, s.4) expectEqual(ss.5, s.5) expectEqual(ss.6, s.6) expectEqual(ss.7, s.7) return 0 case .P2(let oo): expectTrue(oo === o) return 1 case .P3(let oo): expectTrue(oo === o) return 2 case .P4(let oo): expectTrue(oo === o) return 3 case .P5(let oo): expectTrue(oo === o) return 4 case .P6(let oo): expectTrue(oo === o) return 5 case .P7(let oo): expectTrue(oo === o) return 6 case .P8(let oo): expectTrue(oo === o) return 7 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4, 5, 6, 7]) } ResilientEnumTestSuite.test("ResilientMultiPayloadGenericEnum") { let o1 = ArtClass() let o2 = ArtClass() let a: [ResilientMultiPayloadGenericEnum<ArtClass>] = [.A, .B, .C, .X(o1), .Y(o2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo1): expectTrue(oo1 === o1) return 3 case .Y(let oo2): expectTrue(oo2 === o2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } public func getMetadata() -> Any.Type { return Shape.self } ResilientEnumTestSuite.test("DynamicLayoutMetatype") { do { var output = "" let expected = "- resilient_enum.Shape #0\n" dump(getMetadata(), to: &output) expectEqual(output, expected) } do { expectEqual(true, getMetadata() == getMetadata()) } } ResilientEnumTestSuite.test("DynamicLayoutSinglePayload") { let s = Size(w: 10, h: 20) let a: [SimpleShape] = [.KleinBottle, .Triangle(s)] let b: [Int] = a.map { switch $0 { case .KleinBottle: return 0 case .Triangle(let s): expectEqual(s.w, 10) expectEqual(s.h, 20) return 1 } } expectEqual(b, [0, 1]) } ResilientEnumTestSuite.test("DynamicLayoutMultiPayload") { let s = Size(w: 10, h: 20) let a: [Shape] = [.Point, .Rect(s), .RoundedRect(s, s)] let b: [Int] = a.map { switch $0 { case .Point: return 0 case .Rect(let s): expectEqual(s.w, 10) expectEqual(s.h, 20) return 1 case .RoundedRect(let s, let ss): expectEqual(s.w, 10) expectEqual(s.h, 20) expectEqual(ss.w, 10) expectEqual(ss.h, 20) return 2 } } expectEqual(b, [0, 1, 2]) } ResilientEnumTestSuite.test("DynamicLayoutMultiPayload2") { let c = Color(r: 1, g: 2, b: 3) let a: [CustomColor] = [.Black, .White, .Custom(c), .Bespoke(c, c)] let b: [Int] = a.map { switch $0 { case .Black: return 0 case .White: return 1 case .Custom(let c): expectEqual(c.r, 1) expectEqual(c.g, 2) expectEqual(c.b, 3) return 2 case .Bespoke(let c, let cc): expectEqual(c.r, 1) expectEqual(c.g, 2) expectEqual(c.b, 3) expectEqual(cc.r, 1) expectEqual(cc.g, 2) expectEqual(cc.b, 3) return 3 } } expectEqual(b, [0, 1, 2, 3]) } // Make sure case numbers round-trip if payload has zero size ResilientEnumTestSuite.test("ResilientEnumWithEmptyCase") { let a: [ResilientEnumWithEmptyCase] = getResilientEnumWithEmptyCase() let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .Empty: return 2 default: return -1 } } expectEqual(b, [0, 1, 2]) } runAllTests()
apache-2.0
szukuro/spacecat-swift
Space Cat/SpaceDogNode.swift
1
2106
// // SpaceDogNode.swift // Space Cat // // Created by László Györi on 24/07/14. // Copyright (c) 2014 László Györi. All rights reserved. // import UIKit import SpriteKit enum SpaceDogType : Int { case SpaceDogTypeA = 0 case SpaceDogTypeB = 1 } class SpaceDogNode: SKSpriteNode { class func spaceDogOfType(type:SpaceDogType) -> SpaceDogNode { var spaceDog : SpaceDogNode var textures : Array<SKTexture> if ( type == SpaceDogType.SpaceDogTypeA) { spaceDog = SpaceDogNode(imageNamed: "spacedog_A_1") textures = [SKTexture(imageNamed: "spacedog_A_1"), SKTexture(imageNamed: "spacedog_A_2"), SKTexture(imageNamed: "spacedog_A_3")] } else if ( type == SpaceDogType.SpaceDogTypeB) { spaceDog = SpaceDogNode(imageNamed: "spacedog_B_1") textures = [SKTexture(imageNamed: "spacedog_B_1"), SKTexture(imageNamed: "spacedog_B_2"), SKTexture(imageNamed: "spacedog_B_3"), SKTexture(imageNamed: "spacedog_B_4")] } else { // need to be initialised no matter what spaceDog = SpaceDogNode() textures = [] } let scale = Util.random(85, max: 100) let scalef = CGFloat(scale) / 100.0 spaceDog.xScale = scalef spaceDog.yScale = scalef let animation = SKAction.animateWithTextures(textures, timePerFrame: 0.1) let repeatAction = SKAction.repeatActionForever(animation) spaceDog.runAction(repeatAction) spaceDog.setupPhysicsBody() return spaceDog } func setupPhysicsBody() { self.physicsBody = SKPhysicsBody(rectangleOfSize: self.frame.size) self.physicsBody.affectedByGravity = false self.physicsBody.categoryBitMask = CollisionCategory.CollisionCategoryEnemy.value self.physicsBody.collisionBitMask = 0 self.physicsBody.contactTestBitMask = CollisionCategory.CollisionCategoryGround.value | CollisionCategory.CollisionCategoryProjectile.value } }
mit
noppoMan/Slimane
Sources/Performance/main.swift
1
1229
import Slimane if Cluster.isMaster { for _ in 0..<ProcessInfo.cpus().count { var worker = try! Cluster.fork(silent: false) } try! _ = Slimane().listen() } else { let app = Slimane() //app.use(Slimane.Static(root: "\(Process.cwd)")) app.use(.get, "/") { request, response, responder in var response = response response.text("Welcome to Slimane!") responder(.respond(response)) } app.`catch` { error, request, response, responder in var response = response switch error { case RoutingError.routeNotFound: response.status(.notFound) response.text("\(error)") case StaticMiddlewareError.resourceNotFound: response.status(.notFound) response.text("\(error)") default: response.status(.internalServerError) response.text("\(error)") } responder(.respond(response)) } app.finally { request, response in print("\(request.method) \(request.path ?? "/") \(response.status.statusCode)") } print("Started HTTP server at 0.0.0.0:3000") try! app.listen() }
mit
Visual-Engineering/HiringApp
HiringApp/HiringAppTests/Tests/UtilityTests.swift
1
2023
// // UtilityTests.swift // HiringApp // // Created by Alba Luján on 26/6/17. // Copyright © 2017 Visual Engineering. All rights reserved. // import XCTest @testable import HiringAppCore import Deferred @testable import BSWFoundation class UtilityTests: XCTestCase { func testParser() { //Given let data = Data(contentsOfJSONFile: "technologies", bundle: Bundle(for: type(of: self))) //When do { let json = try JSONSerialization.jsonObject(with: data, options: []) let model = try [TechnologyModel].decode(json) XCTAssertFalse(model.isEmpty) } catch { XCTAssert(false) } //Then } func testTransformTechnologyRealmToTechnologyModel() { let fakeTechRealm = TechnologyRealm.fake let fakeTechModel = fakeTechRealm.toModel XCTAssert(fakeTechRealm.id == fakeTechModel.id) XCTAssert(fakeTechRealm.title == fakeTechModel.title) XCTAssert(fakeTechRealm.imageURL == fakeTechModel.imageURL) XCTAssert(fakeTechRealm.testAvailable == fakeTechModel.testAvailable) if let realmSubmittedTest: String = fakeTechRealm.submittedTest?["status"] as? String { XCTAssert(realmSubmittedTest == fakeTechModel.submittedTest?["status"]) } } func testTransformTechnologyModelToTechnologyRealm() { let fakeTechModel = TechnologyModel.fake let fakeTechRealm = fakeTechModel.toRealmModel XCTAssert(fakeTechModel.id == fakeTechRealm.id) XCTAssert(fakeTechModel.title == fakeTechRealm.title) XCTAssert(fakeTechModel.imageURL == fakeTechRealm.imageURL) XCTAssert(fakeTechModel.testAvailable == fakeTechRealm.testAvailable) if let realmSubmittedTest: String = fakeTechRealm.submittedTest?["status"] as? String { XCTAssert(realmSubmittedTest == fakeTechModel.submittedTest?["status"]) } } }
apache-2.0
larcus94/ImagePickerSheetController
ImagePickerSheetController/ImagePickerSheetControllerTests/AddingActionTests.swift
3
1950
// // AddingActionTests.swift // ImagePickerSheetController // // Created by Laurin Brandner on 06/09/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // import XCTest import KIF import Nimble import ImagePickerSheetController class AddingActionTests: ImagePickerSheetControllerTests { func testAddingTwoCancelActions() { imageController.addAction(ImagePickerAction(title: "Cancel1", style: .cancel, handler: { _ in })) imageController.addAction(ImagePickerAction(title: "Cancel2", style: .cancel, handler: { _ in })) expect(self.imageController.actions.filter { $0.style == .Cancel }.count) == 1 } func testDisplayOfAddedActions() { let actions: [(String, ImagePickerActionStyle)] = [("Action1", .default), ("Action2", .default), ("Cancel", .cancel)] for (title, style) in actions { imageController.addAction(ImagePickerAction(title: title, style: style, handler: { _ in })) } presentImagePickerSheetController() for (title, _) in actions { tester().waitForView(withAccessibilityLabel: title) } } func testActionOrdering() { imageController.addAction(ImagePickerAction(title: cancelActionTitle, style: .cancel, handler: { _ in })) imageController.addAction(ImagePickerAction(title: defaultActionTitle, handler: { _ in })) expect(self.imageController.actions.map { $0.title }) == [defaultActionTitle, cancelActionTitle] } func testAddingActionAfterPresentation() { presentImagePickerSheetController() imageController.addAction(ImagePickerAction(title: defaultActionTitle, handler: { _ in })) tester().waitForView(withAccessibilityLabel: defaultActionTitle) } }
mit
mojojoseph/SQLite.swift
SQLite Tests/FTSTests.swift
10
2823
import XCTest import SQLite let subject = Expression<String>("subject") let body = Expression<String>("body") class FTSTests: SQLiteTestCase { var emails: Query { return db["emails"] } func test_createVtable_usingFts4_createsVirtualTable() { db.create(vtable: emails, using: fts4(subject, body)) AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\")") } func test_createVtable_usingFts4_withSimpleTokenizer_createsVirtualTableWithTokenizer() { db.create(vtable: emails, using: fts4([subject, body], tokenize: .Simple)) AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", tokenize=simple)") } func test_createVtable_usingFts4_withPorterTokenizer_createsVirtualTableWithTokenizer() { db.create(vtable: emails, using: fts4([subject, body], tokenize: .Porter)) AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", tokenize=porter)") } func test_match_withColumnExpression_buildsMatchExpressionWithColumnIdentifier() { db.create(vtable: emails, using: fts4(subject, body)) AssertSQL("SELECT * FROM \"emails\" WHERE (\"subject\" MATCH 'hello')", emails.filter(match("hello", subject))) } func test_match_withQuery_buildsMatchExpressionWithTableIdentifier() { db.create(vtable: emails, using: fts4(subject, body)) AssertSQL("SELECT * FROM \"emails\" WHERE (\"emails\" MATCH 'hello')", emails.filter(match("hello", emails))) } func test_registerTokenizer_registersTokenizer() { let locale = CFLocaleCopyCurrent() let tokenizer = CFStringTokenizerCreate(nil, "", CFRangeMake(0, 0), UInt(kCFStringTokenizerUnitWord), locale) db.register(tokenizer: "tokenizer") { string in CFStringTokenizerSetString(tokenizer, string, CFRangeMake(0, CFStringGetLength(string))) if CFStringTokenizerAdvanceToNextToken(tokenizer) == .None { return nil } let range = CFStringTokenizerGetCurrentTokenRange(tokenizer) let input = CFStringCreateWithSubstring(kCFAllocatorDefault, string, range) var token = CFStringCreateMutableCopy(nil, range.length, input) CFStringLowercase(token, locale) CFStringTransform(token, nil, kCFStringTransformStripDiacritics, 0) return (token as String, string.rangeOfString(input as String)!) } db.create(vtable: emails, using: fts4([subject, body], tokenize: .Custom("tokenizer"))) AssertSQL("CREATE VIRTUAL TABLE \"emails\" USING fts4(\"subject\", \"body\", tokenize=\"SQLite.swift\" 'tokenizer')") emails.insert(subject <- "Aún más cáfe!") XCTAssertEqual(1, emails.filter(match("aun", emails)).count) } }
mit
makezwl/zhao
Nimble/FailureMessage.swift
81
881
import Foundation @objc public class FailureMessage { public var expected: String = "expected" public var actualValue: String? = "" // empty string -> use default; nil -> exclude public var to: String = "to" public var postfixMessage: String = "match" public var postfixActual: String = "" public init() { } public func stringValue() -> String { var value = "\(expected) \(to) \(postfixMessage)" if let actualValue = actualValue { value = "\(expected) \(to) \(postfixMessage), got \(actualValue)\(postfixActual)" } var lines: [String] = (value as NSString).componentsSeparatedByString("\n") as [String] let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet() lines = lines.map { line in line.stringByTrimmingCharactersInSet(whitespace) } return "".join(lines) } }
apache-2.0
Jubilant-Appstudio/Scuba
ScubaCalendar/Utility/Webservice/APIList.swift
1
904
// // APIList.swift // CredDirectory // // Created by Mahipal on 11/4/17. // Copyright © 2017 Mahipal. All rights reserved. // import UIKit class APIList: NSObject { static let strBaseUrl = "http://scuba.codzgarage.com/" // Base URL static let strUserUrl = "http://scuba.codzgarage.com/api/user/" // User static let strAnimalUrl = "http://scuba.codzgarage.com/api/animal/" // Animal static let strCountryUrl = "http://scuba.codzgarage.com/api/country/" // Country //User Login static let strUserLogin = strUserUrl + "login" //User Login create static let strUserCreate = strUserUrl + "create" //User update profile static let strUserProfile = strUserUrl + "profile" // Animal List static let strAnimalList = strAnimalUrl + "get_list" // Country List static let strCountryList = strCountryUrl + "get_list" }
mit
remirobert/MyCurrency
MyCurrencyTests/NetworkTests.swift
1
1531
// // NetworkTests.swift // MyCurrency // // Created by Remi Robert on 10/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import XCTest class NetworkTests: XCTestCase { private let network = Network() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testRequestAllCurrencies() { var endRequest = false network.perform(ressource: Ressource.all()) { models in endRequest = true XCTAssertNotNil(models) } while (!endRequest) { CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.01, true) } } func testRequestWrongRessource() { var endRequest = false let url = "https://github.com/3lvis/Networking/blob/master/README.md" let ressource = Ressource(url: URL(string: url)!) { data -> [CurrencyModel]? in guard let data = data else { return nil } do { let jsonRoot = try JSONSerialization.jsonObject(with: data, options: []) guard let _ = jsonRoot as? NSDictionary else { return nil } return [] } catch {} return nil } network.perform(ressource: ressource) { models in endRequest = true XCTAssertNil(models) } while (!endRequest) { CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.01, true) } } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/26589-swift-astcontext-allocate.swift
11
411
// 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 // RUN: not %target-swift-frontend %s -parse ([{[{{([{([[[[{{}{
apache-2.0
thyagostall/ios-playground
Week1Project/Week1Project/ViewController.swift
1
886
// // ViewController.swift // Week1Project // // Created by Thyago on 1/23/16. // Copyright © 2016 Thyago. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController { @IBOutlet var webView: UIWebView! @IBOutlet var mapView: MKMapView! override func viewDidLoad() { setMapLocation() setWebPage() } func setWebPage() { let url = NSURL(string: "http://www.thyago.com") let request = NSURLRequest(URL: url!) webView.loadRequest(request) } func setMapLocation() { var currentLocation = CLLocationCoordinate2D() currentLocation.latitude = 42.7255561 currentLocation.longitude = -84.4816436 let region = MKCoordinateRegionMakeWithDistance(currentLocation, 1000, 1000) mapView.setRegion(region, animated: true) } }
gpl-2.0
MarcoSero/HackerNews
HackerNewsTests/Utilities/TestUtilities.swift
5
887
// // TestUtilities.swift // HackerNews // // Created by Marco Sero on 16/07/2015. // Copyright (c) 2015 Marco Sero. All rights reserved. // import Foundation import XCTest // Snippet from https://blog.codecentric.de/en/2014/10/extending-xctestcase-testing-swift-optionals/ extension XCTestCase { func AssertEqualOptional<T : Equatable>(@autoclosure theOptional: () -> T?, @autoclosure _ expression2: () -> T, file: String = __FILE__, line: UInt = __LINE__) { if let e = theOptional() { let e2 = expression2() if e != e2 { self.recordFailureWithDescription("Optional (\(e)) is not equal to (\(e2))", inFile: file, atLine: line, expected: true) } } else { self.recordFailureWithDescription("Optional value is empty", inFile: file, atLine: line, expected: true) } } }
mit
practicalswift/swift
test/Driver/Dependencies/chained-private-after-multiple-nominal-members.swift
6
1463
/// other --> main ==> yet-another /// other ==>+ main ==> yet-another // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/chained-private-after-multiple-nominal-members/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/chained-private-after-multiple-nominal-members/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./yet-another.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND: Handled other.swift // CHECK-SECOND: Handled main.swift // CHECK-SECOND: Handled yet-another.swift
apache-2.0
Zewo/BasicAuthMiddleware
Tests/LinuxMain.swift
1
145
#if os(Linux) import XCTest @testable import BasicAuthMiddlewareTestSuite XCTMain([ testCase(BasicAuthMiddlewareTests.allTests) ]) #endif
mit
coffellas-cto/GDWebViewController
GDWebViewController/GDWebViewController.swift
1
20730
// // GDWebViewController.swift // GDWebBrowserClient // // Created by Alex G on 03.12.14. // Copyright (c) 2015 Alexey Gordiyenko. All rights reserved. // //MIT License // //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 WebKit public enum GDWebViewControllerProgressIndicatorStyle { case activityIndicator case progressView case both case none } @objc public protocol GDWebViewControllerDelegate { @objc optional func webViewController(_ webViewController: GDWebViewController, didChangeURL newURL: URL?) @objc optional func webViewController(_ webViewController: GDWebViewController, didChangeTitle newTitle: NSString?) @objc optional func webViewController(_ webViewController: GDWebViewController, didFinishLoading loadedURL: URL?) @objc optional func webViewController(_ webViewController: GDWebViewController, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) @objc optional func webViewController(_ webViewController: GDWebViewController, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) @objc optional func webViewController(_ webViewController: GDWebViewController, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } open class GDWebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, GDWebViewNavigationToolbarDelegate { // MARK: Public Properties /** An object to serve as a delegate which conforms to GDWebViewNavigationToolbarDelegate protocol. */ open weak var delegate: GDWebViewControllerDelegate? /** The style of progress indication visualization. Can be one of four values: .ActivityIndicator, .ProgressView, .Both, .None*/ open var progressIndicatorStyle: GDWebViewControllerProgressIndicatorStyle = .both /** A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations. The default value is false. */ open var allowsBackForwardNavigationGestures: Bool { get { return webView.allowsBackForwardNavigationGestures } set(value) { webView.allowsBackForwardNavigationGestures = value } } /** A boolean value if set to true shows the toolbar; otherwise, hides it. */ open var showsToolbar: Bool { set(value) { self.toolbarHeight = value ? 44 : 0 } get { return self.toolbarHeight == 44 } } /** A boolean value if set to true shows the refresh control (or stop control while loading) on the toolbar; otherwise, hides it. */ open var showsStopRefreshControl: Bool { get { return toolbarContainer.showsStopRefreshControl } set(value) { toolbarContainer.showsStopRefreshControl = value } } /** The navigation toolbar object (read-only). */ var toolbar: GDWebViewNavigationToolbar { get { return toolbarContainer } } /** Boolean flag which indicates whether JavaScript alerts are allowed. Default is `true`. */ open var allowJavaScriptAlerts = true public var webView: WKWebView! // MARK: Private Properties fileprivate var progressView: UIProgressView! fileprivate var toolbarContainer: GDWebViewNavigationToolbar! fileprivate var toolbarHeightConstraint: NSLayoutConstraint! fileprivate var toolbarHeight: CGFloat = 0 fileprivate var navControllerUsesBackSwipe: Bool = false lazy fileprivate var activityIndicator: UIActivityIndicatorView! = { var activityIndicator = UIActivityIndicatorView() activityIndicator.backgroundColor = UIColor(white: 0, alpha: 0.2) #if swift(>=4.2) activityIndicator.style = .whiteLarge #else activityIndicator.activityIndicatorViewStyle = .whiteLarge #endif activityIndicator.hidesWhenStopped = true activityIndicator.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(activityIndicator) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[activityIndicator]-0-|", options: [], metrics: nil, views: ["activityIndicator": activityIndicator])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[activityIndicator]-0-[toolbarContainer]|", options: [], metrics: nil, views: ["activityIndicator": activityIndicator, "toolbarContainer": self.toolbarContainer, "topGuide": self.topLayoutGuide])) return activityIndicator }() // MARK: Public Methods /** Navigates to an URL created from provided string. - parameter URLString: The string that represents an URL. */ // TODO: Earlier `scheme` property was optional. Now it isn't true. Need to check that scheme is always open func loadURLWithString(_ URLString: String) { if let URL = URL(string: URLString) { if (URL.scheme != "") && (URL.host != nil) { loadURL(URL) } else { loadURLWithString("http://\(URLString)") } } } /** Navigates to the URL. - parameter URL: The URL for a request. - parameter cachePolicy: The cache policy for a request. Optional. Default value is .UseProtocolCachePolicy. - parameter timeoutInterval: The timeout interval for a request, in seconds. Optional. Default value is 0. */ open func loadURL(_ URL: Foundation.URL, cachePolicy: NSURLRequest.CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 0) { webView.load(URLRequest(url: URL, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)) } /** Evaluates the given JavaScript string. - parameter javaScriptString: The JavaScript string to evaluate. - parameter completionHandler: A block to invoke when script evaluation completes or fails. The completionHandler is passed the result of the script evaluation or an error. */ open func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((AnyObject?, NSError?) -> Void)?) { webView.evaluateJavaScript(javaScriptString, completionHandler: completionHandler as! ((Any?, Error?) -> Void)?) } /** Shows or hides toolbar. - parameter show: A Boolean value if set to true shows the toolbar; otherwise, hides it. - parameter animated: A Boolean value if set to true animates the transition; otherwise, does not. */ open func showToolbar(_ show: Bool, animated: Bool) { self.showsToolbar = show if toolbarHeightConstraint != nil { toolbarHeightConstraint.constant = self.toolbarHeight if animated { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.view.layoutIfNeeded() }) } else { self.view.layoutIfNeeded() } } } @objc open func goBack(){ webView.goBack() } @objc open func goForward(){ webView.goForward() } @objc open func stopLoading(){ webView.stopLoading() } @objc open func reload(){ webView.reload() } // MARK: GDWebViewNavigationToolbarDelegate Methods func webViewNavigationToolbarGoBack(_ toolbar: GDWebViewNavigationToolbar) { webView.goBack() } func webViewNavigationToolbarGoForward(_ toolbar: GDWebViewNavigationToolbar) { webView.goForward() } func webViewNavigationToolbarRefresh(_ toolbar: GDWebViewNavigationToolbar) { webView.reload() } func webViewNavigationToolbarStop(_ toolbar: GDWebViewNavigationToolbar) { webView.stopLoading() } // MARK: WKNavigationDelegate Methods open func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { } open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { showLoading(false) if error._code == NSURLErrorCancelled { return } showError(error.localizedDescription) } open func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showLoading(false) if error._code == NSURLErrorCancelled { return } showError(error.localizedDescription) } open func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard ((delegate?.webViewController?(self, didReceiveAuthenticationChallenge: challenge, completionHandler: { (disposition, credential) -> Void in completionHandler(disposition, credential) })) != nil) else { completionHandler(.performDefaultHandling, nil) return } } open func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { } open func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { showLoading(true) } open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard ((delegate?.webViewController?(self, decidePolicyForNavigationAction: navigationAction, decisionHandler: { (policy) -> Void in decisionHandler(policy) if policy == .cancel { self.showError("This navigation is prohibited.") } })) != nil) else { decisionHandler(.allow); return } } open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { guard ((delegate?.webViewController?(self, decidePolicyForNavigationResponse: navigationResponse, decisionHandler: { (policy) -> Void in decisionHandler(policy) if policy == .cancel { self.showError("This navigation response is prohibited.") } })) != nil) else { decisionHandler(.allow) return } } open func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil, let url = navigationAction.request.url{ if url.description.lowercased().range(of: "http://") != nil || url.description.lowercased().range(of: "https://") != nil { webView.load(navigationAction.request) } } return nil } // MARK: WKUIDelegate Methods open func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { if !allowJavaScriptAlerts { return } let alertController: UIAlertController = UIAlertController(title: message, message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: {(action: UIAlertAction) -> Void in completionHandler() })) self.present(alertController, animated: true, completion: nil) } // MARK: Some Private Methods fileprivate func showError(_ errorString: String?) { let alertView = UIAlertController(title: "Error", message: errorString, preferredStyle: .alert) alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertView, animated: true, completion: nil) } fileprivate func showLoading(_ animate: Bool) { if animate { if (progressIndicatorStyle == .activityIndicator) || (progressIndicatorStyle == .both) { activityIndicator.startAnimating() } toolbar.loadDidStart() } else if activityIndicator != nil { if (progressIndicatorStyle == .activityIndicator) || (progressIndicatorStyle == .both) { activityIndicator.stopAnimating() } toolbar.loadDidFinish() } } fileprivate func progressChanged(_ newValue: NSNumber) { if progressView == nil { progressView = UIProgressView() progressView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(progressView) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[progressView]-0-|", options: [], metrics: nil, views: ["progressView": progressView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[progressView(2)]", options: [], metrics: nil, views: ["progressView": progressView, "topGuide": self.topLayoutGuide])) } progressView.progress = newValue.floatValue if progressView.progress == 1 { progressView.progress = 0 UIView.animate(withDuration: 0.2, animations: { () -> Void in self.progressView.alpha = 0 }) } else if progressView.alpha == 0 { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.progressView.alpha = 1 }) } } fileprivate func backForwardListChanged() { if self.navControllerUsesBackSwipe && self.allowsBackForwardNavigationGestures { self.navigationController?.interactivePopGestureRecognizer?.isEnabled = !webView.canGoBack } toolbarContainer.backButtonItem?.isEnabled = webView.canGoBack toolbarContainer.forwardButtonItem?.isEnabled = webView.canGoForward } // MARK: KVO override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else {return} switch keyPath { case "estimatedProgress": if (progressIndicatorStyle == .progressView) || (progressIndicatorStyle == .both) { if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber { progressChanged(newValue) } } case "URL": delegate?.webViewController?(self, didChangeURL: webView.url) case "title": delegate?.webViewController?(self, didChangeTitle: webView.title as NSString?) case "loading": if let val = change?[NSKeyValueChangeKey.newKey] as? Bool { if !val { showLoading(false) backForwardListChanged() delegate?.webViewController?(self, didFinishLoading: webView.url) } } default: super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } // MARK: Overrides // Override this property getter to show bottom toolbar above other toolbars override open var edgesForExtendedLayout: UIRectEdge { get { return UIRectEdge(rawValue: super.edgesForExtendedLayout.rawValue ^ UIRectEdge.bottom.rawValue) } set { super.edgesForExtendedLayout = newValue } } // MARK: Life Cycle override open func viewDidLoad() { super.viewDidLoad() // Set up toolbarContainer self.view.addSubview(toolbarContainer) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[toolbarContainer]-0-|", options: [], metrics: nil, views: ["toolbarContainer": toolbarContainer])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[toolbarContainer]-0-|", options: [], metrics: nil, views: ["toolbarContainer": toolbarContainer])) toolbarHeightConstraint = NSLayoutConstraint(item: toolbarContainer, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: toolbarHeight) toolbarContainer.addConstraint(toolbarHeightConstraint) // Set up webView self.view.addSubview(webView) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[webView]-0-|", options: [], metrics: nil, views: ["webView": webView as WKWebView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topGuide]-0-[webView]-0-[toolbarContainer]|", options: [], metrics: nil, views: ["webView": webView as WKWebView, "toolbarContainer": toolbarContainer, "topGuide": self.topLayoutGuide])) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) webView.removeObserver(self, forKeyPath: "estimatedProgress") webView.removeObserver(self, forKeyPath: "URL") webView.removeObserver(self, forKeyPath: "title") webView.removeObserver(self, forKeyPath: "loading") } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let navVC = self.navigationController { if let gestureRecognizer = navVC.interactivePopGestureRecognizer { navControllerUsesBackSwipe = gestureRecognizer.isEnabled } else { navControllerUsesBackSwipe = false } } } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if navControllerUsesBackSwipe { self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true } } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() webView.stopLoading() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } func commonInit() { webView = WKWebView() webView.navigationDelegate = self webView.uiDelegate = self webView.translatesAutoresizingMaskIntoConstraints = false toolbarContainer = GDWebViewNavigationToolbar(delegate: self) toolbarContainer.translatesAutoresizingMaskIntoConstraints = false } }
mit
mightydeveloper/swift
test/TypeCoercion/overload_noncall.swift
10
1876
// RUN: %target-parse-verify-swift struct X { } struct Y { } struct Z { } func f0(x1: X, x2: X) -> X {} // expected-note{{found this candidate}} func f0(y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}} var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}} func f0_init(x: X, y: Y) -> X {} var f0 : (x : X, y : Y) -> X = f0_init // expected-error{{invalid redeclaration}} func f1(x: X) -> X {} func f2(g: (x: X) -> X) -> ((y: Y) -> Y) { } func test_conv() { var _ : (x1 : X, x2 : X) -> X = f0 var _ : (X, X) -> X = f0 var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0'}} var _ : (X) -> X = f1 var a7 : (X) -> (X) = f1 var a8 : (x2 : X) -> (X) = f1 var a9 : (x2 : X) -> ((X)) = f1 a7 = a8 a8 = a9 a9 = a7 var _ : ((X)->X) -> ((Y) -> Y) = f2; var _ : ((x2 : X)-> (X)) -> (((y2 : Y) -> (Y))) = f2; typealias fp = ((X)->X) -> ((Y) -> Y) var _ = f2 } var xy : X // expected-note {{previously declared here}} var xy : Y // expected-error {{invalid redeclaration of 'xy'}} func accept_X(inout x: X) { } func accept_XY(inout x: X) -> X { } func accept_XY(inout y: Y) -> Y { } func accept_Z(inout z: Z) -> Z { } func test_inout() { var x : X; accept_X(&x); accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}} accept_X(&xy); accept_XY(&x); x = accept_XY(&xy); x = xy; x = &xy; // expected-error{{'&' used with non-inout argument of type 'X'}} accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}} } func lvalue_or_rvalue(inout x: X) -> X { } func lvalue_or_rvalue(x: X) -> Y { } func test_lvalue_or_rvalue() { var x : X; var y : Y; let x1 = lvalue_or_rvalue(&x) x = x1 let y1 = lvalue_or_rvalue(x) y = y1 _ = y }
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers/00626-swift-lexer-lexidentifier.swift
9
289
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T{func g<f{let A{protocol A{{}func a(f.c}}var d=(g<T>(f<T
apache-2.0
aaronraimist/firefox-ios
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
1
12581
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SwiftKeychainWrapper import LocalAuthentication private let logger = Logger.browserLogger private func presentNavAsFormSheet(presented: UINavigationController, presenter: UINavigationController?) { presented.modalPresentationStyle = .FormSheet presenter?.presentViewController(presented, animated: true, completion: nil) } class TurnPasscodeOnSetting: Setting { init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode), delegate: delegate) } override func onClick(navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()), presenter: navigationController) } } class TurnPasscodeOffSetting: Setting { init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode), delegate: delegate) } override func onClick(navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()), presenter: navigationController) } } class ChangePasscodeSetting: Setting { init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) { let attributedTitle: NSAttributedString = (enabled ?? false) ? NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode) : NSAttributedString.disabledTableRowTitle(AuthenticationStrings.changePasscode) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()), presenter: navigationController) } } class RequirePasscodeSetting: Setting { private weak var navigationController: UINavigationController? override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var style: UITableViewCellStyle { return .Value1 } override var status: NSAttributedString { // Only show the interval if we are enabled and have an interval set. let authenticationInterval = KeychainWrapper.authenticationInfo() if let interval = authenticationInterval?.requiredPasscodeInterval where enabled { return NSAttributedString.disabledTableRowTitle(interval.settingTitle) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self.navigationController = settings.navigationController let title = AuthenticationStrings.requirePasscode let attributedTitle = (enabled ?? true) ? NSAttributedString.tableRowTitle(title) : NSAttributedString.disabledTableRowTitle(title) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.authenticationInfo() else { navigateToRequireInterval() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.requirePasscodeTouchReason, success: { self.navigateToRequireInterval() }, cancel: nil, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) }) } else { self.navigateToRequireInterval() } } private func navigateToRequireInterval() { navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true) } } extension RequirePasscodeSetting: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismissViewControllerAnimated(true) { self.navigateToRequireInterval() } } } class TouchIDSetting: Setting { private let authInfo: AuthenticationKeychainInfo? private weak var navigationController: UINavigationController? private weak var switchControl: UISwitch? private var touchIDSuccess: (() -> Void)? = nil private var touchIDFallback: (() -> Void)? = nil init( title: NSAttributedString?, navigationController: UINavigationController? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil, touchIDSuccess: (() -> Void)? = nil, touchIDFallback: (() -> Void)? = nil) { self.touchIDSuccess = touchIDSuccess self.touchIDFallback = touchIDFallback self.navigationController = navigationController self.authInfo = KeychainWrapper.authenticationInfo() super.init(title: title, delegate: delegate, enabled: enabled) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .None // In order for us to recognize a tap gesture without toggling the switch, // the switch is wrapped in a UIView which has a tap gesture recognizer. This way // we can disable interaction of the switch and still handle tap events. let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.on = authInfo?.useTouchID ?? false control.userInteractionEnabled = false switchControl = control let accessoryContainer = UIView(frame: control.frame) accessoryContainer.addSubview(control) let gesture = UITapGestureRecognizer(target: self, action: #selector(TouchIDSetting.switchTapped)) accessoryContainer.addGestureRecognizer(gesture) cell.accessoryView = accessoryContainer } @objc private func switchTapped() { guard let authInfo = authInfo else { logger.error("Authentication info should always be present when modifying Touch ID preference.") return } if authInfo.useTouchID { AppAuthenticator.presentAuthenticationUsingInfo( authInfo, touchIDReason: AuthenticationStrings.disableTouchReason, success: self.touchIDSuccess, cancel: nil, fallback: self.touchIDFallback ) } else { toggleTouchID(enabled: true) } } func toggleTouchID(enabled enabled: Bool) { authInfo?.useTouchID = enabled KeychainWrapper.setAuthenticationInfo(authInfo) switchControl?.setOn(enabled, animated: true) } } class AuthenticationSettingsViewController: SettingsTableViewController { override func viewDidLoad() { super.viewDidLoad() updateTitleForTouchIDState() let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidRemove, object: nil) notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidCreate, object: nil) notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil) tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView" } deinit { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: NotificationPasscodeDidRemove, object: nil) notificationCenter.removeObserver(self, name: NotificationPasscodeDidCreate, object: nil) notificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } override func generateSettings() -> [SettingSection] { if let _ = KeychainWrapper.authenticationInfo() { return passcodeEnabledSettings() } else { return passcodeDisabledSettings() } } private func updateTitleForTouchIDState() { if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) { navigationItem.title = AuthenticationStrings.touchIDPasscodeSetting } else { navigationItem.title = AuthenticationStrings.passcode } } private func passcodeEnabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOffSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: true) ]) var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)] let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) { requirePasscodeSectionChildren.append( TouchIDSetting( title: NSAttributedString.tableRowTitle( NSLocalizedString("Use Touch ID", tableName: "AuthenticationManager", comment: "List section title for when to use Touch ID") ), navigationController: self.navigationController, delegate: nil, enabled: true, touchIDSuccess: { [unowned self] in self.touchIDAuthenticationSucceeded() }, touchIDFallback: { [unowned self] in self.fallbackOnTouchIDFailure() } ) ) } let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren) settings += [ passcodeSection, requirePasscodeSection, ] return settings } private func passcodeDisabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOnSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: false) ]) let requirePasscodeSection = SettingSection(title: nil, children: [ RequirePasscodeSetting(settings: self, delegate: nil, enabled: false), ]) settings += [ passcodeSection, requirePasscodeSection, ] return settings } } extension AuthenticationSettingsViewController { func refreshSettings(notification: NSNotification) { updateTitleForTouchIDState() settings = generateSettings() tableView.reloadData() } } extension AuthenticationSettingsViewController: PasscodeEntryDelegate { private func getTouchIDSetting() -> TouchIDSetting? { guard settings.count >= 2 && settings[1].count >= 2 else { return nil } return settings[1][1] as? TouchIDSetting } func touchIDAuthenticationSucceeded() { getTouchIDSetting()?.toggleTouchID(enabled: false) } func fallbackOnTouchIDFailure() { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) } @objc func passcodeValidationDidSucceed() { getTouchIDSetting()?.toggleTouchID(enabled: false) navigationController?.dismissViewControllerAnimated(true, completion: nil) } }
mpl-2.0
mightydeveloper/swift
validation-test/compiler_crashers/26976-swift-constraints-constraintsystem-opentype.swift
9
284
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let:{enum S{{}class d{struct B<T where f:A{class a{let v:a={
apache-2.0
danielrhodes/Swift-ActionCableClient
Example/ActionCableClient-Example-tVOS/AppDelegate.swift
2
2133
// // AppDelegate.swift // ActionCableClient-Example-tVOS // // Created by Daniel Rhodes on 10/27/16. // Copyright © 2016 Daniel Rhodes. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
huonw/swift
validation-test/compiler_crashers_fixed/27549-swift-namelookup-findlocalval-visitbracestmt.swift
65
454
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck {class a{struct S<I where h:A{class A{func g:a{let t=A{
apache-2.0
Ares42/Portfolio
HackerRankMobile/Extensions/MainTabBarController.swift
1
1110
// // MainTabBarController.swift // HackerRankMobile // // Created by Luke Solomon on 11/9/17. // Copyright © 2017 Solomon Stuff. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { let photoHelper = MGPhotoHelper() override func viewDidLoad() { super.viewDidLoad() photoHelper.completionHandler = { image in PostService.create(for: image) } delegate = self tabBar.unselectedItemTintColor = .black // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension MainTabBarController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { if viewController.tabBarItem.tag == 1 { photoHelper.presentActionSheet(from: self) return false } else { return true } } }
mit
austinzheng/swift
test/Interpreter/formal_access.swift
36
1927
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: swift_test_mode_optimize_none // REQUIRES: rdar44160503 class C: CustomStringConvertible { var value: Int init(_ v: Int) { value = v } var description: String { return String(value) } } var global = [C(1), C(2)] print("Begin") print("1. global[0] == \(global[0])") // CHECK: Begin // CHECK-NEXT: 1. global[0] == 1 func doit(_ local: inout C) { print("2. local == \(local)") print("2. global[0] == \(global[0])") // CHECK-NEXT: 2. local == 1 // CHECK-NEXT: 2. global[0] == 1 // There's a connection between 'local' and 'global[0]'. local = C(4) print("3. local == \(local)") print("3. global[0] == \(global[0])") // CHECK-NEXT: 3. local == 4 // CHECK-NEXT: 3. global[0] == 4 // This assignment is to a different index and so is // not allowed to cause unspecified behavior. global[1] = C(5) print("4. local == \(local)") print("4. global[0] == \(global[0])") // CHECK-NEXT: 4. local == 4 // CHECK-NEXT: 4. global[0] == 4 // The connection is not yet broken. local = C(2) print("5. local == \(local)") print("5. global[0] == \(global[0])") // CHECK-NEXT: 5. local == 2 // CHECK-NEXT: 5. global[0] == 4 // This assignment structurally changes 'global' while a // simultaneous modification is occurring to it. This is // allowed to have unspecified behavior but not to crash. global.append(C(3)) print("6. local == \(local)") print("6. global[0] == \(global[0])") // CHECK-NEXT: 6. local == 2 // CHECK-NEXT: 6. global[0] == 4 // Note that here the connection is broken. local = C(7) print("7. local == \(local)") print("7. global[0] == \(global[0])") // CHECK-NEXT: 7. local == 7 // CHECK-NEXT: 7. global[0] == 4 } doit(&global[0]) print("8. global[0] == \(global[0])") print("End") // CHECK-NEXT: 8. global[0] == 4 // CHECK-NEXT: End
apache-2.0
PJayRushton/StarvingStudentGuide
StarvingStudentGuide/Error.swift
1
938
// // M A R S H A L // // () // /\ // ()--' '--() // `. .' // / .. \ // ()' '() // // import Foundation public enum Error: ErrorType, CustomStringConvertible { case KeyNotFound(key: String) case NullValue(key: String) case TypeMismatch(expected: Any, actual: Any) case TypeMismatchWithKey(key: String, expected: Any, actual: Any) public var description: String { switch self { case let .KeyNotFound(key): return "Key not found: \(key.stringValue)" case let .NullValue(key): return "Null Value found at: \(key.stringValue)" case let .TypeMismatch(expected, actual): return "Type mismatch. Expected type \(expected). Got '\(actual)'" case let .TypeMismatchWithKey(key, expected, actual): return "Type mismatch. Expected type \(expected) for key: \(key). Got '\(actual)'" } } }
mit
box/box-ios-sdk
Sources/BoxSDK.swift
1
29460
// // BoxSDK.swift // BoxSDK // // Created by Abel Osorio on 03/12/19. // Copyright © 2018 Box Inc. All rights reserved. // #if os(iOS) import AuthenticationServices #endif import Foundation /// Closure to return any generic type or an BoxSDKError /// Used to simplify interfaces public typealias Callback<T> = (Result<T, BoxSDKError>) -> Void /// Provides methods for creating BoxSDKClient public class BoxSDK { /// Box-specific constants public enum Constants { /// Root folder identifier public static let rootFolder = "0" /// Current user identifier public static let currentUser = "me" } /// SDK configuration public private(set) var configuration: BoxSDKConfiguration /// Default configuration public static let defaultConfiguration = try! BoxSDKConfiguration() // swiftlint:disable:previous force_try #if os(iOS) private var webSession: AuthenticationSession? #endif private var networkAgent: BoxNetworkAgent /// Auth module providing authorization and token related requests. /// Is set upon BoxSDK initialisation public private(set) var auth: AuthModule /// Initializer /// /// - Parameters: /// - clientId: The client ID of the application requesting authentication. To get the client ID for your application, /// log in to your Box developer console click the Edit Application link for the application you're working with. /// In the OAuth 2 Parameters section of the configuration page, find the item labeled "client_id". The text of that item /// is your application's client ID. /// - clientSecret: The client secret of the application requesting authentication. To get the client secret for your application, /// log in to your Box developer console and click the Edit Application link for the application you're working with. /// In the OAuth 2 Parameters section of the configuration page, find the item labeled "client_secret". /// The text of that item is your application's client secret. /// - callbackURL: An optional custom callback URL string. The URL to which Box redirects the browser when authentication completes. /// The user's actual interaction with your application begins when Box redirects to this URL. /// If not specified, the default URL is used, in the format of `boxsdk-CLIENTID://boxsdkoauth2redirect`, where CLIENTID is replaced with the value of the `clientId` parameter. public init(clientId: String, clientSecret: String, callbackURL: String? = nil) { // swiftlint:disable:next force_try configuration = try! BoxSDKConfiguration(clientId: clientId, clientSecret: clientSecret, callbackURL: callbackURL) networkAgent = BoxNetworkAgent(configuration: configuration) auth = AuthModule(networkAgent: networkAgent, configuration: configuration) } // MARK: - Developer Token Client /// Creates BoxClient object based on developer token /// /// - Parameter token: Developer token /// - Returns: New BoxClient object public static func getClient(token: String) -> BoxClient { let networkAgent = BoxNetworkAgent(configuration: defaultConfiguration) return BoxClient( networkAgent: networkAgent, session: SingleTokenSession( token: token, authModule: AuthModule(networkAgent: networkAgent, configuration: defaultConfiguration) ), configuration: defaultConfiguration ) } /// Creates BoxClient with developer token /// /// - Parameter token: Developer token /// - Returns: New BoxClient object public func getClient(token: String) -> BoxClient { return BoxClient(networkAgent: networkAgent, session: SingleTokenSession(token: token, authModule: auth), configuration: configuration) } // MARK: - JWT Client /// Creates BoxClient using JWT token. /// /// - Parameters: /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - authClosure: Requests new JWT token value when needed. Provide the token value from your token provider. /// - uniqueID: Unique identifier provided for jwt token. /// - completion: Returns standard BoxClient object or error. public func getDelegatedAuthClient( authClosure: @escaping DelegatedAuthClosure, uniqueID: String, tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, completion: @escaping Callback<BoxClient> ) { var designatedTokenStore: TokenStore let networkAgent = BoxNetworkAgent(configuration: configuration) let authModule = AuthModule(networkAgent: networkAgent, configuration: configuration) if tokenInfo == nil, let unWrappedTokenStore = tokenStore { designatedTokenStore = unWrappedTokenStore designatedTokenStore.read { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get delegated auth client - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): let session = DelegatedAuthSession( authModule: authModule, configuration: self.configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, authClosure: authClosure, uniqueID: uniqueID ) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } } else if let tokenInfo = tokenInfo { designatedTokenStore = tokenStore ?? MemoryTokenStore() designatedTokenStore.write(tokenInfo: tokenInfo) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get delegated auth client - BoxSDK deallocated")))) return } switch result { case .success: let session = DelegatedAuthSession( authModule: authModule, configuration: self.configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, authClosure: authClosure, uniqueID: uniqueID ) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } } else { designatedTokenStore = MemoryTokenStore() let session = DelegatedAuthSession( authModule: authModule, configuration: configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, authClosure: authClosure, uniqueID: uniqueID ) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration) completion(.success(client)) } } // MARK: - CCG Client /// Creates BoxClient using Server Authentication with Client Credentials Grant for account service /// /// - Parameters: /// - enterpriseId: The enterprise ID to use when getting the access token. /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - completion: Returns standard BoxClient object or error. public func getCCGClientForAccountService( enterpriseId: String, tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, completion: @escaping Callback<BoxClient> ) { getCCGClinet( connectionType: CCGAuthModule.CCGConnectionType.applicationService(enterpriseId), tokenInfo: tokenInfo, tokenStore: tokenStore, completion: completion ) } /// Creates BoxClient using Server Authentication with Client Credentials Grant for user account /// /// - Parameters: /// - userId: The user ID to use when getting the access token. /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - completion: Returns standard BoxClient object or error. public func getCCGClientForUser( userId: String, tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, completion: @escaping Callback<BoxClient> ) { getCCGClinet( connectionType: CCGAuthModule.CCGConnectionType.user(userId), tokenInfo: tokenInfo, tokenStore: tokenStore, completion: completion ) } /// Creates BoxClient using Server Authentication with Client Credentials Grant /// /// - Parameters: /// - connectionType: The type of CCG connection, either user with userId or application service with enterpriseId. /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - completion: Returns standard BoxClient object or error. private func getCCGClinet( connectionType: CCGAuthModule.CCGConnectionType, tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, completion: @escaping Callback<BoxClient> ) { var designatedTokenStore: TokenStore let authModule = CCGAuthModule(connectionType: connectionType, networkAgent: networkAgent, configuration: configuration) if tokenInfo == nil, let unWrappedTokenStore = tokenStore { designatedTokenStore = unWrappedTokenStore designatedTokenStore.read { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get CCG client - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): let session = CCGAuthSession(authModule: authModule, configuration: self.configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case .failure: let session = CCGAuthSession(authModule: authModule, configuration: self.configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) } } } else if let tokenInfo = tokenInfo { designatedTokenStore = tokenStore ?? MemoryTokenStore() designatedTokenStore.write(tokenInfo: tokenInfo) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get CCG client - BoxSDK deallocated")))) return } switch result { case .success: let session = CCGAuthSession(authModule: authModule, configuration: self.configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } } else { designatedTokenStore = MemoryTokenStore() let session = CCGAuthSession(authModule: authModule, configuration: configuration, tokenInfo: tokenInfo, tokenStore: designatedTokenStore) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration) completion(.success(client)) } } // MARK: - OAUTH2 Client #if os(iOS) /// Creates BoxClient in a completion with OAuth 2.0 type of authentication /// /// - Parameters: /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - context: The ViewController that is presenting the OAuth request /// - completion: Returns created standard BoxClient object or error @available(iOS 13.0, *) public func getOAuth2Client( tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, context: ASWebAuthenticationPresentationContextProviding, completion: @escaping Callback<BoxClient> ) { var designatedTokenStore: TokenStore if tokenInfo == nil, let unWrappedTokenStore = tokenStore { designatedTokenStore = unWrappedTokenStore designatedTokenStore.read { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get OAuth 2 client - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case .failure: self.startOAuth2WebSession(completion: completion, tokenStore: designatedTokenStore, context: context) } } } else if let tokenInfo = tokenInfo { designatedTokenStore = tokenStore ?? MemoryTokenStore() designatedTokenStore.write(tokenInfo: tokenInfo) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get OAuth 2 client - BoxSDK deallocated")))) return } switch result { case .success: let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } } else { designatedTokenStore = MemoryTokenStore() startOAuth2WebSession(completion: completion, tokenStore: designatedTokenStore, context: context) } } #endif /// Creates BoxClient in a completion with OAuth 2.0 type of authentication /// /// - Parameters: /// - tokenInfo: Information about token /// - tokenStore: Custom token store. To use custom store, implement TokenStore protocol. /// - completion: Returns created standard BoxClient object or error @available(iOS 11.0, *) public func getOAuth2Client( tokenInfo: TokenInfo? = nil, tokenStore: TokenStore? = nil, completion: @escaping Callback<BoxClient> ) { var designatedTokenStore: TokenStore if tokenInfo == nil, let unWrappedTokenStore = tokenStore { designatedTokenStore = unWrappedTokenStore designatedTokenStore.read { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get OAuth 2 client - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case .failure: self.startOAuth2WebSession(completion: completion, tokenStore: designatedTokenStore) } } } else if let tokenInfo = tokenInfo { designatedTokenStore = tokenStore ?? MemoryTokenStore() designatedTokenStore.write(tokenInfo: tokenInfo) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get OAuth 2 client - BoxSDK deallocated")))) return } switch result { case .success: let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: designatedTokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } } else { designatedTokenStore = MemoryTokenStore() startOAuth2WebSession(completion: completion, tokenStore: designatedTokenStore) } } // swiftlint:enable cyclomatic_complexity // MARK: - OAuthWebAuthenticationable related #if os(iOS) @available(iOS 13.0, *) func startOAuth2WebSession(completion: @escaping Callback<BoxClient>, tokenStore: TokenStore, context: ASWebAuthenticationPresentationContextProviding) { obtainAuthorizationCodeFromWebSession(context: context) { result in switch result { case let .failure(error): completion(.failure(error)) case let .success(authorizationCode): self.auth.getToken(withCode: authorizationCode) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to start OAuth 2 web session - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): tokenStore.write(tokenInfo: tokenInfo) { result in switch result { case .success: let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: tokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } case let .failure(error): completion(.failure(error)) } } } } } #endif func startOAuth2WebSession(completion: @escaping Callback<BoxClient>, tokenStore: TokenStore) { obtainAuthorizationCodeFromWebSession { result in switch result { case let .failure(error): completion(.failure(error)) case let .success(authorizationCode): self.auth.getToken(withCode: authorizationCode) { [weak self] result in guard let self = self else { completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to start OAuth 2 web session - BoxSDK deallocated")))) return } switch result { case let .success(tokenInfo): tokenStore.write(tokenInfo: tokenInfo) { result in switch result { case .success: let session = OAuth2Session(authModule: self.auth, tokenInfo: tokenInfo, tokenStore: tokenStore, configuration: self.configuration) let client = BoxClient(networkAgent: self.networkAgent, session: session, configuration: self.configuration) completion(.success(client)) case let .failure(error): completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error))) } } case let .failure(error): completion(.failure(error)) } } } } } #if os(iOS) @available(iOS 13.0, *) func obtainAuthorizationCodeFromWebSession(context: ASWebAuthenticationPresentationContextProviding, completion: @escaping Callback<String>) { let authorizeURL = makeAuthorizeURL(state: nonce) webSession = AuthenticationSession(url: authorizeURL, callbackURLScheme: URL(string: configuration.callbackURL)?.scheme, context: context) { resultURL, error in guard error == nil, let successURL = resultURL else { print(error.debugDescription) completion(.failure(BoxAPIAuthError(message: .invalidOAuthRedirectConfiguration, error: error))) return } let usedState = self.getURLComponentValueAt(key: "state", from: authorizeURL) if let authorizationCode = self.getURLComponentValueAt(key: "code", from: successURL), let receivedState = self.getURLComponentValueAt(key: "state", from: successURL), receivedState == usedState { completion(.success(authorizationCode)) return } else { completion(.failure(BoxAPIAuthError(message: .invalidOAuthState))) } } webSession?.start() } #endif func obtainAuthorizationCodeFromWebSession(completion: @escaping Callback<String>) { let authorizeURL = makeAuthorizeURL(state: nonce) #if os(iOS) webSession = AuthenticationSession(url: authorizeURL, callbackURLScheme: URL(string: configuration.callbackURL)?.scheme) { resultURL, error in guard error == nil, let successURL = resultURL else { print(error.debugDescription) completion(.failure(BoxAPIAuthError(message: .invalidOAuthRedirectConfiguration, error: error))) return } let usedState = self.getURLComponentValueAt(key: "state", from: authorizeURL) if let authorizationCode = self.getURLComponentValueAt(key: "code", from: successURL), let receivedState = self.getURLComponentValueAt(key: "state", from: successURL), receivedState == usedState { completion(.success(authorizationCode)) return } else { completion(.failure(BoxAPIAuthError(message: .invalidOAuthState))) } } webSession?.start() #endif } } // MARK: - Configuration /// Extension for configuration-related methods public extension BoxSDK { /// Updates current SDK configuration /// /// - Parameters: /// - apiBaseURL: Base URL for majority of the requests. /// - uploadApiBaseURL: Base URL for upload requests. If not specified, default URL is used. /// - oauth2AuthorizeURL: URL for the OAuth2 authorization page, where users are redirected to enter their credentials /// - maxRetryAttempts: Maximum number of request retries in case of error result. If not specified, default value 5 is used. /// - tokenRefreshThreshold: Specifies how many seconds before token expires it shuld be refreshed. /// If not specified, default value 60 seconds is used. /// - consoleLogDestination: Custom destination of console log. /// - fileLogDestination: Custom destination of file log. /// - clientAnalyticsInfo: Custom analytics info that will be set to request header. func updateConfiguration( apiBaseURL: URL? = nil, uploadApiBaseURL: URL? = nil, oauth2AuthorizeURL: URL? = nil, maxRetryAttempts: Int? = nil, tokenRefreshThreshold: TimeInterval? = nil, consoleLogDestination: ConsoleLogDestination? = nil, fileLogDestination: FileLogDestination? = nil, clientAnalyticsInfo: ClientAnalyticsInfo? = nil ) throws { configuration = try BoxSDKConfiguration( clientId: configuration.clientId, clientSecret: configuration.clientSecret, apiBaseURL: apiBaseURL, uploadApiBaseURL: uploadApiBaseURL, oauth2AuthorizeURL: oauth2AuthorizeURL, maxRetryAttempts: maxRetryAttempts, tokenRefreshThreshold: tokenRefreshThreshold, consoleLogDestination: consoleLogDestination, fileLogDestination: fileLogDestination, clientAnalyticsInfo: clientAnalyticsInfo ) // Refresh config-dependent objects networkAgent = BoxNetworkAgent(configuration: configuration) auth = AuthModule(networkAgent: networkAgent, configuration: configuration) } } // MARK: - AuthenticationSession extension BoxSDK { /// Creates OAuth2 authorization URL you can use in browser to authorize. /// /// - Parameters: /// - state: A text string that you choose. Box sends the same string to your redirect URL when authentication is complete. /// This parameter is provided for your use in protecting against hijacked sessions and other attacks. /// - Returns: Standard URL object to be used for authorization in external browser. public func makeAuthorizeURL(state: String? = nil) -> URL { // swiftlint:disable:next line_length var urlString = "\(configuration.oauth2AuthorizeURL)?\(BoxOAuth2ParamsKey.responseType)=\(BoxOAuth2ParamsKey.responseTypeValue)&\(BoxOAuth2ParamsKey.clientId)=\(configuration.clientId)&\(BoxOAuth2ParamsKey.redirectURL)=\(configuration.callbackURL)" if let state = state { urlString.append("&\(BoxOAuth2ParamsKey.state)=\(state)") } // swiftlint:disable:next force_unwrapping return URL(string: urlString)! } private var nonce: String { let length = 16 let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // swiftlint:disable:next force_unwrapping let randomCharacters = (0 ..< length).map { _ in characters.randomElement()! } return String(randomCharacters) } private func getURLComponentValueAt(key: String, from url: URL?) -> String? { guard let url = url, let urlComponent = NSURLComponents(string: url.absoluteString)?.queryItems?.first(where: { $0.name == key }), let value = urlComponent.value else { return nil } return value } }
apache-2.0
HeartRateLearning/HRLApp
HRLAppTests/TestDoubles/Modules/AddWorkout/Interactor/GetAllWorkoutsInteractorOutputTestDouble.swift
1
810
// // GetAllWorkoutsInteractorOutputTestDouble.swift // HRLApp // // Created by Enrique de la Torre (dev) on 24/01/2017. // Copyright © 2017 Enrique de la Torre. All rights reserved. // import Foundation @testable import HRLApp // MARK: - Main body final class GetAllWorkoutsInteractorOutputTestDouble { // MARK: - Public properties fileprivate (set) var didFindWorkoutsCount = 0 fileprivate (set) var lastFoundWorkouts = [] as [String] } // MARK: - GetConfiguredWorkoutsInteractorOutput methods extension GetAllWorkoutsInteractorOutputTestDouble: GetAllWorkoutsInteractorOutput { func interactor(_ interactor: GetAllWorkoutsInteractorInput, didFindWorkouts workouts: [String]) { didFindWorkoutsCount += 1 lastFoundWorkouts = workouts } }
mit
muhasturk/smart-citizen-ios
Smart Citizen/Core/Services.swift
1
1756
/** * Copyright (c) 2016 Mustafa Hastürk * * 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 struct AppAPI { static let serviceDomain = "http://smart-citizen.mustafahasturk.com" static let loginServiceURL = "/memberLogin" static let signUpServiceURL = "/memberSignUp" static let mapServiceURL = "/getUnorderedReportsByType?reportType=" static let dashboardServiceURL = "/getReportsByType?reportType=" static let reportServiceURL = "/sendReport" static let profileServiceURL = "/getReportsByUserId?userId=" static let getReportById = "/getReportDetailsById?reportId=" static let voteReport = "/voteReport" static let authorizedReaction = "/authorizedReaction" }
mit
masters3d/xswift
exercises/dominoes/Sources/DominoesExample.swift
1
4882
struct Dominoes { let singles: [Bone] let doubles: [Bone] var chained: Bool { if singles.isEmpty && doubles.count == 1 { return true } let (success, result) = chainning(swapDuplicate(singles)) if doubles.isEmpty { return success } else if success == true { return doubles.count == doubles.filter({ each in return result.contains(where: { e in return e.value.head == each.value.head }) }).count } else { return false } } private func swapDuplicate(_ input: [Bone]) -> [Bone] { var unique = [Bone]() for each in input { if unique.contains(each) { unique.insert(Bone(each.value.tail, each.value.head), at: 0) } else { unique.append(each) } } return unique } private func chainning(_ input: [Bone]) -> (Bool, [Bone]) { var matched = input guard !matched.isEmpty else { return (false, []) } let total = matched.count - 1 for index in 0...total { for innerIndex in 0...total { matched[index].connect(matched[innerIndex]) } } return (matched.filter({ $0.connected >= 2 }).count == matched.count) ? (true, matched) : (false, []) } init(_ input: [(Int, Int)]) { var singles = [Bone]() var doubles = [Bone]() for each in input { if each.0 == each.1 { doubles.append(Bone(each.0, each.1)) } else { singles.append(Bone(each.0, each.1)) } } self.singles = singles self.doubles = doubles } } func == (lhs: Bone, rhs: Bone) -> Bool { return lhs.value.head == rhs.value.head && lhs.value.tail == rhs.value.tail } class Bone: CustomStringConvertible, Equatable { let value:(head: Int, tail: Int) var connected: Int = 0 var available: Int? var connectedTo: Bone? var description: String { return "\(value)|\(connected)|\(available) " } @discardableResult func connect(_ input: Bone) -> Bool { guard self !== input else { return false } guard self !== input.connectedTo else { return false } var toReturn = false func oneZero() { if available == input.value.head { self.available = nil input.available = input.value.tail toReturn = true } if available == input.value.tail { self.available = nil input.available = input.value.head toReturn = true } } func zeroOne() { if available == value.head { input.available = nil self.available = value.tail toReturn = true } if available == value.tail { input.available = nil self.available = value.head toReturn = true } } func oneOne() { if available == input.available { self.available = nil input.available = nil toReturn = true } } func zeroZero() { if value.head == input.value.head { available = value.tail input.available = input.value.tail connectedTo = input toReturn = true } if value.tail == input.value.tail { available = value.head input.available = input.value.head connectedTo = input toReturn = true } if value.head == input.value.tail { available = value.tail input.available = input.value.head connectedTo = input toReturn = true } if value.tail == input.value.head { available = value.head input.available = input.value.tail connectedTo = input toReturn = true } } switch (connected, input.connected) { case (1, 0): guard let _ = available else { return false } oneZero() case (0, 1): guard let _ = input.available else { return false } zeroOne() case (1, 1): oneOne() case (0, 0): zeroZero() default: toReturn = false } if toReturn { connected += 1 input.connected += 1 return true } else { return false } } init(_ head: Int, _ tail: Int) { self.value.head = head self.value.tail = tail } }
mit
xeo-it/contacts-sample
totvs-contacts-test/ViewControllers/KeyValueCell.swift
1
457
// // KeyValueCell.swift // totvs-contacts-test // // Created by Francesco Pretelli on 30/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import Foundation import SDWebImage import UIKit class KeyValueCell: UITableViewCell { @IBOutlet weak var keyLbl: UILabel! @IBOutlet weak var valueLbl: UILabel! func updateData(key:String, value:String){ keyLbl.text = key valueLbl.text = value } }
mit
lelandjansen/fatigue
ios/Pods/PhoneNumberKit/PhoneNumberKit/Formatter.swift
4
5499
// // Formatter.swift // PhoneNumberKit // // Created by Roy Marmelstein on 03/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation final class Formatter { weak var regexManager: RegexManager? init(phoneNumberKit: PhoneNumberKit) { self.regexManager = phoneNumberKit.regexManager } init(regexManager: RegexManager) { self.regexManager = regexManager } // MARK: Formatting functions /// Formats phone numbers for display /// /// - Parameters: /// - phoneNumber: Phone number object. /// - formatType: Format type. /// - regionMetadata: Region meta data. /// - Returns: Formatted Modified national number ready for display. func format(phoneNumber: PhoneNumber, formatType: PhoneNumberFormat, regionMetadata: MetadataTerritory?) -> String { var formattedNationalNumber = phoneNumber.adjustedNationalNumber() if let regionMetadata = regionMetadata { formattedNationalNumber = formatNationalNumber(formattedNationalNumber, regionMetadata: regionMetadata, formatType: formatType) if let formattedExtension = formatExtension(phoneNumber.numberExtension, regionMetadata: regionMetadata) { formattedNationalNumber = formattedNationalNumber + formattedExtension } } return formattedNationalNumber } /// Formats extension for display /// /// - Parameters: /// - numberExtension: Number extension string. /// - regionMetadata: Region meta data. /// - Returns: Modified number extension with either a preferred extension prefix or the default one. func formatExtension(_ numberExtension: String?, regionMetadata: MetadataTerritory) -> String? { if let extns = numberExtension { if let preferredExtnPrefix = regionMetadata.preferredExtnPrefix { return "\(preferredExtnPrefix)\(extns)" } else { return "\(PhoneNumberConstants.defaultExtnPrefix)\(extns)" } } return nil } /// Formats national number for display /// /// - Parameters: /// - nationalNumber: National number string. /// - regionMetadata: Region meta data. /// - formatType: Format type. /// - Returns: Modified nationalNumber for display. func formatNationalNumber(_ nationalNumber: String, regionMetadata: MetadataTerritory, formatType: PhoneNumberFormat) -> String { guard let regexManager = regexManager else { return nationalNumber } let formats = regionMetadata.numberFormats var selectedFormat: MetadataPhoneNumberFormat? for format in formats { if let leadingDigitPattern = format.leadingDigitsPatterns?.last { if (regexManager.stringPositionByRegex(leadingDigitPattern, string: String(nationalNumber)) == 0) { if (regexManager.matchesEntirely(format.pattern, string: String(nationalNumber))) { selectedFormat = format break; } } } else { if (regexManager.matchesEntirely(format.pattern, string: String(nationalNumber))) { selectedFormat = format break; } } } if let formatPattern = selectedFormat { guard let numberFormatRule = (formatType == PhoneNumberFormat.international && formatPattern.intlFormat != nil) ? formatPattern.intlFormat : formatPattern.format, let pattern = formatPattern.pattern else { return nationalNumber } var formattedNationalNumber = String() var prefixFormattingRule = String() if let nationalPrefixFormattingRule = formatPattern.nationalPrefixFormattingRule, let nationalPrefix = regionMetadata.nationalPrefix { prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.npPattern, string: nationalPrefixFormattingRule, template: nationalPrefix) prefixFormattingRule = regexManager.replaceStringByRegex(PhoneNumberPatterns.fgPattern, string: prefixFormattingRule, template:"\\$1") } if formatType == PhoneNumberFormat.national && regexManager.hasValue(prefixFormattingRule){ let replacePattern = regexManager.replaceFirstStringByRegex(PhoneNumberPatterns.firstGroupPattern, string: numberFormatRule, templateString: prefixFormattingRule) formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: replacePattern) } else { formattedNationalNumber = regexManager.replaceStringByRegex(pattern, string: nationalNumber, template: numberFormatRule) } return formattedNationalNumber } else { return nationalNumber } } } public extension PhoneNumber { /** Adjust national number for display by adding leading zero if needed. Used for basic formatting functions. - Returns: A string representing the adjusted national number. */ public func adjustedNationalNumber() -> String { if self.leadingZero == true { return "0" + String(nationalNumber) } else { return String(nationalNumber) } } }
apache-2.0
madhusamuel/MovieBrowser
MovieBrowser/Movies/ViewController/MovieTableViewCell.swift
1
594
// // MovieTableViewCell.swift // MovieBrowser // // Created by Madhu Samuel on 24/11/2015. // Copyright © 2015 Madhu. All rights reserved. // import UIKit class MovieTableViewCell: UITableViewCell { @IBOutlet weak var movieImageView: UIImageView! @IBOutlet weak var movieTitle: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
SmallElephant/FESwiftDemo
5-ContextGraphics/5-ContextGraphicsUITests/__ContextGraphicsUITests.swift
1
1272
// // __ContextGraphicsUITests.swift // 5-ContextGraphicsUITests // // Created by keso on 2017/2/12. // Copyright © 2017年 FlyElephant. All rights reserved. // import XCTest class __ContextGraphicsUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
lotpb/iosSQLswift
mySQLswift/TrendingCell.swift
1
780
// // TrendingCell.swift // youtube // // Created by Brian Voong on 7/9/16. // Copyright © 2016 letsbuildthatapp. All rights reserved. // import UIKit import Parse class TrendingCell: FeedCell { override func fetchVideos() { let query = PFQuery(className:"Newsios") //query.cachePolicy = PFCachePolicy.CacheThenNetwork query.orderByDescending("Liked") query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { let temp: NSArray = objects! as NSArray self._feedItems = temp.mutableCopy() as! NSMutableArray self.collectionView.reloadData() } else { print("Error") } } } }
gpl-2.0
RamiAsia/Swift-Sorting
Sorting Algorithms/Radix-Sort/Tests/LinuxMain.swift
1
106
import XCTest @testable import Radix_SortTestSuite XCTMain([ testCase(Radix_SortTests.allTests), ])
mit
vary-llc/SugarRecord
library/Core/Protocols/SugarRecordResultsProtocol.swift
10
1452
// // SugarRecordResultsProtocol.swift // project // // Created by Pedro Piñera Buendía on 29/12/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation internal protocol SugarRecordResultsProtocol { /** Returns the count of elements in Results :param: finder Finder restrict the query results (lasts, first, firsts, ...) which is not possible directly on Realm :returns: Count of elements */ func count(#finder: SugarRecordFinder) -> Int /** Returns the object at a given index :param: index Index of the object :param: finder Finder restrict the query results (lasts, first, firsts, ...) which is not possible directly on Realm :returns: Object at that index (if exists) */ func objectAtIndex(index: UInt, finder: SugarRecordFinder) -> AnyObject! /** Returns the first object of the results :param: finder Finder restrict the query results (lasts, first, firsts, ...) which is not possible directly on Realm :returns: First object (if exists) */ func firstObject(#finder: SugarRecordFinder) -> AnyObject! /** Returns the last object of the results :param: finder Finder restrict the query results (lasts, first, firsts, ...) which is not possible directly on Realm :returns: Last object (if exists) */ func lastObject(#finder: SugarRecordFinder) -> AnyObject! }
mit
joaomarcelo93/ios-ble-explorer
ios-ble-explorer/String+Hexadecimal.swift
1
3559
// // String+DataFromHex.swift // ios-ble-explorer // // Created by João Marcelo on 20/06/15. // Copyright (c) 2015 João Marcelo Oliveira. All rights reserved. // import Foundation extension String { /// Create NSData from hexadecimal string representation /// /// This takes a hexadecimal representation and creates a NSData object. Note, if the string has any spaces, those are removed. Also if the string started with a '<' or ended with a '>', those are removed, too. This does no validation of the string to ensure it's a valid hexadecimal string /// /// The use of `strtoul` inspired by Martin R at http://stackoverflow.com/a/26284562/1271826 /// /// :returns: NSData represented by this hexadecimal string. Returns nil if string contains characters outside the 0-9 and a-f range. func dataFromHexadecimalString() -> NSData? { let trimmedString = self.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<> ")).stringByReplacingOccurrencesOfString(" ", withString: "") // make sure the cleaned up string consists solely of hex digits, and that we have even number of them var error: NSError? let regex = NSRegularExpression(pattern: "^[0-9a-f]*$", options: .CaseInsensitive, error: &error) let found = regex?.firstMatchInString(trimmedString, options: nil, range: NSMakeRange(0, count(trimmedString))) if found == nil || found?.range.location == NSNotFound || count(trimmedString) % 2 != 0 { return nil } // everything ok, so now let's build NSData let data = NSMutableData(capacity: count(trimmedString) / 2) for var index = trimmedString.startIndex; index < trimmedString.endIndex; index = index.successor().successor() { let byteString = trimmedString.substringWithRange(Range<String.Index>(start: index, end: index.successor().successor())) let num = UInt8(byteString.withCString { strtoul($0, nil, 16) }) data?.appendBytes([num] as [UInt8], length: 1) } return data } /// Create NSData from hexadecimal string representation /// /// This takes a hexadecimal representation and creates a String object from taht. Note, if the string has any spaces, those are removed. Also if the string started with a '<' or ended with a '>', those are removed, too. /// /// :param: encoding The NSStringCoding that indicates how the binary data represented by the hex string should be converted to a String. /// /// :returns: String represented by this hexadecimal string. Returns nil if string contains characters outside the 0-9 and a-f range or if a string cannot be created using the provided encoding func stringFromHexadecimalStringUsingEncoding(encoding: NSStringEncoding) -> String? { if let data = dataFromHexadecimalString() { return NSString(data: data, encoding: encoding) as? String } return nil } /// Create hexadecimal string representation of String object. /// /// :param: encoding The NSStringCoding that indicates how the string should be converted to NSData before performing the hexadecimal conversion. /// /// :returns: String representation of this String object. func hexadecimalStringUsingEncoding(encoding: NSStringEncoding) -> String? { let data = dataUsingEncoding(NSUTF8StringEncoding) return data?.hexadecimalString() } }
mit
kirkbyo/Alpha
Alpha/Fortunes.swift
1
2111
// // fortunes.swift // Alpha // // Created by Ozzie Kirkby on 2014-10-19. // Copyright (c) 2014 Ozzie Kirkby. All rights reserved. // import Foundation import UIKit import Social class FortunesController: UIViewController { //============================// //****** Outlet & Actions ****// //============================// let utility = Utility() @IBOutlet weak var fortuneBackground: UIImageView! @IBOutlet weak var displayFortune: UILabel! //============================// //********** General *********// //============================// override func viewDidLoad() { super.viewDidLoad() // Checks if time is greater then 3pm to change background let currentTime = utility.currentTime() if (currentTime >= 15 ) { fortuneBackground.image = UIImage(named: "fortune_background.png") } else { fortuneBackground.image = UIImage(named:"morning_fortunes_background.png") } } //============================// //********** Fortunes ********// //============================// let fortunes = fortunesGroup() var fortune: String = "" override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { fortune = fortunes.randomFortune() displayFortune.text = fortune } //============================// //***** Sharing Features *****// //============================// @IBAction func shareTweet(_ sender: AnyObject) { Share(fortune).shareTwitter(fortune.characters.count, action: { sheet in self.present(sheet, animated: true, completion: nil) }, error: { alert in self.present(alert, animated: true, completion: nil) }) } @IBAction func shareFacebook(_ sender: AnyObject) { Share(fortune).shareFacebook({ sheet in self.present(sheet, animated: true, completion: nil) }, error: { alert in self.present(alert, animated: true, completion: nil) }) } }
mit
overtake/TelegramSwift
submodules/Mozjpeg/Package.swift
1
854
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Mozjpeg", platforms: [ .macOS(.v10_12) ], products: [ .library( name: "Mozjpeg", targets: ["Mozjpeg"]), ], targets: [ .target( name: "Mozjpeg", dependencies: [], path: ".", publicHeadersPath: "Sources", cSettings: [ .headerSearchPath("Sources"), .unsafeFlags([ "-I../../core-xprojects/Mozjpeg/build", "-I../../submodules/telegram-ios/third-party/mozjpeg/mozjpeg" ]) ]), ] )///../../submodules/telegram-ios/third-party/mozjpeg/mozjpeg
gpl-2.0
gouyz/GYZBaking
baking/Classes/Orders/Controller/GYZSelectReceivedGoodsVC.swift
1
6737
// // GYZSelectReceivedGoodsVC.swift // baking // 选择收货商品 // Created by gouyz on 2017/6/8. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD private let receivedGoodsCell = "receivedGoodsCell" class GYZSelectReceivedGoodsVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource { ///订单商品列表 var goodsModels: [OrderGoodsModel] = [OrderGoodsModel]() ///选择的收货商品 var selectGoods: [String : String] = [:] /// 订单id var orderId: String = "" ///商品状态,0未收货 1已收货 -1退货 var type:String = "0" override func viewDidLoad() { super.viewDidLoad() self.title = "选择收货商品" view.addSubview(tableView) view.addSubview(receivedGoodsBtn) tableView.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsMake(0, 0, kBottomTabbarHeight, 0)) } receivedGoodsBtn.snp.makeConstraints { (make) in make.bottom.equalTo(view) make.top.equalTo(tableView.snp.bottom) make.left.right.equalTo(view) } requestGoods() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 懒加载UITableView lazy var tableView : UITableView = { let table = UITableView(frame: CGRect.zero, style: .plain) table.dataSource = self table.delegate = self table.tableFooterView = UIView() table.separatorColor = kGrayLineColor table.register(GYZSelectReceivedGoodsCell.self, forCellReuseIdentifier: receivedGoodsCell) return table }() /// 确定收货按钮 fileprivate lazy var receivedGoodsBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.backgroundColor = kBtnClickBGColor btn.setTitle("确定收货", for: .normal) btn.setTitleColor(kWhiteColor, for: .normal) btn.titleLabel?.font = k15Font btn.addTarget(self, action: #selector(clickReceivedGoodsBtn), for: .touchUpInside) return btn }() /// 获取订单商品信息 func requestGoods(){ weak var weakSelf = self showLoadingView() GYZNetWork.requestNetwork("Order/orderGoods",parameters: ["order_id":orderId,"type":type], success: { (response) in weakSelf?.hiddenLoadingView() GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] guard let info = data["info"].array else { return } for item in info{ guard let itemInfo = item.dictionaryObject else { return } let model = OrderGoodsModel.init(dict: itemInfo) weakSelf?.goodsModels.append(model) } if weakSelf?.goodsModels.count > 0{ weakSelf?.tableView.reloadData() } }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hiddenLoadingView() GYZLog(error) }) } /// 确定收货 func clickReceivedGoodsBtn(){ if selectGoods.count > 0 { weak var weakSelf = self GYZAlertViewTools.alertViewTools.showAlert(title: "提示", message: "确定收货吗?", cancleTitle: "取消", viewController: self, buttonTitles: "确定") { (index) in if index != -1{ //确定收货 weakSelf?.requestUpdateGoodsState() } } }else{ MBProgressHUD.showAutoDismissHUD(message: "请选择收货商品") } } /// 部分确认收货接口 func requestUpdateGoodsState(){ weak var weakSelf = self createHUD(message: "加载中...") var ids: String = "" for item in selectGoods { ids += item.value + ";" } ids = ids.substring(to: ids.index(ids.startIndex, offsetBy: ids.characters.count - 1)) GYZNetWork.requestNetwork("Order/updateOrderGoodsType",parameters: ["order_id":orderId,"type":"1","goods_id":ids], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 _ = weakSelf?.navigationController?.popViewController(animated: true) }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return goodsModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: receivedGoodsCell) as! GYZSelectReceivedGoodsCell let item = goodsModels[indexPath.row] cell.logoImgView.kf.setImage(with: URL.init(string: item.goods_thumb_img!), placeholder: UIImage.init(named: "icon_goods_default"), options: nil, progressBlock: nil, completionHandler: nil) cell.nameLab.text = item.cn_name if selectGoods.keys.contains(item.goods_id!){//是否选择 cell.checkBtn.isSelected = true }else{ cell.checkBtn.isSelected = false } cell.selectionStyle = .none return cell } ///MARK : UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = goodsModels[indexPath.row] if selectGoods.keys.contains(item.goods_id!){//是否选择 selectGoods.removeValue(forKey: item.goods_id!) }else{ selectGoods[item.goods_id!] = item.goods_id! } self.tableView.reloadData() } }
mit
Shivam0911/IOS-Training-Projects
NightUI/LoginViewVC.swift
2
452
// // LoginViewVC.swift // NightUI // // Created by MAC on 02/03/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class LoginViewVC: UIViewController { @IBOutlet weak var loginTable: UITableView! @IBOutlet weak var signUpButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
witekbobrowski/Stanford-CS193p-Winter-2017
Cassini/Cassini/CassiniViewController.swift
1
1529
// // CassiniViewController.swift // Cassini // // Created by Witek on 12/05/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit class CassiniViewController: UIViewController, UISplitViewControllerDelegate { override func awakeFromNib() { super.awakeFromNib() self.splitViewController?.delegate = self } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let url = DemoURL.NASA[segue.identifier ?? ""]{ if let imageVC = (segue.destination.contents as? ImageViewController) { imageVC.imageURL = url imageVC.title = (sender as? UIButton)?.currentTitle } } } func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { if primaryViewController.contents == self { if let ivc = secondaryViewController.contents as? ImageViewController, ivc.imageURL == nil { return true } } return false } } extension UIViewController{ var contents: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController ?? self } else { return self } } }
mit
vinzscam/ReSwift-Rx
Tests/ReSwiftRxTests.swift
1
2197
// // ReSwiftRxTests.swift // ReSwiftRx // // Created by Vincenzo Scamporlino on 2016-11-04. // Copyright © 2016 Vincenzo Scamporlino. All rights reserved. // import UIKit import XCTest import ReSwiftRx import ReSwift import RxSwift //Example taken from: https://github.com/ReSwift/ReSwift#about-reswift struct AppState: StateType{ var counter: Int = 0 } struct CounterActionIncrease: Action {} struct CounterActionDecrease: Action {} struct CounterReducer: Reducer { func handleAction(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() switch action { case _ as CounterActionIncrease: state.counter += 1 case _ as CounterActionDecrease: state.counter -= 1 default: break } return state } } class ReSwiftRxTests: XCTestCase{ var mainStore : Store<AppState>? var disposable : Disposable? override func setUp() { super.setUp() self.mainStore = Store<AppState>( reducer: CounterReducer(), state: nil ) } override func tearDown() { super.tearDown() self.disposable?.dispose() self.disposable = nil self.mainStore = nil } func testAsObservableSubscribe() { let counterLimit = 10; let attempts = 15 let expectationsTimeout = TimeInterval(10) let exp = expectation(description: "Wait until one or more events are received.") self.disposable = mainStore?.asObservable() .filter{ AppState -> Bool in AppState.counter > counterLimit } .take(1) .subscribe(onNext: { state in XCTAssertGreaterThan(state.counter, counterLimit, "counter must be greater than \(counterLimit)") exp.fulfill() }); for _ in 1...attempts { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(arc4random() % 3)) { [weak self] in self?.mainStore?.dispatch(CounterActionIncrease()) } } waitForExpectations(timeout: expectationsTimeout) } }
mit
CGLueng/DYTV
DYZB/DYZB/Classes/Tools/Common.swift
1
352
// // Common.swift // DYZB // // Created by CGLueng on 2016/12/12. // Copyright © 2016年 com.ruixing. All rights reserved. // import UIKit let kStateBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH : CGFloat = 44 let kScreenW : CGFloat = UIScreen.main.bounds.width let kScreenH : CGFloat = UIScreen.main.bounds.height
mit
jvanlint/Secret-Squirrel
Secret Squirrel/Extensions/UIView+SimpleAnimation.swift
1
17029
// // UIView+SimpleAnimation.swift // SimpleAnimation.swift // // Created by Keith Ito on 4/19/16. // import UIKit /** Edge of the view's parent that the animation should involve - none: involves no edge - top: involves the top edge of the parent - bottom: involves the bottom edge of the parent - left: involves the left edge of the parent - right: involves the right edge of the parent */ public enum SimpleAnimationEdge { case none case top case bottom case left case right } /** A UIView extension that makes adding basic animations, like fades and bounces, simple. */ public extension UIView { /** Fades this view in. This method can be chained with other animations to combine a fade with the other animation, for instance: ``` view.fadeIn().slideIn(from: .left) ``` - Parameters: - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeIn(duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { isHidden = false alpha = 0 UIView.animate( withDuration: duration, delay: delay, options: .curveEaseInOut, animations: { self.alpha = 1 }, completion: completion) return self } /** Fades this view out. This method can be chained with other animations to combine a fade with the other animation, for instance: ``` view.fadeOut().slideOut(to: .right) ``` - Parameters: - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeOut(duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { UIView.animate( withDuration: duration, delay: delay, options: .curveEaseOut, animations: { self.alpha = 0 }, completion: completion) return self } /** Fades the background color of a view from existing bg color to a specified color without using alpha values. - Parameters: - toColor: the final color you want to fade to - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func fadeColor(toColor: UIColor = UIColor.red, duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { UIView.animate( withDuration: duration, delay: delay, options: .curveEaseIn, animations: { self.backgroundColor = toColor }, completion: completion) return self } /** Slides this view into position, from an edge of the parent (if "from" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - from: edge of the parent view that should be used as the starting point of the animation - x: horizontal offset that should be used for the starting point of the animation - y: vertical offset that should be used for the starting point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func slideIn(from edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.4, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) transform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) isHidden = false UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 1, initialSpringVelocity: 2, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Slides this view out of its position, toward an edge of the parent (if "to" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - to: edge of the parent view that should be used as the ending point of the animation - x: horizontal offset that should be used for the ending point of the animation - y: vertical offset that should be used for the ending point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func slideOut(to edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.25, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) let endTransform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) UIView.animate( withDuration: duration, delay: delay, options: .curveEaseOut, animations: { self.transform = endTransform }, completion: completion) return self } /** Moves this view into position, with a bounce at the end, either from an edge of the parent (if "from" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - from: edge of the parent view that should be used as the starting point of the animation - x: horizontal offset that should be used for the starting point of the animation - y: vertical offset that should be used for the starting point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func bounceIn(from edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.5, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) transform = CGAffineTransform(translationX: offset.x + x, y: offset.y + y) isHidden = false UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 0.58, initialSpringVelocity: 3, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Moves this view out of its position, starting with a bounce. The view moves toward an edge of the parent (if "to" is set) or a fixed offset away from its position (if "x" and "y" are set). - Parameters: - to: edge of the parent view that should be used as the ending point of the animation - x: horizontal offset that should be used for the ending point of the animation - y: vertical offset that should be used for the ending point of the animation - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func bounceOut(to edge: SimpleAnimationEdge = .none, x: CGFloat = 0, y: CGFloat = 0, duration: TimeInterval = 0.35, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let offset = offsetFor(edge: edge) let delta = CGPoint(x: offset.x + x, y: offset.y + y) let endTransform = CGAffineTransform(translationX: delta.x, y: delta.y) let prepareTransform = CGAffineTransform(translationX: -delta.x * 0.2, y: -delta.y * 0.2) UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.6) { self.transform = endTransform } }, completion: completion) return self } /** Moves this view into position, as though it were popping out of the screen. - Parameters: - fromScale: starting scale for the view, should be between 0 and 1 - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func popIn(fromScale: CGFloat = 0.5, duration: TimeInterval = 0.5, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { isHidden = false alpha = 0 transform = CGAffineTransform(scaleX: fromScale, y: fromScale) UIView.animate( withDuration: duration, delay: delay, usingSpringWithDamping: 0.55, initialSpringVelocity: 3, options: .curveEaseOut, animations: { self.transform = .identity self.alpha = 1 }, completion: completion) return self } /** Moves this view out of position, as though it were withdrawing into the screen. - Parameters: - toScale: ending scale for the view, should be between 0 and 1 - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func popOut(toScale: CGFloat = 0.5, duration: TimeInterval = 0.3, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let endTransform = CGAffineTransform(scaleX: toScale, y: toScale) let prepareTransform = CGAffineTransform(scaleX: 1.1, y: 1.1) UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.3) { self.transform = prepareTransform } UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) { self.transform = endTransform self.alpha = 0 } }, completion: completion) return self } /** Causes the view to hop, either toward a particular edge or out of the screen (if "toward" is .None). - Parameters: - toward: the edge to hop toward, or .None to hop out - amount: distance to hop, expressed as a fraction of the view's size - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func hop(toward edge: SimpleAnimationEdge = .none, amount: CGFloat = 0.4, duration: TimeInterval = 0.6, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { var dx: CGFloat = 0, dy: CGFloat = 0, ds: CGFloat = 0 if edge == .none { ds = amount / 2 } else if edge == .left || edge == .right { dx = (edge == .left ? -1 : 1) * self.bounds.size.width * amount; dy = 0 } else { dx = 0 dy = (edge == .top ? -1 : 1) * self.bounds.size.height * amount; } UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeLinear, animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.28) { let t = CGAffineTransform(translationX: dx, y: dy) self.transform = t.scaledBy(x: 1 + ds, y: 1 + ds) } UIView.addKeyframe(withRelativeStartTime: 0.28, relativeDuration: 0.28) { self.transform = .identity } UIView.addKeyframe(withRelativeStartTime: 0.56, relativeDuration: 0.28) { let t = CGAffineTransform(translationX: dx * 0.5, y: dy * 0.5) self.transform = t.scaledBy(x: 1 + ds * 0.5, y: 1 + ds * 0.5) } UIView.addKeyframe(withRelativeStartTime: 0.84, relativeDuration: 0.16) { self.transform = .identity } }, completion: completion) return self } /** Causes the view to shake, either toward a particular edge or in all directions (if "toward" is .None). - Parameters: - toward: the edge to shake toward, or .None to shake in all directions - amount: distance to shake, expressed as a fraction of the view's size - duration: duration of the animation, in seconds - delay: delay before the animation starts, in seconds - completion: block executed when the animation ends */ @discardableResult func shake(toward edge: SimpleAnimationEdge = .none, amount: CGFloat = 0.15, duration: TimeInterval = 0.6, delay: TimeInterval = 0, completion: ((Bool) -> Void)? = nil) -> UIView { let steps = 8 let timeStep = 1.0 / Double(steps) var dx: CGFloat, dy: CGFloat if edge == .left || edge == .right { dx = (edge == .left ? -1 : 1) * self.bounds.size.width * amount; dy = 0 } else { dx = 0 dy = (edge == .top ? -1 : 1) * self.bounds.size.height * amount; } UIView.animateKeyframes( withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { var start = 0.0 for i in 0..<(steps - 1) { UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: timeStep) { self.transform = CGAffineTransform(translationX: dx, y: dy) } if (edge == .none && i % 2 == 0) { swap(&dx, &dy) // Change direction dy *= -1 } dx *= -0.85 dy *= -0.85 start += timeStep } UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: timeStep) { self.transform = .identity } }, completion: completion) return self } private func offsetFor(edge: SimpleAnimationEdge) -> CGPoint { if let parentSize = self.superview?.frame.size { switch edge { case .none: return CGPoint.zero case .top: return CGPoint(x: 0, y: -frame.maxY) case .bottom: return CGPoint(x: 0, y: parentSize.height - frame.minY) case .left: return CGPoint(x: -frame.maxX, y: 0) case .right: return CGPoint(x: parentSize.width - frame.minX, y: 0) } } return .zero } }
mit
nalexn/ViewInspector
Tests/ViewInspectorTests/SwiftUI/ColorTests.swift
1
2576
import XCTest import SwiftUI @testable import ViewInspector @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) final class ColorTests: XCTestCase { func testInspect() throws { XCTAssertNoThrow(try Color.red.inspect()) } func testExtractionFromSingleViewContainer() throws { let view = AnyView(Color(red: 1, green: 0.5, blue: 0)) XCTAssertNoThrow(try view.inspect().anyView().color()) } func testExtractionFromMultipleViewContainer() throws { let view = HStack { Text("") Color.blue Text("") Color(hue: 1, saturation: 0.5, brightness: 0.25) } XCTAssertNoThrow(try view.inspect().hStack().color(1)) XCTAssertNoThrow(try view.inspect().hStack().color(3)) } func testSearch() throws { let view = Group { Color.red } XCTAssertEqual(try view.inspect().find(ViewType.Color.self).pathToRoot, "group().color(0)") } func testValue() throws { let color = Color(red: 0.5, green: 0.25, blue: 1) let sut = try color.inspect().color().value() XCTAssertEqual(sut, color) } func testRGBA() throws { let tupleToArray: ((Float, Float, Float, Float)) -> [Float] = { [$0.0, $0.1, $0.2, $0.3] } let color1 = Color(.sRGBLinear, red: 0.1, green: 0.2, blue: 0.3, opacity: 0.9) let rgba1 = try color1.inspect().color().rgba() XCTAssertEqual(tupleToArray(rgba1), [0.1, 0.2, 0.3, 0.9]) let color2 = Color(red: 0.1, green: 0.2, blue: 0.3, opacity: 0.9) let rgba2 = try color2.inspect().color().rgba() // .sRGB color space converts the original values. // They are NOT 0.1, 0.2 and 0.3 XCTAssertNotEqual(tupleToArray(rgba2), [0.1, 0.2, 0.3, 0.9]) let color3 = Color(.displayP3, red: 0.1, green: 0.2, blue: 0.3, opacity: 0.9) let rgba3 = try color3.inspect().color().rgba() XCTAssertEqual(tupleToArray(rgba3), [0.1, 0.2, 0.3, 0.9]) } func testRGBAError() throws { XCTAssertThrows(try Color.accentColor.inspect().color().rgba(), "RGBA values are not available") } func testName() throws { let color = Color("abc") XCTAssertEqual(try color.inspect().color().name(), "abc") } func testNameError() throws { XCTAssertThrows(try Color.accentColor.inspect().color().name(), "Color name is not available") } }
mit
between40and2/XALG
frameworks/Framework-XALG/Tree/Rep/XALG_Rep_Tree_BinarySearchTree.swift
1
6788
// // XALG_Rep_Tree_BinarySearchTree.swift // XALG // // Created by Juguang Xiao on 06/03/2017. // import Swift class XALG_Rep_Tree_BinarySearchTree<Payload, Key>: XALG_ADT_Tree_BinarySearchTree where Key : Comparable { typealias NodeType = XALG_Rep_TreeNode_BinaryTree_Key<Payload, Key> // typealias NodeType = XALG_DS_TreeNode_BinaryTree_Key<Payload, Key, NodeType> typealias PayloadType = Payload typealias KeyType = Key var rootNode : NodeType? func insert(payload: Payload, key: Key) -> NodeType { if let r = rootNode { return _insert(payload: payload, key: key, node: r) }else { let node = NodeType(key: key) node.payload = payload rootNode = node return node } } // for BST, it does nothing. for AVL, it does important thing to maintain AVL property. func balance(_ n : NodeType) { } private func _insert(payload: PayloadType?, key: KeyType, node : NodeType) -> NodeType { if key < node.key { if let child = node.leftChild { return _insert(payload: payload, key: key, node: child) }else { let child = NodeType(key: key) child.payload = payload child.parent = node node.leftChild = child balance(child) return child } }else { if let child = node.rightChild { return _insert(payload: payload, key: key, node: child) }else { let child = NodeType(key: key) child.payload = payload child.parent = node node.rightChild = child balance(child) return child } } } func search(key: KeyType, usesRecursion : Bool) -> NodeType? { return usesRecursion ? _search_recursive(key: key) : _search_iterative(key: key) } private func _search_iterative(key : KeyType) -> NodeType? { var node = rootNode while let n = node { if key < n.key { node = n.leftChild }else if key > n.key { node = n.rightChild }else { return node } } return nil } private func _search_recursive(key : KeyType) -> NodeType? { guard let r = rootNode else { return nil } return _search_recursive_core(key: key, node: r) } private func _search_recursive_core(key : KeyType, node : NodeType?) -> NodeType? { guard let n = node else { return nil } if key == n.key { return n } if key < n.key { return _search_recursive_core(key: key, node: n.leftChild) } return _search_recursive_core(key: key, node: n.rightChild) } } class XALG_Rep_Tree_AVLTree<Payload, Key> : XALG_Rep_Tree_BinarySearchTree<Payload, Key> where Key : Comparable //Self.NodeType == Self.NodeType.NodeType { typealias NodeType = XALG_Rep_TreeNode_BinaryTree_Key<Payload, Key> private func updateHeightUpwards(_ n : NodeType?) { guard let n = n else { return } let height_left = n.leftChild?.height ?? 0 let height_right = n.rightChild?.height ?? 0 n.height = max(height_left, height_right) + 1 if let parent = n.parent as? NodeType { updateHeightUpwards(parent) } } override func balance(_ node: NodeType?) { guard let n = node else { return } updateHeightUpwards(n.leftChild) updateHeightUpwards(n.rightChild) var t0 : NodeType? = nil var t1_ : [NodeType?] = Array<NodeType?>.init(repeating: nil, count: 2) // was named node_ var t2_ = Array<NodeType?>.init(repeating: nil, count: 4) // was named subtree_ let parent = n.parent as? NodeType switch n.balanceFactor { case let bf where bf > 1 : if n.leftChild!.balanceFactor > 0 { // left-left let A = n let B = A.leftChild // let BL = B?.leftChild t0 = B?.leftChild t1_ = [A, n.leftChild?.leftChild] // , n.leftChild] // A, BL, B t2_ = [t1_[1]?.leftChild, t1_[1]?.rightChild, B?.rightChild, A.rightChild] }else { // left-right let A = n let B = n.leftChild let C = B?.rightChild t0 = B?.rightChild t1_ = [n, n.leftChild] // n.leftChild?.rightChild] // A, B, BR(C) t2_ = [B?.leftChild, C?.leftChild, C?.rightChild, A.rightChild] } case let bf where bf < -1 : if n.rightChild!.balanceFactor < 0 { // right-right let A = n let B = A.rightChild let BR = A.rightChild t0 = B t1_ = [BR, A, B] t2_ = [A.leftChild, B?.leftChild, B?.rightChild?.leftChild, B?.rightChild?.rightChild] }else { // right-left let A = n let B = A.rightChild let C = B?.leftChild t0 = C t1_ = [B , A] t2_ = [A.leftChild, C?.leftChild, C?.rightChild, B?.rightChild] } default: balance(parent) return } /////// Round 2: re-weaving the relationships among above defined nodes. // 2.1 between new t0 and its parent if n.isRoot { self.rootNode = t0 self.rootNode?.parent = nil }else if n.isLeftChild { parent?.lchild = t0 t0?.parentNode = parent }else if n.isRightChild { parent?.rightChild = t0 t0?.parentNode = parent } /// 2.2 between t0 and t1_ t0?.leftChild = t1_[1] t1_[1]?.parentNode = t0 t0?.rightChild = t1_[0] t1_[0]?.parentNode = t0 /// 2.3 between t1_ and t2_ t1_[1]?.leftChild = t2_[0] t2_[0]?.parentNode = t1_[1] t1_[1]?.rightChild = t2_[1] t2_[1]?.parentNode = t1_[1] t1_[0]?.leftChild = t2_[2] t2_[2]?.parentNode = t1_[0] t1_[0]?.rightChild = t2_[3] t2_[3]?.parentNode = t1_[0] /// Round 3 t1_.forEach{ updateHeightUpwards($0) } balance(t0?.parentNode) } }
mit
between40and2/XALG
frameworks/Framework-XALG/Graph/Algo/SSSP/XALG_Algo_Graph_SSSP.swift
1
2219
// // XALG_Algo_Graph_SSSP.swift // XALG // // Created by Juguang Xiao on 25/04/2017. // import Swift class XALG_Algo_Graph_SSSP<G : XALG_ADT_Graph_Weighted> : XALG_Algo_Graph_base<G> //where G.VertexType : Hashable { typealias DistanceType = G.WeightType var sourceVertex : VertexType? // expected outputs var predecessor_ = [VertexType: VertexType?]() var distance_ = [VertexType: DistanceType]() // also called INITIALIZE-SINGLE-SOURCE(G, s) // was called setup() func initializeSingleSource() { let vs = sourceVertex! let g_w = graph! for v in graph!.vertex_ { distance_[v] = G.WeightType.max predecessor_[v] = nil } for e in graph!.outEdges(forVertex: vs) { let e_w = e as! G.EdgeType_Weighted let to = e_w.vertex_[1] as! G.VertexType distance_[to] = g_w.weight(onEdge: e_w) predecessor_[to] = vs } // distance_[source!] = 0 predecessor_[vs] = vs let zero : G.WeightType = G.WeightType.zero distance_[vs] = zero } func relax(from : VertexType, to : VertexType, w : DistanceType) { if distance_[to]! > distance_[from]! + w { distance_[to]! = distance_[from]! + w predecessor_[to] = from } } } extension XALG_Algo_Graph_SSSP { func distance(to : VertexType) -> DistanceType? { let d = distance_[to] guard d != DistanceType.max else { return nil } return d } func path(to : VertexType) -> [VertexType]? { guard distance_[to] != DistanceType.max else { return nil } guard let p = recursePath(to: to, path: [to]) else { return nil } return p } private func recursePath(to : VertexType, path: [VertexType]) -> [VertexType]? { guard let pred = predecessor_[to] else { return nil } if pred == to { return [to] } guard let p = recursePath(to: pred!, path: path) else { return nil } return p + [to] } }
mit
dezinezync/YapDatabase
YapDatabase/Extensions/CloudCore/Swift/YapDatabaseCloudCore.swift
2
76
/// Add Swift extensions here extension YapDatabaseCloudCoreTransaction { }
bsd-3-clause
AutomationStation/BouncerBuddy
BouncerBuddy(version1.0)/BouncerBuddy/ViewController.swift
1
734
// // ViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { // comment out the next lines if you want to go to homepage without sign in //self.performSegueWithIdentifier("SignInView", sender: self) } }
apache-2.0
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/General/ReactiveCocoa/RACSignal+Extensions.swift
2
1416
// // RACSignal+Extensions.swift // ReactiveSwiftFlickrSearch // // Created by Colin Eberhardt on 15/07/2014. // Copyright (c) 2014 Colin Eberhardt. All rights reserved. // import Foundation import ReactiveCocoa // a collection of extension methods that allows for strongly typed closures extension RACSignal { func subscribeNextAs<T>(nextClosure:(T) -> ()) -> () { self.subscribeNext { (next: AnyObject!) -> () in let nextAsT = next! as! T nextClosure(nextAsT) } } func mapAs<T: AnyObject, U: AnyObject>(mapClosure:(T) -> U) -> RACSignal { return self.map { (next: AnyObject!) -> AnyObject! in let nextAsT = next as! T return mapClosure(nextAsT) } } func filterAs<T: AnyObject>(filterClosure:(T) -> Bool) -> RACSignal { return self.filter { (next: AnyObject!) -> Bool in let nextAsT = next as! T return filterClosure(nextAsT) } } func doNextAs<T: AnyObject>(nextClosure:(T) -> ()) -> RACSignal { return self.doNext { (next: AnyObject!) -> () in let nextAsT = next as! T nextClosure(nextAsT) } } } class RACSignalEx { class func combineLatestAs<T, U, R: AnyObject>(signals:[RACSignal], reduce:(T,U) -> R) -> RACSignal { return RACSignal.combineLatest(signals).mapAs { (tuple: RACTuple) -> R in return reduce(tuple.first as! T, tuple.second as! U) } } }
apache-2.0
xedin/swift
stdlib/public/Darwin/Accelerate/vDSP_DecibelConversion.swift
2
9043
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension vDSP { /// Converts power to decibels, single-precision. /// /// - Parameter power: Source vector. /// - Parameter zeroReference: Zero reference. /// - Returns: `power` converted to decibels. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func powerToDecibels<U>(_ power: U, zeroReference: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: power.count) { buffer, initializedCount in convert(power: power, toDecibels: &buffer, zeroReference: zeroReference) initializedCount = power.count } return result } /// Converts power to decibels, single-precision. /// /// - Parameter power: Source vector. /// - Parameter decibels: Destination vector. /// - Parameter zeroReference: Zero reference. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func convert<U, V>(power: U, toDecibels decibels: inout V, zeroReference: Float) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = decibels.count precondition(power.count == n) decibels.withUnsafeMutableBufferPointer { db in power.withUnsafeBufferPointer { pwr in withUnsafePointer(to: zeroReference) { zref in vDSP_vdbcon(pwr.baseAddress!, 1, zref, db.baseAddress!, 1, vDSP_Length(n), 0) } } } } /// Converts power to decibels, double-precision. /// /// - Parameter power: Source vector. /// - Parameter zeroReference: Zero reference. /// - Returns: `power` converted to decibels. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func powerToDecibels<U>(_ power: U, zeroReference: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: power.count) { buffer, initializedCount in convert(power: power, toDecibels: &buffer, zeroReference: zeroReference) initializedCount = power.count } return result } /// Converts power to decibels, double-precision. /// /// - Parameter power: Source vector. /// - Parameter decibels: Destination vector. /// - Parameter zeroReference: Zero reference. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func convert<U, V>(power: U, toDecibels decibels: inout V, zeroReference: Double) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = decibels.count precondition(power.count == n) decibels.withUnsafeMutableBufferPointer { db in power.withUnsafeBufferPointer { pwr in withUnsafePointer(to: zeroReference) { zref in vDSP_vdbconD(pwr.baseAddress!, 1, zref, db.baseAddress!, 1, vDSP_Length(n), 0) } } } } /// Converts amplitude to decibels, single-precision. /// /// - Parameter amplitude: Source vector. /// - Parameter zeroReference: Zero reference. /// - Returns: `amplitude` converted to decibels. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func amplitudeToDecibels<U>(_ amplitude: U, zeroReference: Float) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: amplitude.count) { buffer, initializedCount in convert(amplitude: amplitude, toDecibels: &buffer, zeroReference: zeroReference) initializedCount = amplitude.count } return result } /// Converts amplitude to decibels, single-precision. /// /// - Parameter amplitude: Source vector. /// - Parameter decibels: Destination vector. /// - Parameter zeroReference: Zero reference. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func convert<U, V>(amplitude: U, toDecibels decibels: inout V, zeroReference: Float) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = decibels.count precondition(amplitude.count == n) decibels.withUnsafeMutableBufferPointer { db in amplitude.withUnsafeBufferPointer { amp in withUnsafePointer(to: zeroReference) { zref in vDSP_vdbcon(amp.baseAddress!, 1, zref, db.baseAddress!, 1, vDSP_Length(n), 1) } } } } /// Converts amplitude to decibels, double-precision. /// /// - Parameter amplitude: Source vector. /// - Parameter zeroReference: Zero reference. /// - Returns: `amplitude` converted to decibels. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func amplitudeToDecibels<U>(_ amplitude: U, zeroReference: Double) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: amplitude.count) { buffer, initializedCount in convert(amplitude: amplitude, toDecibels: &buffer, zeroReference: zeroReference) initializedCount = amplitude.count } return result } /// Converts amplitude to decibels, double-precision. /// /// - Parameter amplitude: Source vector. /// - Parameter decibels: Destination vector. /// - Parameter zeroReference: Zero reference. @inlinable @available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) public static func convert<U, V>(amplitude: U, toDecibels decibels: inout V, zeroReference: Double) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = decibels.count precondition(amplitude.count == n) decibels.withUnsafeMutableBufferPointer { db in amplitude.withUnsafeBufferPointer { amp in withUnsafePointer(to: zeroReference) { zref in vDSP_vdbconD(amp.baseAddress!, 1, zref, db.baseAddress!, 1, vDSP_Length(n), 1) } } } } }
apache-2.0
banjun/JetToTheFuture
JetToTheFuture/Classes/JetToTheFuture.swift
1
820
import Foundation import BrightFutures private let forcedFutureQueue = DispatchQueue(label: "forcedFutureQueue") /// synchronously turn Future into Result on the main queue public func forcedFuture<T, E>(createFuture: @escaping () -> Future<T, E>) -> Result<T, E> { // avoid deadlock by waiting using forced() on main queue for a Future created on main queue (as of BrightFutures 5.1.0) // also avoid the optimization that introduces main thread block execution by just calling the block in DispatchQueue.global().sync on main thread // for example, (f1 ?? f2).forced() on main thread causes deadlock var future: Future<T, E>? let sem = DispatchSemaphore(value: 0) forcedFutureQueue.async { future = createFuture() sem.signal() } sem.wait() return future!.forced() }
mit
antlr/grammars-v4
swift/swift5/examples/Regex.swift
1
5477
import Foundation /** Create a regular expression from a pattern string and options. ``` import Regex let regex = Regex(#"^[a-z]+$"#, options: .caseInsensitive) regex.isMatched(by: "Unicorn") //=> true ``` */ public struct Regex: Hashable { let nsRegex: NSRegularExpression // MARK: Initializers /** Create a `Regex` from a static pattern string and options. Tip: Wrap the pattern string in `#` to reduce the need for escaping. For example: `#"\d+"#`. [Supported regex syntax.](https://developer.apple.com/documentation/foundation/nsregularexpression#1661061) */ public init( _ pattern: StaticString, options: Options = [], file: StaticString = #fileID, line: Int = #line ) { do { try self.init(pattern.string, options: options) } catch { fatalError("Invalid regular expression: \(error.localizedDescription)", file: file, line: UInt(line)) } } /** Create a `Regex` from a pattern string and options. Tip: Wrap the pattern string in `#` to reduce the need for escaping. For example: `#"\d+"#`. [Supported regex syntax.](https://developer.apple.com/documentation/foundation/nsregularexpression#1661061) */ @_disfavoredOverload public init( _ pattern: String, options: Options = [] ) throws { self.init( try NSRegularExpression(pattern: pattern, options: options) ) } /** Create a `Regex` from a `NSRegularExpression`. */ @_disfavoredOverload public init(_ regularExpression: NSRegularExpression) { self.nsRegex = regularExpression } } // MARK: Methods extension Regex { /** Returns whether there is a match in the given string. ``` import Regex Regex(#"^\d+$"#).isMatched(by: "123") //=> true ``` */ public func isMatched(by string: String) -> Bool { firstMatch(in: string) != nil } /** Returns the first match in the given string. ``` import Regex Regex(#"\d+"#).firstMatch(in: "123-456")?.value //=> "123" ``` */ public func firstMatch(in string: String) -> Match? { nsRegex.firstMatch(in: string).map { Match(checkingResult: $0, string: string) } } /** Returns all the matches in the given string. ``` import Regex Regex(#"\d+"#).allMatches(in: "123-456").map(\.value) //=> ["123", "456"] ``` */ public func allMatches(in string: String) -> [Match] { nsRegex.matches(in: string).map { Match(checkingResult: $0, string: string) } } } // TODO: This needs to include the options too. //extension Regex: CustomStringConvertible { // public var description: String { regex.pattern } //} extension Regex { // MARK: Properties /** The regular expression pattern. */ public var pattern: String { nsRegex.pattern } /** The regular expression options. */ public var options: Options { nsRegex.options } } // MARK: Types extension Regex { public typealias Options = NSRegularExpression.Options public typealias MatchingOptions = NSRegularExpression.MatchingOptions /** A regex match. */ public struct Match: Hashable { /** A regex match capture group. */ public struct Group: Hashable { /** The capture group string. */ public let value: String /** The range of the capture group string in the original string. */ public let range: Range<String.Index> fileprivate init(originalString: String, range: NSRange) { self.range = Range(range, in: originalString)! self.value = String(originalString[self.range]) } } fileprivate let originalString: String let checkingResult: NSTextCheckingResult /** The matched string. */ public let value: String /** The range of the matched string in the original string. */ public let range: Range<String.Index> /** All the match groups. */ public let groups: [Group] /** Get a match group by its name. ``` import Regex Regex(#"(?<number>\d+)"#).firstMatch(in: "1a-2b")?.group(named: "number")?.value //=> "1" ``` */ public func group(named name: String) -> Group? { let range = checkingResult.range(withName: name) guard range.length > 0 else { return nil } return Group(originalString: originalString, range: range) } fileprivate init(checkingResult: NSTextCheckingResult, string: String) { self.checkingResult = checkingResult self.originalString = string self.value = string[nsRange: checkingResult.range]!.string self.range = Range(checkingResult.range, in: string)! // The first range is the full range, so we ignore that. self.groups = (1..<checkingResult.numberOfRanges).map { let range = checkingResult.range(at: $0) return Group(originalString: string, range: range) } } } } // MARK: Operators extension Regex { /** Enables using a regex for pattern matching. ``` import Regex switch "foo123" { case Regex(#"^foo\d+$"#): print("Match!") default: break } ``` */ public static func ~= (string: String, regex: Self) -> Bool { regex.isMatched(by: string) } /** Enables using a regex for pattern matching. ``` import Regex switch Regex(#"^foo\d+$"#) { case "foo123": print("Match!") default: break } ``` */ public static func ~= (regex: Self, string: String) -> Bool { regex.isMatched(by: string) } } // MARK: Helpers extension Regex { /** Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters. */ public static func escapingPattern(for string: String) -> String { NSRegularExpression.escapedPattern(for: string) } }
mit
iOSDevLog/iOSDevLog
201. UI Test/Swift/ListerKit Tests/ListPresenterTestHelper.swift
1
4033
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A class that makes it easier to test `ListPresenterType` implementations. */ import ListerKit import XCTest class ListPresenterTestHelper: ListPresenterDelegate { // MARK: Properties var remainingExpectedWillChanges: Int? = nil var willChangeCallbackCount = 0 /// An array of tuples representing the inserted list items. var didInsertListItemCallbacks = [(listItem: ListItem, index: Int)]() /// An array of tuples representing the removed list items. var didRemoveListItemCallbacks = [(listItem: ListItem, index: Int)]() /// An array of tuples representing the updated list items. var didUpdateListItemCallbacks = [(listItem: ListItem, index: Int)]() /// An array of tuples representing the moved list items. var didMoveListItemCallbacks = [(listItem: ListItem, fromIndex: Int, toIndex: Int)]() /// An array of tuples representing the updates to the list presenter's color. var didUpdateListColorCallbacks: [List.Color] = [] var remainingExpectedDidChanges: Int? = nil var didChangeCallbackCount = 0 // Expectation specific variables. var assertions: (Void -> Void)! = nil var isTesting = false // MARK: ListPresenterDelegate func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) { /* Lister's tests currently do not support testing and `listPresenterDidRefreshCompleteLayout(_:)` calls. */ } func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { if !isTesting { return } remainingExpectedWillChanges?-- willChangeCallbackCount++ } func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) { if !isTesting { return } didInsertListItemCallbacks += [(listItem: listItem, index: index)] } func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) { if !isTesting { return } didRemoveListItemCallbacks += [(listItem: listItem, index: index)] } func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) { if !isTesting { return } didUpdateListItemCallbacks += [(listItem: listItem, index: index)] } func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) { if !isTesting { return } didMoveListItemCallbacks += [(listItem: listItem, fromIndex: fromIndex, toIndex: toIndex)] } func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) { if !isTesting { return } didUpdateListColorCallbacks += [color] } func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { if !isTesting { return } remainingExpectedDidChanges?-- didChangeCallbackCount++ if remainingExpectedDidChanges == 0 { assertions() isTesting = false } } /// A helper method run `assertions` once a batch of changes has occured to the list presenter. func expectOnNextChange(expectations: Void -> Void) { isTesting = true self.assertions = expectations willChangeCallbackCount = 0 remainingExpectedWillChanges = nil didInsertListItemCallbacks = [] didRemoveListItemCallbacks = [] didUpdateListItemCallbacks = [] didMoveListItemCallbacks = [] didUpdateListColorCallbacks = [] didChangeCallbackCount = 0 remainingExpectedDidChanges = nil remainingExpectedWillChanges = 1 remainingExpectedDidChanges = 1 } }
mit
xbainbain/xSpider
Tests/LinuxMain.swift
1
95
import XCTest @testable import xSpiderTests XCTMain([ testCase(xSpiderTests.allTests), ])
mit
DannyVancura/SwifTrix
SwifTrix/SwifTrixTests/SwifTrixDatabaseTests.swift
1
9294
// // SwifTrixDatabaseTests.swift // SwifTrix // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // 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 XCTest import CoreData @testable import SwifTrix class SwifTrixDatabaseTests: XCTestCase { override func setUp() { super.setUp() STDatabase.createSharedDatabase("TestDataModel", inBundle: NSBundle(forClass: SwifTrixTests.self)) } override func tearDown() { super.tearDown() do { let userDirectory = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) let databaseURL = userDirectory.URLByAppendingPathComponent("Main.sqlite") try NSFileManager.defaultManager().removeItemAtURL(databaseURL) // Delete the sqlite's Shared Memory file and Write-Ahead Log file as well guard let databasePath = databaseURL.path else { return } for additionalFile in [ NSURL(fileURLWithPath: databasePath.stringByAppendingString("-shm")), NSURL(fileURLWithPath: databasePath.stringByAppendingString("-wal"))] { print(additionalFile) try NSFileManager.defaultManager().removeItemAtURL(additionalFile) } } catch let error as NSError { print(error.localizedDescription) } } /** Tests the context consistency, i.e. modifying an object on both contexts and assuring that after a save operation, both changes have successfully been applied. */ func testDatabaseContextConsistency() { // Create book on the main context if let book: Book = STDatabase.SharedDatabase!.createObjectNamed("Book") { book.pages = Set<Page>() // Create a page on the async, an another page on the main thread if let page1: Page = NSEntityDescription.insertNewObjectForEntityForName("Page", inManagedObjectContext: STDatabase.SharedDatabase!.asyncContext) as? Page, page2: Page = NSEntityDescription.insertNewObjectForEntityForName("Page", inManagedObjectContext: STDatabase.SharedDatabase!.mainContext) as? Page { // Add both pages to the book (once to the book reference on the main queue, once on the async queue) STDatabase.SharedDatabase!.asyncContext.performBlockAndWait({ page1.book = STDatabase.SharedDatabase!.asyncContext.objectWithID(book.objectID) as? Book }) page2.book = book STDatabase.SharedDatabase!.save() guard let allBooks: [Book] = STDatabase.SharedDatabase?.fetchObjectsWithType("Book") where allBooks.count == 1 else { XCTFail("Expected one book to be saved") return } XCTAssertEqual(allBooks[0].pages?.count, 2, "Expected the book to have 2 pages by now") } else { XCTFail("Unexpectedly got nil while creating pages") } } else { XCTFail("Unexpectedly got nil while creating a book") } } private var completionCounter = 0 private var expectation: XCTestExpectation? /** A function that is called twice by `testAsynchronousChanges` - once from the main queue, once from a separate queue. It checks, whether it has been called twice (so both queues finished adding books to the database) and then runs the tests, assuming that all books have been added. */ private func asyncChangesCompletionBlock(expectedNumberOfBooks: Int) { completionCounter += 1 if completionCounter == 2 { guard let books: [Book] = STDatabase.SharedDatabase!.fetchObjectsWithType("Book") else { XCTFail("Database contains no books") return } XCTAssertEqual(books.count, expectedNumberOfBooks) for book: Book in books { guard let title = book.title, pages = book.pages else { XCTAssertNotNil(book.title, "Book contains no title") XCTAssertNotNil(book.pages, "Book contains no pages") continue } if title.containsString("async") { let expectedNumberOfPages = NSString(string: NSString(string: title).substringFromIndex(5)).integerValue XCTAssertEqual(expectedNumberOfPages, pages.count) } else if title.containsString("sync") { let expectedNumberOfPages = NSString(string: NSString(string: title).substringFromIndex(4)).integerValue XCTAssertEqual(expectedNumberOfPages, pages.count) } } // Fulfill the expectation that both queues did finish self.expectation?.fulfill() } } /** Tests the case where objects are added to the main context and the asynchronous background context simultaneously and checks if the inserted objects are saved correctly. */ func testAsynchronousChanges() { // Number of asynchronously added books let nAsyncBooks = 100 // Number of synchronously added books let nSyncBooks = 100 self.expectation = self.expectationWithDescription("Expect both queues to finish adding books") // Asynchronous changes NSOperationQueue().addOperationWithBlock({ for i in 0..<nAsyncBooks { STDatabase.SharedDatabase!.asyncContext.performBlock({ // Create a book asynchronously guard let book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: STDatabase.SharedDatabase!.asyncContext) as? Book else { XCTFail("Failure while creating a book asynchronously") return } book.title = "async\(i)" // Add i pages, so that the name of the book tells the number of pages it contains for _ in 0..<i { guard let page = NSEntityDescription.insertNewObjectForEntityForName("Page", inManagedObjectContext: STDatabase.SharedDatabase!.asyncContext) as? Page else { XCTFail("Failure while creating a page asynchronously") return } page.book = book } }) } do { try STDatabase.SharedDatabase!.asyncContext.save() self.asyncChangesCompletionBlock(nAsyncBooks + nSyncBooks) } catch { XCTFail("Unexpected error while saving asynchronous context.") } }) // Synchronous changes NSOperationQueue.mainQueue().addOperationWithBlock({ for i in 0..<nSyncBooks { guard let book: Book = STDatabase.SharedDatabase?.createObjectNamed("Book") else { XCTFail("Failure while creating a book synchronously") return } book.title = "sync\(i)" // Add i pages, so that the name of the book tells the number of pages it contains for _ in 0..<i { guard let page: Page = STDatabase.SharedDatabase!.createObjectNamed("Page") else { XCTFail("Failure while creating a page synchronously") return } page.book = book } } STDatabase.SharedDatabase!.save() self.asyncChangesCompletionBlock(nAsyncBooks + nSyncBooks) }) self.waitForExpectationsWithTimeout(30, handler: {print($0)}) } }
mit
steveholt55/metro
iOS/MetroTransitTests/Controller/UserAnnotationTests.swift
1
160
// // Copyright © 2015 Brandon Jenniges. All rights reserved. // import XCTest @testable import MetroTransit class UserAnnotationTests: XCTestCase { }
mit
Alloc-Studio/Hypnos
Hypnos/Pods/JLToast/JLToast/JLToastWindow.swift
1
5413
/* * JLToastView.swift * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2013-2015 Su Yeol Jeon * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. * */ import UIKit public class JLToastWindow: UIWindow { public static let sharedWindow = JLToastWindow(frame: UIScreen.mainScreen().bounds) /// Will not return `rootViewController` while this value is `true`. Or the rotation will be fucked in iOS 9. var isStatusBarOrientationChanging = false /// Don't rotate manually if the application: /// /// - is running on iPad /// - is running on iOS 9 /// - supports all orientations /// - doesn't require full screen /// - has launch storyboard /// var shouldRotateManually: Bool { let iPad = UIDevice.currentDevice().userInterfaceIdiom == .Pad let application = UIApplication.sharedApplication() let window = application.delegate?.window ?? nil let supportsAllOrientations = application.supportedInterfaceOrientationsForWindow(window) == .All let info = NSBundle.mainBundle().infoDictionary let requiresFullScreen = info?["UIRequiresFullScreen"]?.boolValue == true let hasLaunchStoryboard = info?["UILaunchStoryboardName"] != nil if #available(iOS 9, *), iPad && supportsAllOrientations && !requiresFullScreen && hasLaunchStoryboard { return false } return true } override public var rootViewController: UIViewController? { get { guard !self.isStatusBarOrientationChanging else { return nil } return UIApplication.sharedApplication().windows.first?.rootViewController } set { /* Do nothing */ } } public override init(frame: CGRect) { super.init(frame: frame) self.userInteractionEnabled = false self.windowLevel = CGFloat.max self.backgroundColor = .clearColor() self.hidden = false self.handleRotate(UIApplication.sharedApplication().statusBarOrientation) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.bringWindowToTop), name: UIWindowDidBecomeVisibleNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.statusBarOrientationWillChange), name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.statusBarOrientationDidChange), name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil ) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Bring JLToastWindow to top when another window is being shown. func bringWindowToTop(notification: NSNotification) { if !(notification.object is JLToastWindow) { self.dynamicType.sharedWindow.hidden = true self.dynamicType.sharedWindow.hidden = false } } dynamic func statusBarOrientationWillChange() { self.isStatusBarOrientationChanging = true } dynamic func statusBarOrientationDidChange() { let orientation = UIApplication.sharedApplication().statusBarOrientation self.handleRotate(orientation) self.isStatusBarOrientationChanging = false } func applicationDidBecomeActive() { let orientation = UIApplication.sharedApplication().statusBarOrientation self.handleRotate(orientation) } func handleRotate(orientation: UIInterfaceOrientation) { let angle = self.angleForOrientation(orientation) if self.shouldRotateManually { self.transform = CGAffineTransformMakeRotation(CGFloat(angle)) } if let window = UIApplication.sharedApplication().windows.first { if orientation.isPortrait || !self.shouldRotateManually { self.frame.size.width = window.bounds.size.width self.frame.size.height = window.bounds.size.height } else { self.frame.size.width = window.bounds.size.height self.frame.size.height = window.bounds.size.width } } self.frame.origin = .zero dispatch_async(dispatch_get_main_queue()) { JLToastCenter.defaultCenter().currentToast?.view.updateView() } } func angleForOrientation(orientation: UIInterfaceOrientation) -> Double { switch orientation { case .LandscapeLeft: return -M_PI_2 case .LandscapeRight: return M_PI_2 case .PortraitUpsideDown: return M_PI default: return 0 } } }
mit
Ryce/flickrpickr
FlickrPickr/Protocol/Reusable.swift
1
473
// // Reusable.swift // FlickrPickr // // Created by Hamon Riazy on 13/07/2017. // Copyright © 2017 Hamon Riazy. All rights reserved. // import UIKit protocol Reusable: class { static var reuseIdentifier: String { get } } extension Reusable { static var reuseIdentifier: String { // I like to use the class's name as an identifier // so this makes a decent default value. return String(describing: self) } }
mit
ilyapuchka/VIPER-SWIFT
VIPER-SWIFTTests/CalendarTests.swift
1
3119
// // CalendarTests.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/6/14. // Copyright (c) 2014 Conrad Stoll. All rights reserved. // import XCTest class CalendarTests: XCTestCase { var calendar: NSCalendar! override func setUp() { super.setUp() calendar = NSCalendar.gregorianCalendar() } func testEarlyYearMonthDayIsBeforeLaterYearMonthDay() { let earlyDate = calendar.dateWithYear(2004, month: 2, day: 29) let laterDate = calendar.dateWithYear(2004, month: 3, day: 1) let comparison = calendar.isDate(earlyDate, beforeYearMonthDay: laterDate) XCTAssert(comparison, "\(earlyDate) should be before \(laterDate)") } func testYearMonthDayIsNotBeforeSameYearMonthDay() { let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1) let laterDate = calendar.dateWithYear(2005, month: 6, day: 1) let comparison = calendar.isDate(earlyDate, beforeYearMonthDay: laterDate) XCTAssertFalse(comparison, "\(earlyDate) should not be before \(laterDate)") } func testLaterYearMonthDayIsNotBeforeEarlyYearMonthDay() { let earlyDate = calendar.dateWithYear(2006, month: 4, day: 15) let laterDate = calendar.dateWithYear(2006, month: 4, day: 16) let comparison = calendar.isDate(laterDate, beforeYearMonthDay: earlyDate) XCTAssertFalse(comparison, "\(earlyDate) should not be before \(laterDate)") } func testEqualYearMonthDaysCompareAsEqual() { let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1) let laterDate = calendar.dateWithYear(2005, month: 6, day: 1) let comparison = calendar.isDate(earlyDate, equalToYearMonthDay: laterDate) XCTAssert(comparison, "\(earlyDate) should equal \(laterDate)") } func testDifferentYearMonthDaysCompareAsNotEqual() { let earlyDate = calendar.dateWithYear(2005, month: 6, day: 1) let laterDate = calendar.dateWithYear(2005, month: 6, day: 2) let comparison = calendar.isDate(earlyDate, equalToYearMonthDay: laterDate) XCTAssertFalse(comparison, "\(earlyDate) should not equal \(laterDate)") } func testEndOfNextWeekDuringSameYear() { let date = calendar.dateWithYear(2005, month: 8, day: 2) let expectedNextWeek = calendar.dateWithYear(2005, month: 8, day: 13) let nextWeek = calendar.dateForEndOfFollowingWeekWithDate(date) let comparison = calendar.isDate(nextWeek, equalToYearMonthDay: expectedNextWeek) XCTAssert(comparison, "Next week should end on \(expectedNextWeek) (not \(nextWeek))") } func testEndOfNextWeekDuringFollowingYear() { let date = calendar.dateWithYear(2005, month: 12, day: 27) let expectedNextWeek = calendar.dateWithYear(2006, month: 1, day: 7) let nextWeek = calendar.dateForEndOfFollowingWeekWithDate(date) let comparison = calendar.isDate(nextWeek, equalToYearMonthDay: expectedNextWeek) XCTAssert(comparison, "Next week should end on \(expectedNextWeek) (not \(nextWeek))") } }
mit
fortmarek/SwipeViewController
SwipeViewController_Example/TestViewController.swift
1
955
// // TestViewController.swift // SwipeViewController_Example // // Created by Marek Fořt on 1/13/18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton() button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) button.setTitle("Button", for: .normal) button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } @objc private func buttonTapped() { let viewController = UIViewController() viewController.view.backgroundColor = .black navigationController?.pushViewController(viewController, animated: true) } }
mit
kstaring/swift
stdlib/public/SDK/Dispatch/Dispatch.swift
4
5564
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Dispatch import SwiftShims /// dispatch_assert @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public enum DispatchPredicate { case onQueue(DispatchQueue) case onQueueAsBarrier(DispatchQueue) case notOnQueue(DispatchQueue) } @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public func _dispatchPreconditionTest(_ condition: DispatchPredicate) -> Bool { switch condition { case .onQueue(let q): __dispatch_assert_queue(q) case .onQueueAsBarrier(let q): __dispatch_assert_queue_barrier(q) case .notOnQueue(let q): __dispatch_assert_queue_not(q) } return true } @_transparent @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) public func dispatchPrecondition(condition: @autoclosure () -> DispatchPredicate) { // precondition is able to determine release-vs-debug asserts where the overlay // cannot, so formulating this into a call that we can call with precondition() precondition(_dispatchPreconditionTest(condition()), "dispatchPrecondition failure") } /// qos_class_t public struct DispatchQoS : Equatable { public let qosClass: QoSClass public let relativePriority: Int @available(OSX 10.10, iOS 8.0, *) public static let background = DispatchQoS(qosClass: .background, relativePriority: 0) @available(OSX 10.10, iOS 8.0, *) public static let utility = DispatchQoS(qosClass: .utility, relativePriority: 0) @available(OSX 10.10, iOS 8.0, *) public static let `default` = DispatchQoS(qosClass: .default, relativePriority: 0) @available(OSX 10.10, iOS 8.0, *) public static let userInitiated = DispatchQoS(qosClass: .userInitiated, relativePriority: 0) @available(OSX 10.10, iOS 8.0, *) public static let userInteractive = DispatchQoS(qosClass: .userInteractive, relativePriority: 0) public static let unspecified = DispatchQoS(qosClass: .unspecified, relativePriority: 0) public enum QoSClass { @available(OSX 10.10, iOS 8.0, *) case background @available(OSX 10.10, iOS 8.0, *) case utility @available(OSX 10.10, iOS 8.0, *) case `default` @available(OSX 10.10, iOS 8.0, *) case userInitiated @available(OSX 10.10, iOS 8.0, *) case userInteractive case unspecified @available(OSX 10.10, iOS 8.0, *) public init?(rawValue: qos_class_t) { switch rawValue { case QOS_CLASS_BACKGROUND: self = .background case QOS_CLASS_UTILITY: self = .utility case QOS_CLASS_DEFAULT: self = .default case QOS_CLASS_USER_INITIATED: self = .userInitiated case QOS_CLASS_USER_INTERACTIVE: self = .userInteractive case QOS_CLASS_UNSPECIFIED: self = .unspecified default: return nil } } @available(OSX 10.10, iOS 8.0, *) public var rawValue: qos_class_t { switch self { case .background: return QOS_CLASS_BACKGROUND case .utility: return QOS_CLASS_UTILITY case .default: return QOS_CLASS_DEFAULT case .userInitiated: return QOS_CLASS_USER_INITIATED case .userInteractive: return QOS_CLASS_USER_INTERACTIVE case .unspecified: return QOS_CLASS_UNSPECIFIED } } } public init(qosClass: QoSClass, relativePriority: Int) { self.qosClass = qosClass self.relativePriority = relativePriority } } public func ==(a: DispatchQoS, b: DispatchQoS) -> Bool { return a.qosClass == b.qosClass && a.relativePriority == b.relativePriority } /// public enum DispatchTimeoutResult { case success case timedOut } /// dispatch_group public extension DispatchGroup { public func notify(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], queue: DispatchQueue, execute work: @escaping @convention(block) () -> ()) { if #available(OSX 10.10, iOS 8.0, *), qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: work) _swift_dispatch_group_notify(self, queue, item._block) } else { _swift_dispatch_group_notify(self, queue, work) } } @available(OSX 10.10, iOS 8.0, *) public func notify(queue: DispatchQueue, work: DispatchWorkItem) { _swift_dispatch_group_notify(self, queue, work._block) } public func wait() { _ = __dispatch_group_wait(self, DispatchTime.distantFuture.rawValue) } public func wait(timeout: DispatchTime) -> DispatchTimeoutResult { return __dispatch_group_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } public func wait(wallTimeout timeout: DispatchWallTime) -> DispatchTimeoutResult { return __dispatch_group_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } } /// dispatch_semaphore public extension DispatchSemaphore { @discardableResult public func signal() -> Int { return __dispatch_semaphore_signal(self) } public func wait() { _ = __dispatch_semaphore_wait(self, DispatchTime.distantFuture.rawValue) } public func wait(timeout: DispatchTime) -> DispatchTimeoutResult { return __dispatch_semaphore_wait(self, timeout.rawValue) == 0 ? .success : .timedOut } public func wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult { return __dispatch_semaphore_wait(self, wallTimeout.rawValue) == 0 ? .success : .timedOut } }
apache-2.0
csano/blink-api-swift
src/blinkapi/Data/blinkAccount.swift
1
199
public struct BlinkAccount { let email: String; let password: String; public init(email: String, password: String) { self.email = email self.password = password } }
lgpl-3.0
Mayfleet/SimpleChat
Frontend/iOS/SimpleChat/SimpleChat/Logic/StorageDispatcher.swift
1
975
// // Created by Maxim Pervushin on 06/03/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import Foundation class StorageDispatcher { static let defaultDispatcher = StorageDispatcher() private let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] private func filePath(fileName: String) -> String? { return (documentsPath as NSString).stringByAppendingPathComponent("\(fileName).json") } func writeString(string: String, fileName: String) -> Bool { do { try string.writeToFile(filePath(fileName)!, atomically: true, encoding: NSUTF8StringEncoding) return true } catch { return false } } func readString(fileName: String) -> String? { do { return try String(contentsOfFile: filePath(fileName)!, encoding: NSUTF8StringEncoding) } catch { return nil } } }
mit
tonilopezmr/Learning-Swift
Learning-Swift/Learning-Swift/looping.swift
1
1599
// // looping.swift // Learning-Swift // // Created by Antonio López Marín on 10/01/16. // Copyright © 2016 Antonio López Marín. All rights reserved. // import Foundation class LoopingExample: ExampleProtocol{ func example(){ print("**** Looping Examples ****") var complete: Bool = false var cont = 0 while !complete { printDownloading(cont) cont++ if cont > 8 { complete = true } } print("*** repeat - while ***") complete = false cont = 0; repeat { printDownloading(cont) cont++ if cont > 10 { complete = true } } while !complete for number in 0...10 { print(number) } indexLoopExample() } func printDownloading(cont: Int){ var downloadingMessage = "Downloading.." for var i = 0; i < cont; i++ { downloadingMessage += "." } print(downloadingMessage) } func indexLoopExample(){ //Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values. var firstForLoop = 0 for i in 0..<4 { print("") firstForLoop = i } print(firstForLoop) var secondForLoop = 0 for i in 0...4 { secondForLoop = i } print(secondForLoop) } }
apache-2.0
hirohitokato/HKLColorTable
HKLColorTable/Sources/CommonColors.swift
1
22356
// // KatakanaColors.swift // HKLColorTable // // Created by Hirohito Kato on 2016/04/16. // Copyright © 2016 Hirohito Kato. All rights reserved. // import UIKit /// Common color name : http://www.colordic.org/y/ public enum CommonColor: Int { case CoralRed = 0 // 慣用色名 コーラルレッド / 0xef857d case SunshineYellow // 慣用色名 サンシャインイエロー / 0xffedab case IceGreen // 慣用色名 アイスグリーン / 0xa3d6cc case Wistaria // 慣用色名 ウイスタリア / 0x8d93c8 case PinkAlmond // 慣用色名 ピンクアーモンド / 0xe3acae case PoppyRed // 慣用色名 ポピーレッド / 0xea5550 case CreamYellow // 慣用色名 クリームイエロー / 0xfff3b8 case TurquoiseGreen // 慣用色名 ターコイズグリーン / 0x00947a case BlueLavender // 慣用色名 ブルーラベンダー / 0xa4a8d4 case RoseDust // 慣用色名 ローズダスト / 0xe6c0c0 case Red // 慣用色名 レッド / 0xea5550 case NaplesYellow // 慣用色名 ネープルスイエロー / 0xfdd35c case SeaGreen // 慣用色名 シーグリーン / 0x00ac97 case Pannsy // 慣用色名 パンジー / 0x4d4398 case White // 慣用色名 ホワイト / 0xffffff case TomatoRed // 慣用色名 トマトレッド / 0xea5549 case Topaz // 慣用色名 トパーズ / 0xe9bc00 case PeppermintGreen // 慣用色名 ペパーミントグリーン / 0x00ac9a case Violet // 慣用色名 バイオレット / 0x5a4498 case SnowWhite // 慣用色名 スノーホワイト / 0xfafdff case Vermilion // 慣用色名 バーミリオン / 0xea553a case ChromeYellow // 慣用色名 クロムイエロー / 0xfcc800 case PeacockGreen // 慣用色名 ピーコックグリーン / 0x00a497 case Heliotrope // 慣用色名 ヘリオトロープ / 0x9079b6 case PinkWhite // 慣用色名 ピンクホワイト / 0xfef9fb case Scarlet // 慣用色名 スカーレット / 0xea5532 case Cream // 慣用色名 クリーム / 0xe3d7a3 case NileBlue // 慣用色名 ナイルブルー / 0x2cb4ad case DeepRoyalPurple // 慣用色名 ディープロイヤルパープル / 0x47266e case MilkyWhite // 慣用色名 ミルキーホワイト / 0xfffff9 case CarrotOrange // 慣用色名 キャロットオレンジ / 0xed6d35 case Straw // 慣用色名 ストロー / 0xece093 case SaxeBlue // 慣用色名 サックスブルー / 0x418b89 case Grape // 慣用色名 グレープ / 0x56256e case AmberWhite // 慣用色名 アンバーホワイト / 0xfff9f5 case ChineseRed // 慣用色名 チャイニーズレッド / 0xed6d46 case JasmineYellow // 慣用色名 ジャスミンイエロー / 0xedde7b case SlateGreen // 慣用色名 スレートグリーン / 0x3c7170 case Mauve // 慣用色名 モーブ / 0x915da3 case LavenderIce // 慣用色名 ラベンダーアイス / 0xf7f6fb case Terracotta // 慣用色名 テラコッタ / 0xbd6856 case AntiqueGold // 慣用色名 アンティックゴールド / 0xc1ab05 case TealGreen // 慣用色名 テールグリーン / 0x006a6c case Iris // 慣用色名 アイリス / 0xc7a5cc case PearlWhite // 慣用色名 パールホワイト / 0xf7f6f5 case CocoaBrown // 慣用色名 ココアブラウン / 0x98605e case Olive // 慣用色名 オリーブ / 0x72640c case AquaGreen // 慣用色名 アクアグリーン / 0x88bfbf case Lilac // 慣用色名 ライラック / 0xd1bada case Ivory // 慣用色名 アイボリー / 0xf8f4e6 case Mahogany // 慣用色名 マホガニー / 0x6b3f31 case OliveDrab // 慣用色名 オリーブドラブ / 0x665a1a case Aquamarine // 慣用色名 アクアマリン / 0x67b5b7 case Lavender // 慣用色名 ラベンダー / 0xcab8d9 case PowderPink // 慣用色名 パウダーピンク / 0xf5ecf4 case Chocolate // 慣用色名 チョコレート / 0x6c3524 case JauneBrillant // 慣用色名 ジョンブリアン / 0xffdc00 case PeacockBlue // 慣用色名 ピーコックブルー / 0x009e9f case Crocus // 慣用色名 クロッカス / 0xb79fcb case SilverWhite // 慣用色名 シルバーホワイト / 0xefefef case Marron // 慣用色名 マルーン / 0x6a1917 case Yellow // 慣用色名 イエロー / 0xffdc00 case Turquoise // 慣用色名 ターコイズ / 0x009b9f case LavenderMauve // 慣用色名 ラベンダーモーブ / 0xa688bd case FrostyGray // 慣用色名 フロスティグレイ / 0xe8ece9 case Sepia // 慣用色名 セピア / 0x622d18 case Citrus // 慣用色名 シトラス / 0xeddc44 case CapriBlue // 慣用色名 カプリブルー / 0x00a3a7 case Purple // 慣用色名 パープル / 0x9b72b0 case SilverPink // 慣用色名 シルバーピンク / 0xeeeaec case CoffeeIro // 慣用色名 コーヒー色 / 0x7b5544 case Limelight // 慣用色名 ライムライト / 0xfff799 case CambridgeBlue // 慣用色名 ケンブリッジブルー / 0x25b7c0 case RoyalPurple // 慣用色名 ロイヤルパープル / 0x7f1184 case BeigeCameo // 慣用色名 ベージュカメオ / 0xeee9e6 case Brown // 慣用色名 ブラウン / 0x8f6552 case CanaryYellow // 慣用色名 カナリヤ / 0xfff462 case TurquoiseBlue // 慣用色名 ターコイズブルー / 0x00afcc case Raisin // 慣用色名 レーズン / 0x6b395f case Ecru // 慣用色名 エクリュ / 0xeee7e0 case BurntSienna // 慣用色名 バーントシェンナ / 0xbb5535 case Mimosa // 慣用色名 ミモザ / 0xfff462 case HorizonBlue // 慣用色名 ホライズンブルー / 0x82cddd case Plum // 慣用色名 プラム / 0x6c2463 case PinkBeige // 慣用色名 ピンクベージュ / 0xede4e1 case AmberRose // 慣用色名 アンバーローズ / 0xe6bfb2 case LemonYellow // 慣用色名 レモンイエロー / 0xfff352 case SummerShower // 慣用色名 サマーシャワー / 0xa1d8e2 case Raspberry // 慣用色名 ラズベリー / 0x841a75 case FrostyWhite // 慣用色名 フロスティホワイト / 0xe6eae6 case BeigeRose // 慣用色名 ベージュローゼ / 0xe8d3ca case MelonYellow // 慣用色名 メロンイエロー / 0xe0de94 case HorizonBlue2 // 慣用色名 ホリゾンブルー / 0xa1d8e6 case Framboise // 慣用色名 フランボワーズ / 0x9a0d7c case OysterWhite // 慣用色名 オイスターホワイト / 0xeae8e1 case SalmonPink // 慣用色名 サーモンピンク / 0xf3a68c case ChartreuseYellow // 慣用色名 シャルトルーズイエロー / 0xe3e548 case CeruleanBlue // 慣用色名 セルリアンブルー / 0x008db7 case DahliaPurple // 慣用色名 ダリアパープル / 0xa50082 case WisteriaMist // 慣用色名 ウィステリアミスト / 0xd3d6dd case Sahara // 慣用色名 サハラ / 0xe29676 case LimeYellow // 慣用色名 ライムイエロー / 0xeaeea2 case DuckBlue // 慣用色名 ダックブルー / 0x007199 case OrchidPurple // 慣用色名 オーキッドパープル / 0xaf0082 case Cloud // 慣用色名 クラウド / 0xd4d9df case AshRose // 慣用色名 アッシュローズ / 0xe6bfab case LimeGreen // 慣用色名 ライムグリーン / 0xe6eb94 case MarineBlue // 慣用色名 マリンブルー / 0x006888 case RaspberryRed // 慣用色名 ラズベリーレッド / 0x9f166a case MoonGray // 慣用色名 ムーングレイ / 0xd4d9dc case ShellPink // 慣用色名 シェルピンク / 0xfbdac8 case ChartreuseGreen // 慣用色名 シャトルーズグリーン / 0xd9e367 case MadonnaBlue // 慣用色名 マドンナブルー / 0x00608d case Orchid // 慣用色名 オーキッド / 0xd9aacd case ChinaClay // 慣用色名 チャイナクレイ / 0xd4dcd3 case BabyPink // 慣用色名 ベビーピンク / 0xfdede4 case LettuceGreen // 慣用色名 レタスグリーン / 0xd1de4c case EgyptianBlue // 慣用色名 エジプシャンブルー / 0x0073a8 case Lilla // 慣用色名 リラ / 0xe0b5d3 case SandBeige // 慣用色名 サンドベージュ / 0xdcd6d2 case NailPink // 慣用色名 ネールピンク / 0xfce4d6 case OliveGreen // 慣用色名 オリーブグリーン / 0x5f6527 case BabyBule // 慣用色名 ベビーブルー / 0xbbe2f1 case RoseTendre // 慣用色名 ローズタンドル / 0xe6afcf case OrchidMist // 慣用色名 オーキッドミスト / 0xd3d3d8 case RawSienna // 慣用色名 ローシェンナ / 0xe17b34 case MossGreen // 慣用色名 モスグリーン / 0x777e41 case SkyBlue // 慣用色名 スカイブルー / 0xa0d8ef case OrchidPink // 慣用色名 オーキッドピンク / 0xda81b2 case ReedGray // 慣用色名 リードグレイ / 0xd4d9d6 case Caramel // 慣用色名 キャラメル / 0xbc611e case GrassGreen // 慣用色名 グラスグリーン / 0x7b8d42 case ShadowBlue // 慣用色名 シャドウブルー / 0x719bad case CyclamenPink // 慣用色名 シクラメンピンク / 0xd04f97 case SkyGray // 慣用色名 スカイグレイ / 0xcbd0d3 case Sunset // 慣用色名 サンセット / 0xf6b483 case SpringGreen // 慣用色名 スプリンググリーン / 0x9cbb1c case Cyan // 慣用色名 シアン / 0x00a1e9 case Magenta // 慣用色名 マゼンタ / 0xe4007f case LavenderGray // 慣用色名 ラベンダーグレイ / 0xbcbace case Cinnamon // 慣用色名 シナモン / 0xbe8f68 case LeafGreen // 慣用色名 リーフグリーン / 0x9fc24d case YachtBlue // 慣用色名 ヨットブルー / 0x409ecc case Bougainvillaea // 慣用色名 ブーゲンビリア / 0xe62f8b case Silver // 慣用色名 シルバー / 0xc9caca case Tan // 慣用色名 タン / 0xbf783e case WhiteLily // 慣用色名 ホワイトリリー / 0xf0f6da case ChalkBlue // 慣用色名 チョークブルー / 0x68a9cf case Ruby // 慣用色名 ルビー / 0xc70067 case PearlGray // 慣用色名 パールグレイ / 0xc9c9c4 case Champagne // 慣用色名 シャンパン / 0xe9dacb case AsparagusGreen // 慣用色名 アスパラガスグリーン / 0xdbebc4 case PigeonBlue // 慣用色名 ピジョンブルー / 0x88b5d3 case Claret // 慣用色名 クラレット / 0x941f57 case SandGray // 慣用色名 サンドグレイ / 0xc9c9c2 case Peach // 慣用色名 ピーチ / 0xfbd8b5 case CitronGreen // 慣用色名 シトロングリーン / 0x618e34 case SmokeBlue // 慣用色名 スモークブルー / 0xa4c1d7 case Azalee // 慣用色名 アザレ / 0xd83473 case MarbleGray // 慣用色名 マーブルグレイ / 0xc0c5c2 case CafeAuLait // 慣用色名 カフェオレ / 0x946c45 case MeadowGreen // 慣用色名 メドウグリーン / 0x65ab31 case FrostyBlue // 慣用色名 フロスティブルー / 0xbbdbf3 case Cosmos // 慣用色名 コスモス / 0xdc6b9a case OpalGray // 慣用色名 オパールグレイ / 0xbfbec5 case Orange // 慣用色名 オレンジ / 0xee7800 case AppleGreen // 慣用色名 アップルグリーン / 0xa7d28d case BleuAcide // 慣用色名 ブルーアシード / 0x006eb0 case LotusPink // 慣用色名 ロータスピンク / 0xde82a7 case FrenchGray // 慣用色名 フレンチグレイ / 0x8da0b6 case Apricot // 慣用色名 アプリコット / 0xf7b977 case IvyGreen // 慣用色名 アイビーグリーン / 0x578a3d case CobaltBlue // 慣用色名 コバルトブルー / 0x0068b7 case OldOrchid // 慣用色名 オールドオーキッド / 0xe3adc1 case Mist // 慣用色名 ミスト / 0xb4aeb1 case Amber // 慣用色名 アンバー / 0xc2894b case SpinachGreen // 慣用色名 スピナッチグリーン / 0x417038 case SapphireBlue // 慣用色名 サファイアブルー / 0x0068b7 case RoseMist // 慣用色名 ローズミスト / 0xdebecc case AshBlond // 慣用色名 アッシュブロンド / 0xb5b5ae case Bronze // 慣用色名 ブロンズ / 0xac6b25 case Cactus // 慣用色名 カクタス / 0x387d39 case SpectrumBlue // 慣用色名 スペクトラムブルー / 0x0075c2 case RoseDragee // 慣用色名 ローズドラジェ / 0xe5c1cd case Fog // 慣用色名 フォッグ / 0xabb1b5 case Vanilla // 慣用色名 ヴァニラ / 0xe8c59c case SkyGreen // 慣用色名 スカイグリーン / 0xbee0c2 case Blue // 慣用色名 ブルー / 0x0075c2 case CherryPink // 慣用色名 チェリーピンク / 0xeb6ea0 case BeigeGray // 慣用色名 ベージュグレイ / 0xb4ada9 case Cork // 慣用色名 コルク / 0xc49a6a case Spearmint // 慣用色名 スペアミント / 0x79c06e case ZenithBlue // 慣用色名 ゼニスブルー / 0x4496d3 case Opera // 慣用色名 オペラ / 0xe95388 case SilverGray // 慣用色名 シルバーグレイ / 0xafafb0 case BurntUmber // 慣用色名 バーントアンバー / 0x6f5436 case MintGreen // 慣用色名 ミントグリーン / 0x89c997 case HeavenlyBlue // 慣用色名 ヘブンリーブルー / 0x68a4d9 case RoseRed // 慣用色名 ローズレッド / 0xea618e case StormGray // 慣用色名 ストームグレイ / 0xaaaab0 case RawUmber // 慣用色名 ローアンバー / 0x866629 case ParrotGreen // 慣用色名 パロットグリーン / 0x37a34a case OrchidGray // 慣用色名 オーキッドグレイ / 0xbcc7d7 case OldLilac // 慣用色名 オールドライラック / 0xb0778c case GreenFog // 慣用色名 グリーンフォッグ / 0xabb1ad case Flesh // 慣用色名 フレッシュ / 0xfad09e case SummerGreen // 慣用色名 サマーグリーン / 0x009944 case PowderBlue // 慣用色名 パウダーブルー / 0xbccddb case CocoaIro // 慣用色名 ココア色 / 0x6e4a55 case AshGray // 慣用色名 アッシュグレイ / 0x9fa09e case GoldenYellow // 慣用色名 ゴールデンイエロー / 0xf6ae54 case OpalGreen // 慣用色名 オパールグリーン / 0xbee0ce case LightBlue // 慣用色名 ライトブルー / 0xb2cbe4 case WineRed // 慣用色名 ワインレッド / 0xb33e5c case RoseGray // 慣用色名 ローズグレイ / 0x9d8e87 case MandarinOrange // 慣用色名 マンダリンオレンジ / 0xf3981d case SprayGreen // 慣用色名 スプレイグリーン / 0xa4d5bd case BabyBlue // 慣用色名 ベイビーブルー / 0xa2c2e6 case Garnet // 慣用色名 ガーネット / 0x942343 case ElephantSkin // 慣用色名 エレファントスキン / 0x9f9f98 case Marigold // 慣用色名 マリーゴールド / 0xf39800 case BottleGreen // 慣用色名 ボトルグリーン / 0x004d25 case DayDream // 慣用色名 デイドリーム / 0xa3b9e0 case CochinealRed // 慣用色名 コチニールレッド / 0xc82c55 case BattleshipGray // 慣用色名 バトルシップグレイ / 0x898989 case EcruBeige // 慣用色名 エクルベージュ / 0xf6e5cc case CobaltGreen // 慣用色名 コバルトグリーン / 0x3cb37a case SalviaBlue // 慣用色名 サルビアブルー / 0x94adda case Strawberry // 慣用色名 ストロベリー / 0xe73562 case StoneGray // 慣用色名 ストーングレイ / 0x898880 case Oyster // 慣用色名 オイスター / 0xeae1cf case Evergreen // 慣用色名 エバーグリーン / 0x00984f case HyacinthBlue // 慣用色名 ヒヤシンスブルー / 0x7a99cf case RubyRed // 慣用色名 ルビーレッド / 0xe73562 case MossGray // 慣用色名 モスグレイ / 0x7e837f case Ochre // 慣用色名 オーカー / 0xba8b40 case MalachiteGreen // 慣用色名 マラカイトグリーン / 0x009854 case Hyacinth // 慣用色名 ヒヤシンス / 0x6c9bd2 case Carmine // 慣用色名 カーマイン / 0xd70035 case DoveGray // 慣用色名 ダブグレイ / 0x7d7b83 case Khaki // 慣用色名 カーキー / 0xc5a05a case Green // 慣用色名 グリーン / 0x00a960 case MidnightBlue // 慣用色名 ミッドナイトブルー / 0x001e43 case SignalRed // 慣用色名 シグナルレッド / 0xe8383d case Gray // 慣用色名 グレイ / 0x7d7d7d case Buff // 慣用色名 バフ / 0xcaac71 case EmeraldGreen // 慣用色名 エメラルドグリーン / 0x00a968 case NavyBlue // 慣用色名 ネービーブルー / 0x202f55 case Burgundy // 慣用色名 バーガンディー / 0x6c2735 case SteelGray // 慣用色名 スチールグレイ / 0x736d71 case SaffronYellow // 慣用色名 サフランイエロー / 0xfac559 case ForestGreen // 慣用色名 フォレストグリーン / 0x288c66 case PrussianBlue // 慣用色名 プルシャンブルー / 0x192f60 case Bordeaux // 慣用色名 ボルドー / 0x6c272d case IvyGray // 慣用色名 アイビーグレイ / 0x666c67 case Pumpkin // 慣用色名 パンプキン / 0xe5a323 case Viridian // 慣用色名 ビリジアン / 0x00885a case IronBlue // 慣用色名 アイアンブルー / 0x192f60 case Camellia // 慣用色名 カメリア / 0xda536e case SlateGray // 慣用色名 スレートグレイ / 0x626063 case YellowOcher // 慣用色名 イエローオーカー / 0xc4972f case HollyGreen // 慣用色名 ホーリーグリーン / 0x006948 case Indigo // 慣用色名 インディゴ / 0x043c78 case Rose // 慣用色名 ローズ / 0xe95464 case Graphite // 慣用色名 グラファイト / 0x594e52 case Blond // 慣用色名 ブロンド / 0xf2d58a case BilliardGreen // 慣用色名 ビリヤードグリーン / 0x005c42 case InkBlue // 慣用色名 インクブルー / 0x003f8e case RosePink // 慣用色名 ローズピンク / 0xf19ca7 case CharcoalGray // 慣用色名 チャコールグレイ / 0x4e454a case Beige // 慣用色名 ベージュ / 0xeedcb3 case ChromeGreen // 慣用色名 クロムグリーン / 0x00533f case OrientalBlue // 慣用色名 オリエンタルブルー / 0x26499d case Pink // 慣用色名 ピンク / 0xf5b2b2 case Taupe // 慣用色名 トープ / 0x504946 case Biscuit // 慣用色名 ビスケット / 0xead7a4 case AntiqueGreen // 慣用色名 アンティークグリーン / 0x54917f case UltramarineBlue // 慣用色名 ウルトラマリンブルー / 0x4753a2 case FlamingoPink // 慣用色名 フラミンゴピンク / 0xf5b2ac case LampBlack // 慣用色名 ランプブラック / 0x24140e case Leghorn // 慣用色名 レグホーン / 0xffe9a9 case WaterGreen // 慣用色名 ウォーターグリーン / 0xa5c9c1 case Ultramarine // 慣用色名 ウルトラマリン / 0x434da2 case OldRose // 慣用色名 オールドローズ / 0xe29399 case Black // 慣用色名 ブラック / 0x000000 } extension CommonColor: HKLColorTableRepresentable { public var name: String { return commonKatakanaNameColors[self.rawValue].name } public var uiColor: UIColor { return UIColor(hexValue: commonKatakanaNameColors[self.rawValue].hex) } public var count: Int { return commonKatakanaNameColors.count } }
mit
yangligeryang/codepath
assignments/DropboxDemo/DropboxDemo/SignInFormViewController.swift
1
2835
// // SignInFormViewController.swift // DropboxDemo // // Created by Yang Yang on 10/15/16. // Copyright © 2016 Yang Yang. All rights reserved. // import UIKit class SignInFormViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var formImage: UIImageView! let resetImage = UIImage(named: "sign_in") let activeImage = UIImage(named: "sign_in1") override func viewDidLoad() { super.viewDidLoad() emailField.delegate = self emailField.becomeFirstResponder() passwordField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if emailField.isFirstResponder { emailField.resignFirstResponder() passwordField.becomeFirstResponder() } else if passwordField.isFirstResponder { let characterCount = passwordField.text?.characters.count if characterCount! > 0 { performSegue(withIdentifier: "existingAccount", sender: nil) } } return false } @IBAction func onBack(_ sender: UIButton) { navigationController!.popViewController(animated: true) } @IBAction func onCreate(_ sender: UIButton) { performSegue(withIdentifier: "existingAccount", sender: nil) } @IBAction func didTap(_ sender: UITapGestureRecognizer) { view.endEditing(true) } @IBAction func onForgotPassword(_ sender: UIButton) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let forgotAction = UIAlertAction(title: "Forgot Password?", style: .default) { (action) in } alertController.addAction(forgotAction) let ssoAction = UIAlertAction(title: "Single Sign-On", style: .default) { (action) in } alertController.addAction(ssoAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in } alertController.addAction(cancelAction) present(alertController, animated: true) {} } @IBAction func onPasswordChanged(_ sender: UITextField) { let characterCount = passwordField.text?.characters.count if characterCount! > 0 { signInButton.isEnabled = true formImage.image = activeImage } else { formImage.image = resetImage signInButton.isEnabled = false } } }
apache-2.0
MukeshKumarS/Swift
stdlib/public/SDK/Foundation/NSStringAPI.swift
1
58895
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Open Issues // =========== // // Property Lists need to be properly bridged // @warn_unused_result func _toNSArray<T, U : AnyObject>(a: [T], @noescape f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.addObject(f(s)) } return result } @warn_unused_result func _toNSRange(r: Range<String.Index>) -> NSRange { return NSRange( location: r.startIndex._utf16Index, length: r.endIndex._utf16Index - r.startIndex._utf16Index) } @warn_unused_result func _countFormatSpecifiers(a: String) -> Int { // The implementation takes advantage of the fact that internal // representation of String is UTF-16. Because we only care about the ASCII // percent character, we don't need to decode UTF-16. let percentUTF16 = UTF16.CodeUnit(("%" as UnicodeScalar).value) let notPercentUTF16: UTF16.CodeUnit = 0 var lastChar = notPercentUTF16 // anything other than % would work here var count = 0 for c in a.utf16 { if lastChar == percentUTF16 { if c == percentUTF16 { // a "%" following this one should not be taken as literal lastChar = notPercentUTF16 } else { count += 1 lastChar = c } } else { lastChar = c } } return count } extension String { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. var _ns: NSString { return self as NSString } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. @warn_unused_result func _index(utf16Index: Int) -> Index { return Index(_base: String.UnicodeScalarView.Index(utf16Index, _core)) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. @warn_unused_result func _range(r: NSRange) -> Range<Index> { return _index(r.location)..<_index(r.location + r.length) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. @warn_unused_result func _optionalRange(r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return .None } return _range(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( index: UnsafeMutablePointer<Index>, @noescape body: (UnsafeMutablePointer<Int>)->Result ) -> Result { var utf16Index: Int = 0 let result = index._withBridgeValue(&utf16Index) { body($0) } index._setIfNonNil { self._index(utf16Index) } return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( range: UnsafeMutablePointer<Range<Index>>, @noescape body: (UnsafeMutablePointer<NSRange>)->Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = range._withBridgeValue(&nsRange) { body($0) } range._setIfNonNil { self._range(nsRange) } return result } //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // + (const NSStringEncoding *)availableStringEncodings /// Returns an Array of the encodings string objects support /// in the application’s environment. @warn_unused_result public static func availableStringEncodings() -> [NSStringEncoding] { var result = [NSStringEncoding]() var p = NSString.availableStringEncodings() while p.memory != 0 { result.append(p.memory) p += 1 } return result } // + (NSStringEncoding)defaultCStringEncoding /// Returns the C-string encoding assumed for any method accepting /// a C string as an argument. @warn_unused_result public static func defaultCStringEncoding() -> NSStringEncoding { return NSString.defaultCStringEncoding() } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of a given encoding. @warn_unused_result public static func localizedNameOfStringEncoding( encoding: NSStringEncoding ) -> String { return NSString.localizedNameOfStringEncoding(encoding) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. @warn_unused_result public static func localizedStringWithFormat( format: String, _ arguments: CVarArgType... ) -> String { return String(format: format, locale: NSLocale.currentLocale(), arguments: arguments) } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message="Use fileURLWithPathComponents on NSURL instead.") public static func pathWithComponents(components: [String]) -> String { return NSString.pathWithComponents(components) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Produces a string created by copying the data from a given /// C array of UTF8-encoded bytes. public init?(UTF8String bytes: UnsafePointer<CChar>) { if let ns = NSString(UTF8String: bytes) { self = ns as String } else { return nil } } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the /// `String` can be converted to a given encoding without loss of /// information. @warn_unused_result public func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool { return _ns.canBeConvertedToEncoding(encoding) } // @property NSString* capitalizedString /// Produce a string with the first character from each word changed /// to the corresponding uppercase value. public var capitalizedString: String { return _ns.capitalizedString as String } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the `String` that is produced /// using the current locale. @available(OSX 10.11, iOS 9.0, *) public var localizedCapitalizedString: String { return _ns.localizedCapitalizedString } // - (NSString *)capitalizedStringWithLocale:(NSLocale *)locale /// Returns a capitalized representation of the `String` /// using the specified locale. @warn_unused_result public func capitalizedStringWithLocale(locale: NSLocale?) -> String { return _ns.capitalizedStringWithLocale(locale) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. @warn_unused_result public func caseInsensitiveCompare(aString: String) -> NSComparisonResult { return _ns.caseInsensitiveCompare(aString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(NSStringCompareOptions)mask /// Returns a string containing characters the `String` and a /// given string have in common, starting from the beginning of each /// up to the first characters that aren’t equivalent. @warn_unused_result public func commonPrefixWithString( aString: String, options: NSStringCompareOptions) -> String { return _ns.commonPrefixWithString(aString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(NSStringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(NSStringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(NSStringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. @warn_unused_result public func compare( aString: String, options mask: NSStringCompareOptions = [], range: Range<Index>? = nil, locale: NSLocale? = nil ) -> NSComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. return locale != nil ? _ns.compare( aString, options: mask, range: _toNSRange(range ?? self.characters.indices), locale: locale) : range != nil ? _ns.compare( aString, options: mask, range: _toNSRange(range ?? self.characters.indices)) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the `String` as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the `String`. /// Returns the actual number of matching paths. @warn_unused_result public func completePathIntoString( outputName: UnsafeMutablePointer<String> = nil, caseSensitive: Bool, matchesIntoArray: UnsafeMutablePointer<[String]> = nil, filterTypes: [String]? = nil ) -> Int { var nsMatches: NSArray? var nsOutputName: NSString? let result = outputName._withBridgeObject(&nsOutputName) { outputName in matchesIntoArray._withBridgeObject(&nsMatches) { matchesIntoArray in self._ns.completePathIntoString( outputName, caseSensitive: caseSensitive, matchesIntoArray: matchesIntoArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion matchesIntoArray._setIfNonNil { _convertNSArrayToArray(matches) } } if let n = nsOutputName { outputName._setIfNonNil { n as String } } return result } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the `String` /// that have been divided by characters in a given set. @warn_unused_result public func componentsSeparatedByCharactersInSet( separator: NSCharacterSet ) -> [String] { // FIXME: two steps due to <rdar://16971181> let nsa = _ns.componentsSeparatedByCharactersInSet(separator) as NSArray // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion return _convertNSArrayToArray(nsa) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the `String` /// that have been divided by a given separator. public func componentsSeparatedByString(separator: String) -> [String] { let nsa = _ns.componentsSeparatedByString(separator) as NSArray // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion return _convertNSArrayToArray(nsa) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` as a C string /// using a given encoding. @warn_unused_result public func cStringUsingEncoding(encoding: NSStringEncoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cStringUsingEncoding(encoding)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns an `NSData` object containing a representation of /// the `String` encoded using a given encoding. @warn_unused_result public func dataUsingEncoding( encoding: NSStringEncoding, allowLossyConversion: Bool = false ) -> NSData? { return _ns.dataUsingEncoding( encoding, allowLossyConversion: allowLossyConversion) } // @property NSString* decomposedStringWithCanonicalMapping; /// Returns a string made by normalizing the `String`’s /// contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// Returns a string made by normalizing the `String`’s /// contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines(body: (line: String, inout stop: Bool)->()) { _ns.enumerateLinesUsingBlock { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line: line, stop: &stop_) if stop_ { UnsafeMutablePointer<ObjCBool>(stop).memory = true } } } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(NSLinguisticTaggerOptions)opts // orthography:(NSOrthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTagsInRange( range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool)->() ) { _ns.enumerateLinguisticTagsInRange( _toNSRange(range), scheme: tagScheme, options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).memory = true } } } // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the /// specified range of the string. public func enumerateSubstringsInRange( range: Range<Index>, options opts:NSStringEnumerationOptions, _ body: ( substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool )->() ) { _ns.enumerateSubstringsInRange(_toNSRange(range), options: opts) { var stop_ = false body(substring: $0, substringRange: self._range($1), enclosingRange: self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).memory = true } } } // @property NSStringEncoding fastestEncoding; /// Returns the fastest encoding to which the `String` may be /// converted without loss of information. public var fastestEncoding: NSStringEncoding { return _ns.fastestEncoding } // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.") public func fileSystemRepresentation() -> [CChar] { return _persistCString(_ns.fileSystemRepresentation)! } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(NSStringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver’s contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` iff some characters were converted. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes( inout buffer: [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: NSStringEncoding, options: NSStringEncodingConversionOptions, range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding, options: options, range: _toNSRange(range), remainingRange: $0) } } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`’s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( inout buffer: [CChar], maxLength: Int, encoding: NSStringEncoding ) -> Bool { return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength), encoding: encoding) } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.") public func getFileSystemRepresentation( inout buffer: [CChar], maxLength: Int) -> Bool { return _ns.getFileSystemRepresentation( &buffer, maxLength: min(buffer.count, maxLength)) } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart( start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, forRange: _toNSRange(forRange)) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart( start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, forRange: _toNSRange(forRange)) } } } } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Produces an initialized `NSString` object equivalent to the given /// `bytes` interpreted in the given `encoding`. public init? < S: SequenceType where S.Generator.Element == UInt8 >( bytes: S, encoding: NSStringEncoding ) { let byteArray = Array(bytes) if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding) { self = ns as String } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Produces an initialized `String` object that contains a /// given number of bytes from a given buffer of bytes interpreted /// in a given encoding, and optionally frees the buffer. WARNING: /// this initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, encoding: NSStringEncoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding, freeWhenDone: flag) { self = ns as String } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Returns an initialized `String` object that contains a /// given number of characters from a given array of Unicode /// characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = NSString(characters: utf16CodeUnits, length: count) as String } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Returns an initialized `String` object that contains a given /// number of characters from a given array of UTF-16 Code Units public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = NSString( charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag) as String } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: String, encoding enc: NSStringEncoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc) self = ns as String } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: String, usedEncoding: UnsafeMutablePointer<NSStringEncoding> = nil ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: usedEncoding) self = ns as String } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOfURL url: NSURL, encoding enc: NSStringEncoding ) throws { let ns = try NSString(contentsOfURL: url, encoding: enc) self = ns as String } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<NSStringEncoding> = nil ) throws { let ns = try NSString(contentsOfURL: url, usedEncoding: enc) self = ns as String } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( CString: UnsafePointer<CChar>, encoding enc: NSStringEncoding ) { if let ns = NSString(CString: CString, encoding: enc) { self = ns as String } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: NSData, encoding: NSStringEncoding) { guard let s = NSString(data: data, encoding: encoding) else { return nil } self = s as String } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: String, _ arguments: CVarArgType...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user’s default locale. public init(format: String, arguments: [CVarArgType]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: NSLocale?, _ args: CVarArgType...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: NSLocale?, arguments: [CVarArgType]) { _precondition( _countFormatSpecifiers(format) <= arguments.count, "Too many format specifiers (%<letter>) provided for the argument list" ) self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message="Use lastPathComponent on NSURL instead.") public var lastPathComponent: String { return _ns.lastPathComponent } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message="Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { return _ns.length } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. @warn_unused_result public func lengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int { return _ns.lengthOfBytesUsingEncoding(encoding) } // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. @warn_unused_result public func lineRangeForRange(aRange: Range<Index>) -> Range<Index> { return _range(_ns.lineRangeForRange(_toNSRange(aRange))) } // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(NSLinguisticTaggerOptions)opts // orthography:(NSOrthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. @warn_unused_result public func linguisticTagsInRange( range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]> = nil // FIXME:Can this be nil? ) -> [String] { var nsTokenRanges: NSArray? = nil let result = tokenRanges._withBridgeObject(&nsTokenRanges) { self._ns.linguisticTagsInRange( _toNSRange(range), scheme: tagScheme, options: opts, orthography: orthography != nil ? orthography! : nil, tokenRanges: $0) as NSArray } if nsTokenRanges != nil { tokenRanges._setIfNonNil { (nsTokenRanges! as [AnyObject]).map { self._range($0.rangeValue) } } } return _convertNSArrayToArray(result) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and a given string using a /// case-insensitive, localized, comparison. @warn_unused_result public func localizedCaseInsensitiveCompare(aString: String) -> NSComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and a given string using a localized /// comparison. @warn_unused_result public func localizedCompare(aString: String) -> NSComparisonResult { return _ns.localizedCompare(aString) } /// Compares strings as sorted by the Finder. @warn_unused_result public func localizedStandardCompare(string: String) -> NSComparisonResult { return _ns.localizedStandardCompare(string) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercaseString NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(OSX 10.11, iOS 9.0, *) public var localizedLowercaseString: String { return _ns.localizedLowercaseString } // - (NSString *)lowercaseStringWithLocale:(NSLocale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. @warn_unused_result public func lowercaseStringWithLocale(locale: NSLocale?) -> String { return _ns.lowercaseStringWithLocale(locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. @warn_unused_result public func maximumLengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int { return _ns.maximumLengthOfBytesUsingEncoding(encoding) } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. @warn_unused_result public func paragraphRangeForRange(aRange: Range<Index>) -> Range<Index> { return _range(_ns.paragraphRangeForRange(_toNSRange(aRange))) } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message="Use pathComponents on NSURL instead.") public var pathComponents: [String] { return _ns.pathComponents } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`’s extension, if any. @available(*, unavailable, message="Use pathExtension on NSURL instead.") public var pathExtension: String { return _ns.pathExtension } // @property NSString* precomposedStringWithCanonicalMapping; /// Returns a string made by normalizing the `String`’s /// contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// Returns a string made by normalizing the `String`’s /// contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. @warn_unused_result public func propertyList() -> AnyObject { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. @warn_unused_result public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String] } // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(NSStringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(NSStringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. @warn_unused_result public func rangeOfCharacterFromSet( aSet: NSCharacterSet, options mask:NSStringCompareOptions = [], range aRange: Range<Index>? = nil )-> Range<Index>? { return _optionalRange( _ns.rangeOfCharacterFromSet( aSet, options: mask, range: _toNSRange(aRange ?? self.characters.indices))) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. @warn_unused_result public func rangeOfComposedCharacterSequenceAtIndex(anIndex: Index) -> Range<Index> { return _range( _ns.rangeOfComposedCharacterSequenceAtIndex(anIndex._utf16Index)) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. @warn_unused_result public func rangeOfComposedCharacterSequencesForRange( range: Range<Index> ) -> Range<Index> { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _range( _ns.rangeOfComposedCharacterSequencesForRange(_toNSRange(range))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(NSStringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(NSStringCompareOptions)mask // range:(NSRange)searchRange // locale:(NSLocale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. @warn_unused_result public func rangeOfString( aString: String, options mask: NSStringCompareOptions = [], range searchRange: Range<Index>? = nil, locale: NSLocale? = nil ) -> Range<Index>? { return _optionalRange( locale != nil ? _ns.rangeOfString( aString, options: mask, range: _toNSRange(searchRange ?? self.characters.indices), locale: locale ) : searchRange != nil ? _ns.rangeOfString( aString, options: mask, range: _toNSRange(searchRange!) ) : !mask.isEmpty ? _ns.rangeOfString(aString, options: mask) : _ns.rangeOfString(aString) ) } // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns `true` if `self` contains `string`, taking the current locale /// into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func localizedStandardContainsString(string: String) -> Bool { return _ns.localizedStandardContainsString(string) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func localizedStandardRangeOfString(string: String) -> Range<Index>? { return _optionalRange(_ns.localizedStandardRangeOfString(string)) } // @property NSStringEncoding smallestEncoding; /// Returns the smallest encoding to which the `String` can /// be converted without loss of information. public var smallestEncoding: NSStringEncoding { return _ns.smallestEncoding } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message="Use stringByAbbreviatingWithTildeInPath on NSString instead.") public var stringByAbbreviatingWithTildeInPath: String { return _ns.stringByAbbreviatingWithTildeInPath } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string made from the `String` by replacing /// all characters not in the specified set with percent encoded /// characters. @warn_unused_result public func stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacters: NSCharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacters ) } // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(*, deprecated, message="Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func stringByAddingPercentEscapesUsingEncoding( encoding: NSStringEncoding ) -> String? { return _ns.stringByAddingPercentEscapesUsingEncoding(encoding) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string made by appending to the `String` a /// string constructed from a given format string and the following /// arguments. @warn_unused_result public func stringByAppendingFormat( format: String, _ arguments: CVarArgType... ) -> String { return _ns.stringByAppendingString( String(format: format, arguments: arguments)) } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message="Use URLByAppendingPathComponent on NSURL instead.") public func stringByAppendingPathComponent(aString: String) -> String { return _ns.stringByAppendingPathComponent(aString) } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message="Use URLByAppendingPathExtension on NSURL instead.") public func stringByAppendingPathExtension(ext: String) -> String? { // FIXME: This method can return nil in practice, for example when self is // an empty string. OTOH, this is not documented, documentation says that // it always returns a string. // // <rdar://problem/17902469> -[NSString stringByAppendingPathExtension] can // return nil return _ns.stringByAppendingPathExtension(ext) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string made by appending a given string to /// the `String`. @warn_unused_result public func stringByAppendingString(aString: String) -> String { return _ns.stringByAppendingString(aString) } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message="Use URLByDeletingLastPathComponent on NSURL instead.") public var stringByDeletingLastPathComponent: String { return _ns.stringByDeletingLastPathComponent } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message="Use URLByDeletingPathExtension on NSURL instead.") public var stringByDeletingPathExtension: String { return _ns.stringByDeletingPathExtension } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message="Use stringByExpandingTildeInPath on NSString instead.") public var stringByExpandingTildeInPath: String { return _ns.stringByExpandingTildeInPath } // - (NSString *) // stringByFoldingWithOptions:(NSStringCompareOptions)options // locale:(NSLocale *)locale /// Returns a string with the given character folding options /// applied. @warn_unused_result public func stringByFoldingWithOptions( options: NSStringCompareOptions, locale: NSLocale? ) -> String { return _ns.stringByFoldingWithOptions(options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. @warn_unused_result public func stringByPaddingToLength( newLength: Int, withString padString: String, startingAtIndex padIndex: Int ) -> String { return _ns.stringByPaddingToLength( newLength, withString: padString, startingAtIndex: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// Returns a new string made from the `String` by replacing /// all percent encoded sequences with the matching UTF-8 /// characters. public var stringByRemovingPercentEncoding: String? { return _ns.stringByRemovingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. @warn_unused_result public func stringByReplacingCharactersInRange( range: Range<Index>, withString replacement: String ) -> String { return _ns.stringByReplacingCharactersInRange( _toNSRange(range), withString: replacement) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(NSStringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the `String` are replaced by /// another given string. @warn_unused_result public func stringByReplacingOccurrencesOfString( target: String, withString replacement: String, options: NSStringCompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { return (searchRange != nil) || (!options.isEmpty) ? _ns.stringByReplacingOccurrencesOfString( target, withString: replacement, options: options, range: _toNSRange(searchRange ?? self.characters.indices) ) : _ns.stringByReplacingOccurrencesOfString(target, withString: replacement) } // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(*, deprecated, message="Use stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func stringByReplacingPercentEscapesUsingEncoding( encoding: NSStringEncoding ) -> String? { return _ns.stringByReplacingPercentEscapesUsingEncoding(encoding) } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message="Use URLByResolvingSymlinksInPath on NSURL instead.") public var stringByResolvingSymlinksInPath: String { return _ns.stringByResolvingSymlinksInPath } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message="Use URLByStandardizingPath on NSURL instead.") public var stringByStandardizingPath: String { return _ns.stringByStandardizingPath } // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. @warn_unused_result public func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String { return _ns.stringByTrimmingCharactersInSet(set) } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in in a given array. @available(*, unavailable, message="map over paths with URLByAppendingPathComponent instead.") public func stringsByAppendingPaths(paths: [String]) -> [String] { return _ns.stringsByAppendingPaths(paths) } // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @warn_unused_result public func substringFromIndex(index: Index) -> String { return _ns.substringFromIndex(index._utf16Index) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @warn_unused_result public func substringToIndex(index: Index) -> String { return _ns.substringToIndex(index._utf16Index) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @warn_unused_result public func substringWithRange(aRange: Range<Index>) -> String { return _ns.substringWithRange(_toNSRange(aRange)) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(OSX 10.11, iOS 9.0, *) public var localizedUppercaseString: String { return _ns.localizedUppercaseString as String } // - (NSString *)uppercaseStringWithLocale:(NSLocale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. @warn_unused_result public func uppercaseStringWithLocale(locale: NSLocale?) -> String { return _ns.uppercaseStringWithLocale(locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func writeToFile( path: String, atomically useAuxiliaryFile:Bool, encoding enc: NSStringEncoding ) throws { try self._ns.writeToFile( path, atomically: useAuxiliaryFile, encoding: enc) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func writeToURL( url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding ) throws { try self._ns.writeToURL( url, atomically: useAuxiliaryFile, encoding: enc) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); /// Perform string transliteration. @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func stringByApplyingTransform( transform: String, reverse: Bool ) -> String? { return _ns.stringByApplyingTransform(transform, reverse: reverse) } //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` iff `other` is non-empty and contained within /// `self` by case-sensitive, non-literal search. /// /// Equivalent to `self.rangeOfString(other) != nil` @warn_unused_result public func containsString(other: String) -> Bool { let r = self.rangeOfString(other) != nil if #available(OSX 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.containsString(other)) } return r } /// Returns `true` iff `other` is non-empty and contained within /// `self` by case-insensitive, non-literal search, taking into /// account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, /// can be achieved by calling /// `rangeOfString(_:options:_,range:_locale:_)`. /// /// Equivalent to /// /// self.rangeOfString( /// other, options: .CaseInsensitiveSearch, /// locale: NSLocale.currentLocale()) != nil @warn_unused_result public func localizedCaseInsensitiveContainsString(other: String) -> Bool { let r = self.rangeOfString( other, options: .CaseInsensitiveSearch, locale: NSLocale.currentLocale() ) != nil if #available(OSX 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.localizedCaseInsensitiveContainsString(other)) } return r } }
apache-2.0
coppercash/Anna
Demos/Easy/Easy/AnalyzableViews.swift
1
607
// // AnalyzableViews.swift // Anna // // Created by William on 2018/6/25. // import UIKit import Anna class AnalyzableTableView : UITableView, Analyzable { lazy var analyzer: Analyzing = { Analyzer.analyzer(with: self) }() deinit { self.analyzer.detach() } } class AnalyzableTableViewCell : UITableViewCell, Analyzable { lazy var analyzer: Analyzing = { Analyzer.analyzer(with: self) }() deinit { self.analyzer.detach() } } class AnalyzableButton : UIButton, Analyzable { lazy var analyzer: Analyzing = { Analyzer.analyzer(with: self) }() deinit { self.analyzer.detach() } }
mit
benlangmuir/swift
test/IDE/range_info_54276140.swift
27
564
// This range info request used to take several minutes to get. Adding a test to make sure we don't lose track of it. // RUN: %target-swift-ide-test -range -pos=4:1 -end-pos=4:12 -source-filename %s | %FileCheck %s -check-prefix=CHECK1 all = "ALL"= "GET"= "POST"= "PUT"= "HEAD"= "DELETE"= "OPTIONS"= "TRACE"= "COPY"= "LOCK"= "MKCOL"= "MOVE"= "PURGE"= "PROPFIND"= "PROPPATCH"= "UNLOCK"= "REPORT"= "MKACTIVITY"= "CHECKOUT"= "MERGE"= "MSEARCH"= "NOTIFY"= "SUBSCRIBE"= "UNSUBSCRIBE"= "PATCH"= "SEARCH"= "CONNECT"= "ERROR"= "UNKNOWN" // CHECK1: <ASTNodes>2</ASTNodes>
apache-2.0
robtimp/xswift
exercises/atbash-cipher/Sources/AtbashCipher/AtbashCipherExample.swift
2
1328
import Foundation struct AtbashCipher { private static func stripWhiteSpaceAndPunctuations(_ input: String) -> String { var returnString = "" input.forEach { if !" ,.".contains(String($0)) { returnString.append($0) } } return returnString } static let cipherDictApply: [Character: Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"] static func encode( _ valueIn: String) -> String { let value = stripWhiteSpaceAndPunctuations(valueIn.lowercased() ) var text2return = "" for each in value { text2return.append(cipherDictApply[each] ?? each ) } return insertSpace5th(text2return) } static func insertSpace5th(_ value: String) -> String { var tempCounter = 0 var tempString: String = "" for each in value { if tempCounter % 5 == 0 && tempCounter != 0 { tempString += " \(each)" } else { tempString += "\(each)" } tempCounter += 1 } return tempString } }
mit
benlangmuir/swift
validation-test/compiler_crashers_fixed/27386-swift-cantype-isobjcexistentialtypeimpl.swift
65
460
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let i{ {class c g{??{ func a{let i>a?{ {func let{{func g{ a=f
apache-2.0
aronse/Hero
Sources/Debug Plugin/HeroDebugView.swift
1
6635
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.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 UIKit #if os(iOS) protocol HeroDebugViewDelegate: class { func onProcessSliderChanged(progress: Float) func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat) func on3D(wants3D: Bool) func onDisplayArcCurve(wantsCurve: Bool) func onDone() } class HeroDebugView: UIView { var backgroundView: UIView! var debugSlider: UISlider! var perspectiveButton: UIButton! var doneButton: UIButton! var arcCurveButton: UIButton? weak var delegate: HeroDebugViewDelegate? var panGR: UIPanGestureRecognizer! var pinchGR: UIPinchGestureRecognizer! var showControls: Bool = false { didSet { layoutSubviews() } } var showOnTop: Bool = false var rotation: CGFloat = π / 6 var scale: CGFloat = 0.6 var translation: CGPoint = .zero var progress: Float { return debugSlider.value } init(initialProcess: Float, showCurveButton: Bool, showOnTop: Bool) { super.init(frame: .zero) self.showOnTop = showOnTop backgroundView = UIView(frame: .zero) backgroundView.backgroundColor = UIColor(white: 1.0, alpha: 0.95) backgroundView.layer.shadowColor = UIColor.darkGray.cgColor backgroundView.layer.shadowOpacity = 0.3 backgroundView.layer.shadowRadius = 5 backgroundView.layer.shadowOffset = CGSize.zero addSubview(backgroundView) doneButton = UIButton(type: .system) doneButton.setTitle("Done", for: .normal) doneButton.addTarget(self, action: #selector(onDone), for: .touchUpInside) backgroundView.addSubview(doneButton) perspectiveButton = UIButton(type: .system) perspectiveButton.setTitle("3D View", for: .normal) perspectiveButton.addTarget(self, action: #selector(onPerspective), for: .touchUpInside) backgroundView.addSubview(perspectiveButton) if showCurveButton { arcCurveButton = UIButton(type: .system) arcCurveButton!.setTitle("Show Arcs", for: .normal) arcCurveButton!.addTarget(self, action: #selector(onDisplayArcCurve), for: .touchUpInside) backgroundView.addSubview(arcCurveButton!) } debugSlider = UISlider(frame: .zero) debugSlider.layer.zPosition = 1000 debugSlider.minimumValue = 0 debugSlider.maximumValue = 1 debugSlider.addTarget(self, action: #selector(onSlide), for: .valueChanged) debugSlider.isUserInteractionEnabled = true debugSlider.value = initialProcess backgroundView.addSubview(debugSlider) panGR = UIPanGestureRecognizer(target: self, action: #selector(pan)) panGR.delegate = self panGR.maximumNumberOfTouches = 1 addGestureRecognizer(panGR) pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(pinch)) pinchGR.delegate = self addGestureRecognizer(pinchGR) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() var backgroundFrame = bounds backgroundFrame.size.height = 72 if showOnTop { backgroundFrame.origin.y = showControls ? 0 : -80 } else { backgroundFrame.origin.y = bounds.maxY - CGFloat(showControls ? 72.0 : -8.0) } backgroundView.frame = backgroundFrame var sliderFrame = bounds.insetBy(dx: 10, dy: 0) sliderFrame.size.height = 44 sliderFrame.origin.y = 28 debugSlider.frame = sliderFrame perspectiveButton.sizeToFit() perspectiveButton.frame.origin = CGPoint(x: bounds.maxX - perspectiveButton.bounds.width - 10, y: 4) doneButton.sizeToFit() doneButton.frame.origin = CGPoint(x: 10, y: 4) arcCurveButton?.sizeToFit() arcCurveButton?.center = CGPoint(x: center.x, y: doneButton.center.y) } var startRotation: CGFloat = 0 @objc public func pan() { if panGR.state == .began { startRotation = rotation } rotation = startRotation + panGR.translation(in: nil).x / 150 if rotation > π { rotation -= 2 * π } else if rotation < -π { rotation += 2 * π } delegate?.onPerspectiveChanged(translation: translation, rotation: rotation, scale: scale) } var startLocation: CGPoint = .zero var startTranslation: CGPoint = .zero var startScale: CGFloat = 1 @objc public func pinch() { switch pinchGR.state { case .began: startLocation = pinchGR.location(in: nil) startTranslation = translation startScale = scale fallthrough case .changed: if pinchGR.numberOfTouches >= 2 { scale = min(1, max(0.2, startScale * pinchGR.scale)) translation = startTranslation + pinchGR.location(in: nil) - startLocation delegate?.onPerspectiveChanged(translation: translation, rotation: rotation, scale: scale) } default: break } } @objc public func onDone() { delegate?.onDone() } @objc public func onPerspective() { perspectiveButton.isSelected = !perspectiveButton.isSelected delegate?.on3D(wants3D: perspectiveButton.isSelected) } @objc public func onDisplayArcCurve() { arcCurveButton!.isSelected = !arcCurveButton!.isSelected delegate?.onDisplayArcCurve(wantsCurve: arcCurveButton!.isSelected) } @objc public func onSlide() { delegate?.onProcessSliderChanged(progress: debugSlider.value) } } extension HeroDebugView: UIGestureRecognizerDelegate { public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return perspectiveButton.isSelected } } #endif
mit
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Quick/Sources/Quick/Filter.swift
428
954
import Foundation /** A mapping of string keys to booleans that can be used to filter examples or example groups. For example, a "focused" example would have the flags [Focused: true]. */ public typealias FilterFlags = [String: Bool] /** A namespace for filter flag keys, defined primarily to make the keys available in Objective-C. */ final public class Filter: NSObject { /** Example and example groups with [Focused: true] are included in test runs, excluding all other examples without this flag. Use this to only run one or two tests that you're currently focusing on. */ public class var focused: String { return "focused" } /** Example and example groups with [Pending: true] are excluded from test runs. Use this to temporarily suspend examples that you know do not pass yet. */ public class var pending: String { return "pending" } }
mit
scottkawai/sendgrid-swift
Sources/SendGrid/API/V3/Mail/Send/Email.swift
1
36656
import Foundation /// The `Email` class is used to make the Mail Send API call. The class allows /// you to configure many different aspects of the email. /// /// ## Content /// /// To specify the content of an email, use the `Content` class. In general, an /// email will have plain text and/or HTML text content, however you can specify /// other types of content, such as an ICS calendar invite. Following RFC 1341, /// section 7.2, if either HTML or plain text content are to be sent in your /// email: the plain text content needs to be first, followed by the HTML /// content, followed by any other content. /// /// ## Personalizations /// /// The new V3 endpoint introduces the idea of "personalizations." When using /// the API, you define a set of global characteristics for the email, and then /// also define seperate personalizations, which contain recipient-specific /// information for the email. Since personalizations contain the recipients of /// the email, each request must contain at least 1 personalization. /// /// ```swift /// // Send a basic example /// let personalization = Personalization(recipients: "test@example.com") /// let plainText = Content(contentType: ContentType.plainText, value: "Hello World") /// let htmlText = Content(contentType: ContentType.htmlText, value: "<h1>Hello World</h1>") /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: [plainText, htmlText], /// subject: "Hello World" /// ) /// do { /// try Session.shared.send(request: email) /// } catch { /// print(error) /// } /// ``` /// /// An `Email` instance can have up to 1000 `Personalization` instances. A /// `Personalization` can be thought of an individual email. It can contain /// several `to` addresses, along with `cc` and `bcc` addresses. Keep in mind /// that if you put two addresses in a single `Personalization` instance, each /// recipient will be able to see each other's email address. If you want to /// send to several recipients where each recipient only sees their own address, /// you'll want to create a seperate `Personalization` instance for each /// recipient. /// /// The `Personalization` class also allows personalizing certain email /// attributes, including: /// /// - Subject /// - Headers /// - Substitution tags /// - [Custom arguments](https://sendgrid.com/docs/API_Reference/SMTP_API/unique_arguments.html) /// - Scheduled sends /// /// If a `Personalization` instance contains an email attribute that is also /// defined globally in the request (such as the subject), the `Personalization` /// instance's value takes priority. /// /// Here is an advanced example of using personalizations: /// /// ```swift /// // Send an advanced example /// let recipients = [ /// Address(email: "jose@example.none", name: "Jose"), /// Address(email: "isaac@example.none", name: "Isaac"), /// Address(email: "tim@example.none", name: "Tim") /// ] /// let personalizations = recipients.map { (recipient) -> Personalization in /// let name = recipient.name ?? "there" /// return Personalization( /// to: [recipient], /// cc: nil, /// bcc: [Address(email: "bcc@example.none")], /// subject: "Hello \(name)!", /// headers: ["X-Campaign":"12345"], /// substitutions: ["%name%":name], /// customArguments: ["campaign_id":"12345"] /// ) /// } /// let contents = Content.emailBody( /// plain: "Hello %name%,\n\nHow are you?\n\nBest,\nSender", /// html: "<p>Hello %name%,</p><p>How are you?</p><p>Best,<br>Sender</p>" /// ) /// let email = Email( /// personalizations: personalizations, /// from: Address(email: "sender@example.none"), /// content: contents, /// subject: nil /// ) /// email.parameters?.headers = [ /// "X-Campaign": "12345" /// ] /// email.parameters?.customArguments = [ /// "campaign_id": "12345" /// ] /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// You'll notice in the example above, the global email defines custom headers /// and custom arguments. In addition, each personalization defines some headers /// and custom arguments. For the resulting email, the headers and custom /// arguments will be merged together. In the event of a conflict, the /// personalization's values will be used. /// /// ## Attachments /// /// The `Attachment` class allows you to easily add attachments to an email. All /// you need is to convert your desired attachment into `Data` and initialize /// it like so: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// do { /// if let path = Bundle.main.url(forResource: "proposal", withExtension: "pdf") { /// let attachment = Attachment( /// filename: "proposal.pdf", /// content: try Data(contentsOf: path), /// disposition: .attachment, /// type: .pdf, /// contentID: nil /// ) /// email.parameters?.attachments = [attachment] /// } /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// You can also use attachments as inline images by setting the `disposition` /// property to `.inline` and setting the `cid` property. You can then /// reference that unique CID in your HTML like so: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<img src=\"cid:main_logo_12345\" /><h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// do { /// let filename = NSImage.Name("logo.png") /// if let path = Bundle.main.urlForImageResource(filename) { /// let attachment = Attachment( /// filename: "logo.png", /// content: try Data(contentsOf: path), /// disposition: .inline, /// type: .png, /// contentID: "main_logo_12345" /// ) /// email.parameters?.attachments = [attachment] /// } /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## Mail and Tracking Settings /// /// There are various classes available that you can use to modify the /// [mail](https://sendgrid.com/docs/User_Guide/Settings/mail.html) and /// [tracking](https://sendgrid.com/docs/User_Guide/Settings/tracking.html) /// settings for a specific email. /// /// **MAIL SETTINGS** /// /// The following mail setting classes are available: /// /// - `BCCSetting` - This allows you to have a blind carbon copy automatically /// sent to the specified email address for every email that is sent. /// - `BypassListManagement` - Allows you to bypass all unsubscribe groups and /// suppressions to ensure that the email is delivered to every single /// recipient. This should only be used in emergencies when it is absolutely /// necessary that every recipient receives your email. Ex: outage emails, or /// forgot password emails. /// - `Footer` - The default footer that you would like appended to the bottom /// of every email. /// - `SandboxMode` - This allows you to send a test email to ensure that your /// request body is valid and formatted correctly. For more information, please /// see the [Classroom](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/sandbox_mode.html). /// - `SpamChecker` - This allows you to test the content of your email for /// spam. /// /// **TRACKING SETTINGS** /// /// The following tracking setting classes are available: /// /// - `ClickTracking` - Allows you to track whether a recipient clicked a link /// in your email. /// - `GoogleAnalytics` - Allows you to enable tracking provided by Google /// Analytics. /// - `OpenTracking` - Allows you to track whether the email was opened or not, /// but including a single pixel image in the body of the content. When the /// pixel is loaded, we can log that the email was opened. /// - `SubscriptionTracking` - Allows you to insert a subscription management /// link at the bottom of the text and html bodies of your email. If you would /// like to specify the location of the link within your email, you may specify /// a substitution tag. /// /// **EXAMPLE** /// /// Each setting has its own properties that can be configured, but here's a /// basic example: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// email.parameters?.mailSettings.footer = Footer( /// text: "Copyright 2016 MyCompany", /// html: "<p><small>Copyright 2016 MyCompany</small></p>" /// ) /// email.parameters?.trackingSettings.clickTracking = ClickTracking(section: .htmlBody) /// email.parameters?.trackingSettings.openTracking = OpenTracking(location: .off) /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## Unsubscribe Groups (ASM) /// /// If you use SendGrid's /// [unsubscribe groups](https://sendgrid.com/docs/User_Guide/Suppressions/advanced_suppression_manager.html) /// feature, you can specify which unsubscribe group to send an email under like /// so: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// /// Assuming your unsubscribe group has an ID of 4815… /// email.parameters?.asm = ASM(groupID: 4815) /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// You can also specify which unsubscribe groups should be shown on the /// subscription management page for this email: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// /// Assuming your unsubscribe group has an ID of 4815… /// email.parameters?.asm = ASM(groupID: 4815, groupsToDisplay: [16,23,42]) /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## IP Pools /// /// If you're on a pro plan or higher, and have set up /// [IP Pools](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_pools.html) /// on your account, you can specify a specific pool to send an email over like /// so: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// /// Assuming you have an IP pool called "transactional" on your account… /// email.parameters?.ipPoolName = "transactional" /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## Scheduled Sends /// /// If you don't want the email to be sent right away, but rather at some point /// in the future, you can use the `sendAt` property. **NOTE**: You cannot /// schedule an email further than 72 hours in the future. You can also assign /// an optional, unique `batchID` to the email so that you can /// [cancel via the API](https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html) /// in the future if needed. /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// // Schedule the email for 24 hours from now. /// email.parameters?.sendAt = Date(timeIntervalSinceNow: 24 * 60 * 60) /// /// // This part is optional, but if you [generated a batch ID](https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html) /// // and specify it here, you'll have the ability to cancel this send via the API if needed. /// email.parameters?.batchID = "76A8C7A6-B435-47F5-AB13-15F06BA2E3WD" /// /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// In the above example, we've set the `sendAt` property on the global email, /// which means every personalization will be scheduled for that time. You can /// also set the `sendAt` property on a `Personalization` if you want each one /// to be set to a different time, or only have certain ones scheduled: /// /// ```swift /// let recipientInfo: [String : Date?] = [ /// "jose@example.none": Date(timeIntervalSinceNow: 4 * 60 * 60), /// "isaac@example.none": nil, /// "tim@example.none": Date(timeIntervalSinceNow: 12 * 60 * 60) /// ] /// let personalizations = recipientInfo.map { (recipient, date) -> Personalization in /// let personalization = Personalization(recipients: recipient) /// personalization.sendAt = date /// return personalization /// } /// let contents = Content.emailBody( /// plain: "Hello there,\n\nHow are you?\n\nBest,\nSender", /// html: "<p>Hello there,</p><p>How are you?</p><p>Best,<br>Sender</p>" /// ) /// let email = Email( /// personalizations: personalizations, /// from: "sender@example.none", /// content: contents, /// subject: nil /// ) /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## Categories /// /// You can assign categories to an email which will show up in your SendGrid /// stats, Email Activity, and event webhook. You can not have more than 10 /// categories per email. /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// email.parameters?.categories = ["Foo", "Bar"] /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` /// /// ## Sections /// /// Sections allow you to define large blocks of content that can be inserted /// into your emails using substitution tags. An example of this might look like /// the following: /// /// ```swift /// let bob = Personalization(recipients: "bob@example.com") /// bob.substitutions = [ /// ":salutation": ":male", /// ":name": "Bob", /// ":event_details": ":event2", /// ":event_date": "Feb 14" /// ] /// /// let alice = Personalization(recipients: "alice@example.com") /// alice.substitutions = [ /// ":salutation": ":female", /// ":name": "Alice", /// ":event_details": ":event1", /// ":event_date": "Jan 1" /// ] /// /// let casey = Personalization(recipients: "casey@example.com") /// casey.substitutions = [ /// ":salutation": ":neutral", /// ":name": "Casey", /// ":event_details": ":event1", /// ":event_date": "Aug 11" /// ] /// /// let personalization = [ /// bob, /// alice, /// casey /// ] /// let plainText = ":salutation,\n\nPlease join us for the :event_details." /// let htmlText = "<p>:salutation,</p><p>Please join us for the :event_details.</p>" /// let content = Content.emailBody(plain: plainText, html: htmlText) /// let email = Email( /// personalizations: personalization, /// from: "from@example.com", /// content: content /// ) /// email.parameters?.subject = "Hello World" /// email.parameters?.sections = [ /// ":male": "Mr. :name", /// ":female": "Ms. :name", /// ":neutral": ":name", /// ":event1": "New User Event on :event_date", /// ":event2": "Veteran User Appreciation on :event_date" /// ] /// ``` /// /// ## Template Engine /// /// If you use SendGrid's /// [Template Engine](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html), /// you can specify a template to apply to an email like so: /// /// ```swift /// let personalization = Personalization(recipients: "test@example.com") /// let contents = Content.emailBody( /// plain: "Hello World", /// html: "<h1>Hello World</h1>" /// ) /// let email = Email( /// personalizations: [personalization], /// from: "foo@bar.com", /// content: contents, /// subject: "Hello World" /// ) /// /// Assuming you have a template with ID "52523e14-7e47-45ed-ab32-0db344d8cf9z" on your account… /// email.parameters?.templateID = "52523e14-7e47-45ed-ab32-0db344d8cf9z" /// do { /// try Session.shared.send(request: email) { (result) in /// switch result { /// case .success(let response): /// print(response.statusCode) /// case .failure(let err): /// print(err) /// } /// } /// } catch { /// print(error) /// } /// ``` public class Email: Request<Email.Parameters> { // MARK: - Properties /// A `Bool` indicating if the request supports the "On-behalf-of" header. public override var supportsImpersonation: Bool { false } // MARK: - Initialization /// Initializes the email request with a list of personalizations, a from /// address, content, and a subject. /// /// - Parameters: /// - personalizations: An array of personalization instances. /// - from: A from address to use in the email. /// - content: An array of content instances to use in the /// body. /// - subject: An optional global subject line. public init(personalizations: [Personalization], from: Address, content: [Content], subject: String? = nil) { let params = Email.Parameters(personalizations: personalizations, from: from, content: content, subject: subject) let dateEncoder = JSONEncoder.DateEncodingStrategy.custom { date, encoder in var container = encoder.singleValueContainer() try container.encode(Int(date.timeIntervalSince1970)) } super.init(method: .POST, path: "/v3/mail/send", parameters: params, encodingStrategy: EncodingStrategy(dates: dateEncoder)) } /// Initializes the email request with a list of personalizations, a from /// address, template ID, and a subject. /// /// - Parameters: /// - personalizations: An array of personalization instances. /// - from: A from address to use in the email. /// - templateID: The ID of a template to use. /// - subject: An optional global subject line. public init(personalizations: [Personalization], from: Address, templateID: String, subject: String? = nil) { let params = Email.Parameters(personalizations: personalizations, from: from, templateID: templateID, subject: subject) let dateEncoder = JSONEncoder.DateEncodingStrategy.custom { date, encoder in var container = encoder.singleValueContainer() try container.encode(Int(date.timeIntervalSince1970)) } super.init(method: .POST, path: "/v3/mail/send", parameters: params, encodingStrategy: EncodingStrategy(dates: dateEncoder)) } // MARK: - Methods /// Before a `Session` instance makes an API call, it will call this method /// to double check that the auth method it's about to use is supported by /// the endpoint. In general, this will always return `true`, however some /// endpoints, such as the mail send endpoint, only support API keys. /// /// - Parameter auth: The `Authentication` instance that's about to be /// used. /// - Returns: A `Bool` indicating if the authentication method is /// supported. public override func supports(auth: Authentication) -> Bool { // The mail send endpoint only supports API Keys. auth.prefix == "Bearer" } /// :nodoc: public override func validate() throws { try super.validate() try self.parameters?.validate() } } public extension Email /* Parameters Struct */ { /// The `Email.Parameters` struct serves as the parameters sent on the email /// send API. struct Parameters: Encodable, EmailHeaderRepresentable, Scheduling, Validatable { // MARK: - Properties /// An array of personalization instances representing the various /// recipients of the email. public var personalizations: [Personalization] /// The content sections of the email. public var content: [Content]? /// The subject of the email. If the personalizations in the email contain /// subjects, those will override this subject. public var subject: String? /// The sending address on the email. public var from: Address /// The reply to address on the email. public var replyTo: Address? /// Attachments to add to the email. public var attachments: [Attachment]? /// The ID of a template from the Template Engine to use with the email. public var templateID: String? /// Additional headers that should be added to the email. public var headers: [String: String]? /// Categories to associate with the email. public var categories: [String]? /// A dictionary of key/value pairs that define large blocks of content that /// can be inserted into your emails using substitution tags. An example of /// this might look like the following: /// /// ```swift /// let bob = Personalization(recipients: "bob@example.com") /// bob.substitutions = [ /// ":salutation": ":male", /// ":name": "Bob", /// ":event_details": ":event2", /// ":event_date": "Feb 14" /// ] /// /// let alice = Personalization(recipients: "alice@example.com") /// alice.substitutions = [ /// ":salutation": ":female", /// ":name": "Alice", /// ":event_details": ":event1", /// ":event_date": "Jan 1" /// ] /// /// let casey = Personalization(recipients: "casey@example.com") /// casey.substitutions = [ /// ":salutation": ":neutral", /// ":name": "Casey", /// ":event_details": ":event1", /// ":event_date": "Aug 11" /// ] /// /// let personalization = [ /// bob, /// alice, /// casey /// ] /// let plainText = ":salutation,\n\nPlease join us for the :event_details." /// let htmlText = "<p>:salutation,</p><p>Please join us for the :event_details.</p>" /// let content = Content.emailBody(plain: plainText, html: htmlText) /// let email = Email( /// personalizations: personalization, /// from: "from@example.com", /// content: content /// ) /// email.parameters?.subject = "Hello World" /// email.parameters?.sections = [ /// ":male": "Mr. :name", /// ":female": "Ms. :name", /// ":neutral": ":name", /// ":event1": "New User Event on :event_date", /// ":event2": "Veteran User Appreciation on :event_date" /// ] /// ``` public var sections: [String: String]? /// A set of custom arguments to add to the email. The keys of the /// dictionary should be the names of the custom arguments, while the values /// should represent the value of each custom argument. If personalizations /// in the email also contain custom arguments, they will be merged with /// these custom arguments, taking a preference to the personalization's /// custom arguments in the case of a conflict. public var customArguments: [String: String]? /// An `ASM` instance representing the unsubscribe group settings to apply /// to the email. public var asm: ASM? /// An optional time to send the email at. public var sendAt: Date? /// This ID represents a batch of emails (AKA multiple sends of the same /// email) to be associated to each other for scheduling. Including a /// `batch_id` in your request allows you to include this email in that /// batch, and also enables you to cancel or pause the delivery of that /// entire batch. For more information, please read about [Cancel Scheduled /// Sends](https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html). public var batchID: String? /// The IP Pool that you would like to send this email from. See the [docs /// page](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_pools.html#-POST) /// for more information about creating IP Pools. public var ipPoolName: String? /// An optional array of mail settings to configure the email with. public var mailSettings = MailSettings() /// An optional array of tracking settings to configure the email with. public var trackingSettings = TrackingSettings() // MARK: - Initialization /// Initializes the parameters with a list of personalizations, a from /// address, content, and a subject. /// /// - Parameters: /// - personalizations: An array of personalization instances. /// - from: A from address to use in the email. /// - content: An array of content instances to use in the /// body. /// - subject: An optional global subject line. public init(personalizations: [Personalization], from: Address, content: [Content]? = nil, templateID: String? = nil, subject: String? = nil) { self.personalizations = personalizations self.from = from self.content = content self.subject = subject self.templateID = templateID } // MARK: - Methods /// :nodoc: public func validate() throws { // Check for correct amount of personalizations guard 1...Constants.PersonalizationLimit ~= self.personalizations.count else { throw Exception.Mail.invalidNumberOfPersonalizations } // Check for content if self.templateID == nil { guard let bodies = self.content, bodies.count > 0 else { throw Exception.Mail.missingContent } // Check for content order let (isOrdered, _) = try bodies.reduce((true, 0)) { (running, item) -> (Bool, Int) in try item.validate() let thisIsOrdered = running.0 && (item.type.index >= running.1) return (thisIsOrdered, item.type.index) } guard isOrdered else { throw Exception.Mail.invalidContentOrder } } // Check for total number of recipients let totalRecipients: [String] = try self.personalizations.reduce([String]()) { (list, per) -> [String] in try per.validate() func reduce(addresses: [Address]?) throws -> [String] { guard let array = addresses else { return [] } return try array.reduce([String](), { (running, address) -> [String] in if list.contains(address.email.lowercased()) { throw Exception.Mail.duplicateRecipient(address.email.lowercased()) } return running + [address.email.lowercased()] }) } let tos = try reduce(addresses: per.to) let ccs = try reduce(addresses: per.cc) let bcc = try reduce(addresses: per.bcc) return list + tos + ccs + bcc } guard totalRecipients.count <= Constants.RecipientLimit else { throw Exception.Mail.tooManyRecipients } // Check for subject present if (self.subject?.count ?? 0) == 0, self.templateID == nil { let subjectPresent = self.personalizations.reduce(true) { (hasSubject, person) -> Bool in hasSubject && ((person.subject?.count ?? 0) > 0) } guard subjectPresent else { throw Exception.Mail.missingSubject } } // Validate from address try self.from.validate() // Validate reply-to address try self.replyTo?.validate() // Validate the headers try self.validateHeaders() // Validate the categories if let cats = self.categories { guard cats.count <= Constants.Categories.TotalLimit else { throw Exception.Mail.tooManyCategories } _ = try cats.reduce([String](), { (list, cat) -> [String] in guard cat.count <= Constants.Categories.CharacterLimit else { throw Exception.Mail.categoryTooLong(cat) } let lower = cat.lowercased() if list.contains(lower) { throw Exception.Mail.duplicateCategory(lower) } return list + [lower] }) } // Validate the custom arguments. try self.personalizations.forEach({ p in var merged = self.customArguments ?? [:] if let list = p.customArguments { list.forEach { merged[$0.key] = $0.value } } let jsonData = try JSONEncoder().encode(merged) let bytes = jsonData.count guard bytes <= Constants.CustomArguments.MaximumBytes else { let jsonString = String(data: jsonData, encoding: .utf8) throw Exception.Mail.tooManyCustomArguments(bytes, jsonString) } }) // Validate ASM try self.asm?.validate() // Validate the send at date. try self.validateSendAt() // Validate the mail settings. try self.mailSettings.validate() // validate the tracking settings. try self.trackingSettings.validate() } /// :nodoc: public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.personalizations, forKey: .personalizations) try container.encode(self.from, forKey: .from) try container.encode(self.content, forKey: .content) try container.encodeIfPresent(self.subject, forKey: .subject) try container.encodeIfPresent(self.replyTo, forKey: .replyTo) try container.encodeIfPresent(self.attachments, forKey: .attachments) try container.encodeIfPresent(self.templateID, forKey: .templateID) try container.encodeIfPresent(self.sections, forKey: .sections) try container.encodeIfPresent(self.headers, forKey: .headers) try container.encodeIfPresent(self.categories, forKey: .categories) try container.encodeIfPresent(self.customArguments, forKey: .customArguments) try container.encodeIfPresent(self.asm, forKey: .asm) try container.encodeIfPresent(self.sendAt, forKey: .sendAt) try container.encodeIfPresent(self.batchID, forKey: .batchID) try container.encodeIfPresent(self.ipPoolName, forKey: .ipPoolName) if self.mailSettings.hasSettings { try container.encode(self.mailSettings, forKey: .mailSettings) } if self.trackingSettings.hasSettings { try container.encode(self.trackingSettings, forKey: .trackingSettings) } } /// :nodoc: public enum CodingKeys: String, CodingKey { case asm case attachments case batchID = "batch_id" case categories case content case customArguments = "custom_args" case from case headers case ipPoolName = "ip_pool_name" case mailSettings = "mail_settings" case personalizations case replyTo = "reply_to" case sections case sendAt = "send_at" case subject case templateID = "template_id" case trackingSettings = "tracking_settings" } } }
mit
miller-ms/ViewAnimator
ViewAnimator/TransitionController.swift
1
5849
// // TransitionController.swift // ViewAnimator // // Created by William Miller DBA Miller Mobilesoft on 5/13/17. // // This application is intended to be a developer tool for evaluating the // options for creating an animation or transition using the UIView static // methods UIView.animate and UIView.transition. // Copyright © 2017 William Miller DBA Miller Mobilesoft // // 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/>. // // If you would like to reach the developer you may email me at // support@millermobilesoft.com or visit my website at // http://millermobilesoft.com // import UIKit class TransitionController: AnimatorController { enum ParamCellIdentifiers:Int { case durationCell = 0 case optionsCell case count } enum TransitionCellIdentifiers:Int { case transitionCell = 0 case count } enum SectionIdentifiers:Int { case transitionSection = 0 case parameterSection case count } var duration = Double(1.0) var options = OptionsModel(options: [UIViewAnimationOptions.transitionCrossDissolve]) override func viewDidLoad() { super.viewDidLoad() cellIdentifiers = [ "TransitionCell", "DurationCellId", "OptionsCellId"] sectionHeaderTitles = ["Transition", "Parameters"] identifierBaseIdx = [0, TransitionCellIdentifiers.count.rawValue] sectionCount = [TransitionCellIdentifiers.count.rawValue, ParamCellIdentifiers.count.rawValue] rowHeights = [CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)] // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func transferParametersFromCells() { let parameterPath = IndexPath(row:ParamCellIdentifiers.durationCell.rawValue, section: SectionIdentifiers.parameterSection.rawValue) let cell = tableView.cellForRow(at: parameterPath) as? FloatValueCell if cell != nil { duration = Double(cell!.value) } } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let propertySection = SectionIdentifiers(rawValue: indexPath.section) else { fatalError("invalid section in properties controller") } switch propertySection { case .parameterSection: guard let paramCellId = ParamCellIdentifiers(rawValue: indexPath.row) else { fatalError("Invalid row in parameter section") } if paramCellId == .durationCell { let paramCell = cell as! FloatValueCell paramCell.value = Float(duration) } default: break } } override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let propertySection = SectionIdentifiers(rawValue: indexPath.section) else { fatalError("invalid section in properties controller") } switch propertySection { case .parameterSection: guard let paramCellId = ParamCellIdentifiers(rawValue: indexPath.row) else { fatalError("Invalid row in parameter section") } if paramCellId == .durationCell { let paramCell = cell as! FloatValueCell duration = Double(paramCell.value) } default: break } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let optionsController = segue.destination as! TransitionOptionsController optionsController.options = options } @IBAction func durationChanged(_ sender: UISlider) { let cell = sender.superview!.superview as! FloatValueCell duration = Double(cell.value) } @IBAction func executeTransition(_ sender: UIButton) { let cell = sender.superview?.superview as! TransitionCell var hex = String(format: "%x", options.animationOptions.rawValue) print("Options for animate are \(hex)") hex = String(format: "%x", UIViewAnimationOptions.transitionCrossDissolve.rawValue) print("crosse dissolve value is \(hex)") transferParametersFromCells() cell.executeTransition(withDuration: duration, animationOptions: options.animationOptions) } }
gpl-3.0
gregomni/swift
test/SymbolGraph/ClangImporter/Submodules.swift
9
908
// RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/EmitWhileBuilding/EmitWhileBuilding.framework %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -emit-module-path %t/EmitWhileBuilding.framework/Modules/EmitWhileBuilding.swiftmodule/%target-swiftmodule-name -import-underlying-module -F %t -module-name EmitWhileBuilding -disable-objc-attr-requires-foundation-module %S/EmitWhileBuilding.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/Submodules -emit-module-path %t/Submodules.swiftmodule -enable-objc-interop -module-name Submodules -F %t %s -emit-symbol-graph -emit-symbol-graph-dir %t // REQUIRES: objc_interop // Don't crash when a module declared an `@_exported import` for a Clang non-top-level module. @_exported import Mixed @_exported import Mixed.Submodule @_exported import EmitWhileBuilding public func someFunc() {}
apache-2.0
dracrowa-kaz/DeveloperNews
DeveloperNews/APIController.swift
1
1739
// // APIController.swift // DeveloperNews // // Created by 佐藤和希 on 1/5/17. // Copyright © 2017 kaz. All rights reserved. // import Foundation import Alamofire import Alamofire_Synchronous import SwiftyJSON class APIController { func getJSON(url:String)->JSON?{ let response = Alamofire.request(url, method: .get).responseJSON(options: .allowFragments) if let json = response.result.value { //return JSON(json) } return JSON(feedJson) } } var feeds: [Dictionary<String, String>] = [ [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/top/rss", "title": "Top" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/ruby/rss", "title": "Ruby" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/ios/rss", "title": "iOS" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/android/rss", "title": "Android" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/infrastructure/rss", "title": "Infrastructure" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/javascript/rss", "title": "Javascript" ], [ "link": "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://menthas.com/programming/rss", "title": "Programming" ] ]
mit
hanhailong/practice-swift
Views/ActivityViewController/Custom Activity/Custom Activity/ViewController.swift
2
681
// // ViewController.swift // Custom Activity // // Created by Domenico Solazzo on 05/05/15. // License MIT // import UIKit class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let itemsToShare = [ "Item 1" as NSString, "Item 2" as NSString, "Item 3" as NSString ] let activityController = UIActivityViewController( activityItems: itemsToShare, applicationActivities:[StringReverserActivity()]) presentViewController(activityController, animated: true, completion: nil) } }
mit
qaisjp/mta-luac-osx
MTA Lua Compiler/AppDelegate.swift
1
630
// // AppDelegate.swift // MTA Lua Compiler // // Created by Qais Patankar on 02/11/2014. // Copyright (c) 2014 qaisjp. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool { return true } }
apache-2.0
nunofgs/SwiftClient
SwiftClient/FormData.swift
2
3019
// // FormData.swift // SwiftClient // // Created by Adam Nalisnick on 11/4/14. // Copyright (c) 2014 Adam Nalisnick. All rights reserved. // import Foundation import MobileCoreServices internal class FormData { private let boundary = "BOUNDARY-" + NSUUID().UUIDString; private let nl = stringToData("\r\n"); internal init(){} private var fields:[(name:String, value:String)] = Array(); private var files:[(name:String, data:NSData, filename:String, mimeType:String)] = Array(); internal func append(name:String, _ value:String){ fields += [(name: name, value: value)] } internal func append(name:String, _ data:NSData, _ filename:String, _ mimeType:String? = nil){ let type = mimeType ?? determineMimeType(filename) files += [(name: name, data: data, filename: filename, mimeType: type)] } private func determineMimeType(filename:String) -> String { let type = filename.pathExtension if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, type as NSString, nil)?.takeRetainedValue() { if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { return mimetype as String } } return "application/octet-stream"; } internal func getContentType() -> String { return "multipart/form-data; boundary=\(boundary)"; } internal func getBody() -> NSData? { if(fields.count > 0 || files.count > 0){ var body = NSMutableData(); for (field) in fields { appendField(body, field.name, field.value) } for (file) in files { appendFile(body, file.name, file.data, file.filename, file.mimeType); } body.appendData(stringToData("--\(boundary)--")); body.appendData(nl); return body; } return nil } private func appendFile(body:NSMutableData, _ name:String, _ data:NSData, _ filename:String, _ mimeType:String) { body.appendData(stringToData("--\(boundary)")) body.appendData(nl) body.appendData(stringToData("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(filename)\"")) body.appendData(nl); body.appendData(stringToData("Content-Type: \(mimeType)")); body.appendData(nl); body.appendData(nl); body.appendData(data); body.appendData(nl); } private func appendField(body:NSMutableData, _ name:String, _ value:String) { body.appendData(stringToData("--\(boundary)")) body.appendData(nl) body.appendData(stringToData("Content-Disposition: form-data; name=\"\(name)\"")) body.appendData(nl); body.appendData(nl); body.appendData(stringToData(value)) body.appendData(nl); } }
mit
FandyLiu/FDDemoCollection
Swift/Contact/Contact/ContactsManager.swift
1
4752
// // ContactsManager.swift // Contact // // Created by QianTuFD on 2017/5/8. // Copyright © 2017年 fandy. All rights reserved. // import UIKit import Contacts import AddressBook // Errors thrown from here are not handled because the enclosing catch is not exhaustive typealias ContactsIndexTitles = ([String], [String: [PersonPhoneModel]]) class ContactsManager: NSObject { class func getContactsList() -> [PersonPhoneModel] { var contactsList = [PersonPhoneModel]() if #available(iOS 9.0, *) { let store = CNContactStore() let keys: [CNKeyDescriptor] = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey] as [CNKeyDescriptor] let request = CNContactFetchRequest(keysToFetch: keys) do { try store.enumerateContacts(with: request) { (contact, _) in let fullName = (contact.familyName + contact.givenName).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let phoneNumbers = contact.phoneNumbers for labeledValue in phoneNumbers { let phoneNumber = labeledValue.value.stringValue.phoneNumberFormat() let phoneLabel = labeledValue.label ?? "" // print(fullName + phoneNumber + phoneLabel) let model = PersonPhoneModel(fullName: fullName, phoneNumber: phoneNumber, phoneLabel: phoneLabel) contactsList.append(model) } } } catch { assertionFailure("请求 contacts 失败") } } else { let addressBook = ABAddressBookCreate().takeRetainedValue() let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as [ABRecord] for person in allPeople { var firstName = "" var lastName = "" if let firstNameUnmanaged = ABRecordCopyValue(person, kABPersonLastNameProperty) { firstName = firstNameUnmanaged.takeRetainedValue() as? String ?? "" } if let lastNameUnmanaged = ABRecordCopyValue(person, kABPersonFirstNameProperty) { lastName = lastNameUnmanaged.takeRetainedValue() as? String ?? "" } let fullName = (firstName + lastName).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let phones = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValue for i in 0..<ABMultiValueGetCount(phones) { let phoneNumber = (ABMultiValueCopyValueAtIndex(phones, i).takeRetainedValue() as? String ?? "").phoneNumberFormat() let phoneLabel = ABMultiValueCopyLabelAtIndex(phones, i).takeRetainedValue() as String // print(fullName + phoneNumber + phoneLabel) let model = PersonPhoneModel(fullName: fullName, phoneNumber: phoneNumber, phoneLabel: phoneLabel) contactsList.append(model) } } } return contactsList } class func format(contantsList : [PersonPhoneModel]) -> ContactsIndexTitles { // let collection = UILocalizedIndexedCollation.current() // let indexArray = Array(collection.sectionTitles) if contantsList.count < 1 { return ([String](), [String: [PersonPhoneModel]]()) } let indexs = contantsList.map { $0.firstCapital } let sortIndexs = Array(Set(indexs)).sorted(by: <) let sortList = contantsList.sorted(by: {$0.pinYinName < $1.pinYinName}) var dict = [String: [PersonPhoneModel]]() for index in sortIndexs { var arr = [PersonPhoneModel]() arr = sortList.filter{ $0.firstCapital == index} dict[index] = arr } return (sortIndexs, dict) } } struct PersonPhoneModel { init(fullName: String, phoneNumber: String, phoneLabel: String) { self.fullName = fullName self.phoneNumber = phoneNumber self.phoneLabel = phoneLabel self.pinYinName = fullName.pinYin().uppercased() self.firstCapital = String(describing: pinYinName.characters.first ?? "#") } let fullName: String let phoneNumber: String let phoneLabel: String let pinYinName: String var firstCapital: String }
mit
machelix/COBezierTableView
COBezierTableViewDemo/COBezierTableViewDemoTests/COBezierTableViewDemoTests.swift
1
4866
// // COBezierTableViewDemoTests.swift // COBezierTableViewDemoTests // // Created by Knut Inge Grosland on 2015-03-20. // Copyright (c) 2015 Cocmoc. All rights reserved. // import UIKit import XCTest class COBezierTableViewDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } } //import COBezierTableView // //class COBezierDataSourceTest : COBezierTableViewDataSource { // // func bezierTableView(bezierTableView: COBezierTableView, sizeForCellAtIndex index: Int) -> CGSize { // return CGSizeMake(100, 50) // } // // func bezierTableViewCellPadding(bezierTableView: COBezierTableView) -> CGFloat { // return 50.0 // } // // func bezierTableView(bezierTableView: COBezierTableView, cellForRowAtIndex index: Int) -> COBezierTableViewCell { // var cell = bezierTableView.dequeueReusableCellWithIdentifer("cell", forIndex: index) as? MyBezierTableViewCell // cell?.backgroundColor = UIColor.redColor() // // return cell! // // } // // func bezierTableViewNumberOfCells(bezierTableView: COBezierTableView) -> NSInteger { // return 30 // } //} // //class COBezierTableViewTests: XCTestCase { // // let bezierTableView = COBezierTableView(frame: CGRectMake(0, 0, 322, 22)) // let dataSource = COBezierDataSourceTest() // // override func setUp() { // super.setUp() // bezierTableView.dataSource = dataSource // bezierTableView.registerNib(UINib(nibName: "MyBezierTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") // bezierTableView.layoutSubviews() // } // // override func tearDown() { // super.tearDown() // } // // func testDidAddCellsToTableView() { // let totalCells = dataSource.bezierTableViewNumberOfCells(bezierTableView) // if (totalCells > 0) { // XCTAssertGreaterThan(bezierTableView.bezierContentView.subviews.count, 0, "TableView should at least add one view if datasource has data") // } else { // XCTAssertEqual(bezierTableView.bezierContentView.subviews.count, 0, "If there is 0 items in datasource. Also ") // } // // XCTAssertNotEqual(bezierTableView.bezierContentView.subviews.count, dataSource.bezierTableViewNumberOfCells(bezierTableView), "TableView should recycle views and not add all at once") // } // // func testPerformanceLayoutSubviewsSmallDataSource() { // class COBezierDataSourceTestMock : COBezierDataSourceTest { // override func bezierTableViewNumberOfCells(bezierTableView: COBezierTableView) -> NSInteger { // return 5 // } // } // // bezierTableView.dataSource = COBezierDataSourceTestMock() // bezierTableView.layoutSubviews() // // // This is an example of a performance test case. // self.measureBlock() { // self.bezierTableView.reloadData() // self.bezierTableView.layoutSubviews() // } // } // // func testPerformanceLayoutSubviewsMediumDataSource() { // class COBezierDataSourceTestMock : COBezierDataSourceTest { // override func bezierTableViewNumberOfCells(bezierTableView: COBezierTableView) -> NSInteger { // return 100 // } // } // // bezierTableView.dataSource = COBezierDataSourceTestMock() // bezierTableView.layoutSubviews() // // // This is an example of a performance test case. // self.measureBlock() { // self.bezierTableView.reloadData() // self.bezierTableView.layoutSubviews() // } // } // // func testPerformanceLayoutSubviewsBigDataSource() { // class COBezierDataSourceTestMock : COBezierDataSourceTest { // override func bezierTableViewNumberOfCells(bezierTableView: COBezierTableView) -> NSInteger { // return 10000 // } // } // // bezierTableView.dataSource = COBezierDataSourceTestMock() // bezierTableView.layoutSubviews() // // // This is an example of a performance test case. // self.measureBlock() { // self.bezierTableView.reloadData() // self.bezierTableView.layoutSubviews() // } // } //}
mit
pseudobeer/sk-otoge
otoge/GameScene.swift
1
13953
// // GameScene.swift // otoge // // Created by Torgayev Tamirlan on 2015/11/30. // Copyright (c) 2015年 pseudobeer. All rights reserved. // import SpriteKit import Foundation var score:Int = 0 var combo:Int = 0 var maxcombo:Int = 0 // |--------------...-----| // |--------------...-----| // |--()--()--()--...-()--| // |--------------...-----| // "--" is magic number // "--(" is radius + magic number // ")--(" is distance = radius + magic number + radius var hitCircleRadius:CGFloat = 30 var hitCircleDistance:CGFloat = hitCircleRadius*2 + 10 var hitCircleCount:CGFloat = 6 class GameScene: SKScene { let minimumDistance:CGFloat = 80 var height:CGFloat = 0.0 var width:CGFloat = 0.0 var scoreLabel:SKLabelNode? var comboLabel:SKLabelNode? var hitAreaArray: [hitArea] = [] var hitLayer: SKNode? var noteLayer: SKNode? var labelLayer: SKNode? var bgLayer: SKNode? var trace: SKSpriteNode? var explosion: SKSpriteNode? var texture: SKTexture? var backgroundTexture: SKTexture? var levelMusic: SKAudioNode? var thresold300: CGFloat = 0 var thresold150: CGFloat = 0 var thresold50: CGFloat = 0 var thresoldFail: CGFloat = 0 // Simutation var alternator = 0 var flag:Bool = true var fallTimer:Timer? func fallCircleWrapper() { if (flag == true) { self.alternator += 1 } else { self.alternator -= 1 } if (self.alternator == 0) { flag = true } else if (self.alternator == 5) { flag = false } self.hitAreaArray[self.alternator].emitNote(self.texture!) //fallCircle(self.alternator) } // Simulation end func failCombo() { if (combo > maxcombo) { maxcombo = combo } combo = 0 } func scoreObject(_ object: noteObject) { print("Called scoreObject") let area = object.parentArea if (object.id == area.lastHitId + 1) { // score normally let distance = object.position.y - (area.hitnode?.position.y)! area.lastHitId += 1 if (distance < thresold300) { score += 300 combo += 1 } else if (distance < thresold150) { score += 150 combo += 1 } else if (distance < thresold50) { score += 50 combo += 1 } else { failCombo() } } else { area.lastHitId = object.id failCombo() } scoreLabel!.text = "Score: \(score)" comboLabel!.text = "Combo: \(combo)" fadeAndDisappear(TargetNode: object, FadeDuration: 0.1) } func compareSKNodeName(_ a: SKNode, b: SKNode) -> Bool { let x = a.name?.compare(b.name!) return (x != ComparisonResult.orderedDescending) } func fadeAndDisappear(TargetNode a: SKNode, FadeDuration fade: Double ) { let fadeAction = SKAction.fadeAlpha(to: 0, duration: fade) let disappearAction = SKAction.customAction(withDuration: 0, actionBlock: customDisapperAction) a.run(SKAction.sequence([fadeAction, disappearAction])) } func customDisapperAction(_ a: SKNode, b: CGFloat) -> Void { if ((a.name as String?)!.hasPrefix("circle")) { combo = 0 comboLabel?.text = "Combo: \(combo)" } a.removeFromParent() } func transitionGameOver() -> Void { if (combo > maxcombo) { maxcombo = combo } self.fallTimer?.invalidate() let transition: SKTransition = SKTransition.crossFade(withDuration: 1) let scene: SKScene = gameOver(size: self.size) self.view?.showsFPS = false self.view?.showsNodeCount = false self.view?.showsDrawCount = false self.view?.presentScene(scene, transition: transition) } private func newExplosion() -> SKEmitterNode { let explosion = SKEmitterNode() let image = UIImage(named:"spark.png")! explosion.particleTexture = SKTexture(image: image) explosion.particleColor = UIColor.brown() explosion.numParticlesToEmit = 20 explosion.particleBirthRate = 200 explosion.particleLifetime = 1 explosion.emissionAngleRange = 360 explosion.particleSpeed = 50 explosion.particleSpeedRange = 10 explosion.xAcceleration = 0 explosion.yAcceleration = 0 explosion.particleAlpha = 0.8 explosion.particleAlphaRange = 0.2 explosion.particleAlphaSpeed = -1 explosion.particleScale = 0.75 explosion.particleScaleRange = 0.4 explosion.particleScaleSpeed = -0.5 explosion.particleRotation = 0 explosion.particleRotationRange = 0 explosion.particleRotationSpeed = 0 explosion.particleColorBlendFactor = 1 explosion.particleColorBlendFactorRange = 0 explosion.particleColorBlendFactorSpeed = 0 explosion.particleBlendMode = SKBlendMode.add explosion.name = "explosion" return explosion } private func newExplosionTrace() -> SKEmitterNode { let explosion = SKEmitterNode() let lifetime = 0.3 let image = UIImage(named:"spark.png")! explosion.particleTexture = SKTexture(image: image) explosion.particleColor = UIColor.brown() explosion.numParticlesToEmit = 0 explosion.particleBirthRate = 10 explosion.particleLifetime = CGFloat(lifetime) explosion.emissionAngleRange = 360 explosion.particleSpeed = 10 explosion.particleSpeedRange = 5 explosion.xAcceleration = 0 explosion.yAcceleration = 0 explosion.particleAlpha = 0.5 explosion.particleAlphaRange = 0.2 explosion.particleAlphaSpeed = -0.9 explosion.particleScale = 0.4 explosion.particleScaleRange = 0 explosion.particleScaleSpeed = 0 explosion.particleRotation = 0 explosion.particleRotationRange = 0 explosion.particleRotationSpeed = 0 explosion.particleColorBlendFactor = 1 explosion.particleColorBlendFactorRange = 0 explosion.particleColorBlendFactorSpeed = 0 explosion.particleBlendMode = SKBlendMode.screen explosion.name = "trace" explosion.particleColorSequence = SKKeyframeSequence( keyframeValues: [SKColor(red: 255, green: 179, blue: 60, alpha: 0), SKColor(red: 255, green: 179, blue: 60, alpha: 1), SKColor(red: 255, green: 179, blue: 60, alpha: 1)], times: [0, 0.8, 1]) return explosion } override func didMove(to view: SKView) { self.scene?.scaleMode = SKSceneScaleMode.resizeFill self.height = (self.view?.frame.size.height)! self.width = (self.view?.frame.size.width)! hitCircleRadius = self.frame.width/22 hitCircleDistance = hitCircleRadius*2.3 thresold300 = 0.01*height thresold150 = 0.04*height thresold50 = 0.08*height thresoldFail = 0.10*height self.backgroundTexture = SKTextureAtlas(named: "assets").textureNamed("bgtexture") self.texture = SKTextureAtlas(named: "assets").textureNamed("notesprite") self.texture!.usesMipmaps = true self.texture!.filteringMode = .linear self.bgLayer = SKNode() self.bgLayer!.zPosition = 0 self.addChild(self.bgLayer!) self.hitLayer = SKNode() self.hitLayer!.zPosition = 1 self.addChild(self.hitLayer!) self.noteLayer = SKNode() self.noteLayer!.zPosition = 2 self.addChild(self.noteLayer!) self.labelLayer = SKNode() self.labelLayer!.zPosition = 3 self.addChild(self.labelLayer!) let backgroundLayer = SKSpriteNode(texture: backgroundTexture) backgroundLayer.position = CGPoint(x: self.width * 0.5, y: self.height*0.5) backgroundLayer.size = (self.view?.frame.size)! self.bgLayer!.addChild(backgroundLayer) let scoreLabel = SKLabelNode(fontNamed: "Palatino-Roman") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.right scoreLabel.position = CGPoint(x: self.width * 0.9, y: self.height*0.8) scoreLabel.fontSize = 30 self.scoreLabel = scoreLabel self.labelLayer!.addChild(scoreLabel) let comboLabel = SKLabelNode(fontNamed: "Palatino-Roman") comboLabel.text = "Combo: 0" comboLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.right comboLabel.position = CGPoint(x: self.width * 0.9, y: self.height*0.7) comboLabel.fontSize = 30 self.comboLabel = comboLabel self.labelLayer!.addChild(comboLabel) print("scene size \(self.scene?.size)") print("frame size \(self.frame.size)") print(" view size \(self.view?.frame.size)") var xpos = width/(hitCircleCount*hitCircleDistance*2) xpos = ceil(xpos) let ypos = self.height * 0.25 var pos = CGPoint(x: 0,y: 0) var epos = CGPoint(x: 0,y: 0) for i in 0...Int(hitCircleCount) - 1 { if (i == 0) { // position hit circles to center let spaceUnused = self.width - hitCircleCount*hitCircleDistance xpos += hitCircleDistance/2 + spaceUnused/2 } else { xpos += hitCircleDistance } pos = CGPoint(x: xpos, y: ypos) epos = CGPoint(x: self.width/2, y: self.height - ypos) let area = hitArea(gameScene: self, position: pos, emitterposition: epos) hitAreaArray.append(area) } let trace = SKSpriteNode() trace.size = (self.scene?.size)! trace.position = CGPoint(x: 0, y: 0) self.trace = trace self.addChild(trace) let explosion = SKSpriteNode() explosion.size = (self.scene?.size)! self.explosion = explosion self.addChild(explosion) self.fallTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(GameScene.fallCircleWrapper), userInfo: nil, repeats: true) // let music = SKAudioNode(fileNamed: "test.wav") // music.autoplayLooped = false // // self.addChild(music) run(SKAction.playSoundFileNamed("test.wav", waitForCompletion: true), completion: transitionGameOver) // self.levelMusic = music } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { /* Called when a touch begins */ if let touch = touches.first { let location = touch.location(in: self) let explosion = newExplosion() explosion.position = location explosion.name = "explosion" fadeAndDisappear(TargetNode: explosion, FadeDuration: 2) self.explosion!.addChild(explosion) let trace = newExplosionTrace() trace.position = location trace.targetNode = self.trace self.trace!.addChild(trace) let hits = self.nodes(at: location) for hit in hits { print(hit.name) if (hit.isKind(of: noteObject.self)) { let hitNote = (hit as! noteObject) let distance = hit.position.y - (hitNote.parentArea.hitnode?.position.y)! if (abs(distance) < thresoldFail) { scoreObject(hitNote) } print(distance) } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let traces: [SKEmitterNode]? = self.trace!.children as? [SKEmitterNode] if (traces != nil && traces?.isEmpty != nil) { for trace in traces! { trace.particlePosition = (touches.first?.location(in: trace))! } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let traces: [SKEmitterNode]? = self.trace!.children as? [SKEmitterNode] let nodesUnderFinger = self.trace!.nodes(at: (touches.first?.location(in: self.trace!))!) for node in nodesUnderFinger { node.removeFromParent() } if (traces != nil && traces?.isEmpty != nil) { for trace in traces! { fadeAndDisappear(TargetNode: trace, FadeDuration: 0.5) } } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ let explosions: [SKEmitterNode]? = self.explosion?.children as? [SKEmitterNode] if (explosions != nil && explosions?.isEmpty != nil) { for explosion in explosions! { if (explosion.numParticlesToEmit == 0) { explosion.removeFromParent() } } } } }
mit
Sweebi/tvProgress
Demo/tvProgress-Demo/SweebiProgress.swift
1
1927
// // SweebiProgress.swift // tvProgress-Demo // // Created by Antoine Cormery on 02/06/2016. // Copyright © 2016 tvProgress. All rights reserved. // import Foundation import tvProgress class SweebiProgress: tvProgressAnimatable { let sweebiLogo: CAShapeLayer = CAShapeLayer() required init() { } func configureWithStyle(_ style: tvProgressStyle) -> (view: UIView, completion: () -> Void) { let v: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 200)) self.sweebiLogo.bounds = v.bounds self.sweebiLogo.position = v.center self.sweebiLogo.lineWidth = 11 self.sweebiLogo.strokeColor = style.mainColor.cgColor self.sweebiLogo.fillColor = UIColor.clear.cgColor self.sweebiLogo.strokeStart = 0 self.sweebiLogo.strokeEnd = 0 let bezier: UIBezierPath = UIBezierPath() bezier.move(to: CGPoint(x: 90, y: 56)) bezier.addLine(to: CGPoint(x: 90, y: 0)) bezier.addLine(to: CGPoint(x: 10, y: 0)) bezier.addLine(to: CGPoint(x: 10, y: 80)) bezier.addLine(to: CGPoint(x: 136, y: 80)) bezier.addLine(to: CGPoint(x: 136, y: 160)) bezier.addLine(to: CGPoint(x: 56, y: 160)) bezier.addLine(to: CGPoint(x: 56, y: 104)) self.sweebiLogo.path = bezier.cgPath v.layer.addSublayer(self.sweebiLogo) let completion: () -> Void = { () -> Void in self.sweebiLogo.removeAllAnimations() } return (v, completion) } func updateProgress(_ progress: Double) { let anim: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") anim.toValue = progress anim.beginTime = 0 anim.duration = 0.25 anim.fillMode = kCAFillModeForwards anim.isRemovedOnCompletion = false self.sweebiLogo.add(anim, forKey: nil) } }
mit