repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wesj/firefox-ios-1
Sync/KeysPayload.swift
1
1355
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public class KeysPayload: CleartextPayloadJSON { override public func isValid() -> Bool { // We should also call super.isValid(), but that'll fail: // Global is external, but doesn't have external or weak linkage! // Swift compiler bug #18422804. return !isError && self["default"].isArray } var defaultKeys: KeyBundle? { if let pair: [JSON] = self["default"].asArray { if let encKey = pair[0].asString { if let hmacKey = pair[1].asString { return KeyBundle(encKeyB64: encKey, hmacKeyB64: hmacKey) } } } return nil } override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool { if !(obj is KeysPayload) { return false; } if !super.equalPayloads(obj) { return false; } let p = obj as KeysPayload if p.defaultKeys != self.defaultKeys { return false } // TODO: check collections. return true } }
mpl-2.0
4fbf0d2e87a6863274623b3999eb45d1
28.478261
76
0.560886
4.787986
false
false
false
false
appanalytic/lib-swift
Example/RealAppTest/Pods/AppAnalyticsSwift/AppAnalyticsSwift/Classes/AppAnalyticsSwift.swift
1
7955
// // AppAnalytic.swift // Pods // // Created by Vahid Sayad on 2016-06-19. // // import Foundation import UIKit public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 where value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } } public class AppAnalyticsSwift{ private let _accessKey: String private var _APIURL = "http://appanalytics.ir/api/v1/iosservice/initialize/"; private var _APIURL_DeviceInfo = "http://appanalytics.ir/api/v1/iosservice/setdeviceinfo/"; private let _UUID: String private var _deviceModelName: String private var _iOSVersion: String private var _orientation: String private var _batteryLevel: String private var _multitaskingSupported: String // ////////////////////////////////////////////////////////////////////////////////////////////////// //MARK: submitCampain Function // ////////////////////////////////////////////////////////////////////////////////////////////////// public func submitCampaign(){ let url = NSURL(string: self._APIURL + self._UUID) let request = NSMutableURLRequest(URL: url!) request.setValue(self._accessKey, forHTTPHeaderField: "Access-Key") NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in if let data = data { print("AppAnalytic Info: [", String(data: data, encoding: NSUTF8StringEncoding)!,"]") self.sendDeviceInfo(self.getDeviceInfo()) } if let error = error { print("AppAnalytic Error: [\(error.localizedDescription)") } }.resume() } // ////////////////////////////////////////////////////////////////////////////////////////////////// //MARK: SendDeviceInfo() // ////////////////////////////////////////////////////////////////////////////////////////////////// private func sendDeviceInfo(jsonData: NSData){ // Send data... let url = NSURL(string: self._APIURL_DeviceInfo + self._UUID) let request = NSMutableURLRequest(URL: url!) request.setValue(self._accessKey, forHTTPHeaderField: "Access-Key") request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" request.HTTPBody = jsonData NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in if let data = data { print("AppAnalytic Info (Send Device Info): [", String(data: data, encoding: NSUTF8StringEncoding)!,"]") } if let error = error { print("AppAnalytic Error: [\(error.localizedDescription)]") } }.resume() } // ////////////////////////////////////////////////////////////////////////////////////////////////// //Mark: GetDeviceInfo() // ////////////////////////////////////////////////////////////////////////////////////////////////// private func getDeviceInfo() -> NSData { var json = NSData() let info = NSMutableDictionary() if self._deviceModelName != "Error" { info["DeviceModel"] = self._deviceModelName } if self._iOSVersion != "Error" { info["iOSVersion"] = self._iOSVersion } if self._orientation != "Error" { info["Orientation"] = self._orientation } if self._batteryLevel != "Error" { info["BatteryLevel"] = self._batteryLevel } if self._multitaskingSupported != "Error" { info["MultiTaskingSupported"] = self._multitaskingSupported } do { json = try NSJSONSerialization.dataWithJSONObject(info, options: NSJSONWritingOptions.PrettyPrinted) } catch let error as NSError { print(error) } return json } // ////////////////////////////////////////////////////////////////////////////////////////////////// //MARK: Init // ////////////////////////////////////////////////////////////////////////////////////////////////// public init(accessKey key: String){ self._accessKey = key if let id = UIDevice.currentDevice().identifierForVendor { self._UUID = id.UUIDString } else { self._UUID = "error" } //Device model name self._deviceModelName = UIDevice.currentDevice().modelName // iOS Version self._iOSVersion = UIDevice.currentDevice().systemVersion // Device Oriantation let orientation = UIDevice.currentDevice().orientation switch orientation { case .LandscapeLeft: self._orientation = "LandscapeLeft" case .LandscapeRight: self._orientation = "LandscapeRight" case .Portrait: self._orientation = "Portrait" case .PortraitUpsideDown: self._orientation = "PortraitUpsideDown" default: self._orientation = "Error" } // Battery Level switch UIDevice.currentDevice().batteryLevel { case -1.0: self._batteryLevel = "Error" default: self._batteryLevel = String("\(UIDevice.currentDevice().batteryLevel )") } //Multi tasking supported: if UIDevice.currentDevice().multitaskingSupported { self._multitaskingSupported = "true" } else { self._multitaskingSupported = "false" } } }
mit
abf0e2ee5689f94a47b3930e92768935
41.545455
129
0.485858
5.132258
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/Manager/MGPhotoHandleManager.swift
1
14681
// // MGPhotoHandleManager.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit import Photos import ObjectiveC extension PHCachingImageManager { static let defalut = PHCachingImageManager() } /// 进行数据类型转换的Manager class MGPhotoHandleManager: NSObject { /// 用以描述runtime关联属性 struct MGPhotoAssociate { static let mg_assetCollectionAssociate = UnsafeRawPointer(bitPattern: "mg_assetCollection".hashValue) static let mg_cacheAssociate = UnsafeRawPointer(bitPattern: "mg_CacheAssociate".hashValue) static let mg_assetCacheSizeAssociate = UnsafeRawPointer(bitPattern: "mg_assetCacheSizeAssociate".hashValue) } /// PHFetchResult对象转成数组的方法 /// /// - Parameters: /// - result: 转型的fetchResult对象 /// - complete: 完成的闭包 public static func resultToArray(_ result: PHFetchResult<AnyObject>, complete: @escaping ([AnyObject], PHFetchResult<AnyObject>) -> Void) { guard result.count != 0 else { complete([], result); return } var array = [AnyObject]() //开始遍历 result.enumerateObjects({ (object, index, _) in // 过滤自定义空数组 if object.isKind(of: PHAssetCollection.self) && object.estimatedAssetCount > 0 { let assetResult = PHAsset.fetchAssets(in: object as! PHAssetCollection, options: PHFetchOptions()) debugPrint(object.localizedTitle ?? "没有名字") // 过滤空数组 if assetResult.count != 0 { array.append(object) }else { } if index == result.count - 1 { complete(array, result) } }else { if index == result.count - 1 { complete(array, result) } } }) } /// PHFetchResult对象转成PHAsset数组的方法 /// /// - Parameters: /// - result: 转型的fetchResult对象 PHAsset /// - complete: 完成的闭包 public static func resultToPHAssetArray(_ result: PHFetchResult<AnyObject>, complete: @escaping ([AnyObject], PHFetchResult<AnyObject>) -> Void) { guard result.count != 0 else { complete([], result); return } var array = [AnyObject]() //开始遍历 result.enumerateObjects({ (object, index, _) in if object.isKind(of: PHAsset.self) { array.append(object) } complete(array, result) }) } /// 获得选择的图片数组 /// /// - Parameters: /// - allAssets: 所有的资源数组 /// - status: 选中状态 /// - Returns: public static func assets(_ allAssets: [PHAsset], status: [Bool]) -> [PHAsset] { var assethandle = [PHAsset]() for i in 0 ..< allAssets.count { let status = status[i] if status { assethandle.append(allAssets[i]) } } return assethandle } /// 获取PHAssetCollection的详细信息 /// /// - Parameters: /// - size: 获得封面图片的大小 /// - completion: 取组的标题、照片资源的预估个数以及封面照片,默认为最新的一张 public static func assetCollection(detailInformationFor collection: PHAssetCollection, size: CGSize, completion: @escaping ((String?, UInt, UIImage?) -> Void)) { let assetResult = PHAsset.fetchAssets(in: collection, options: PHFetchOptions()) if assetResult.count == 0 { completion(collection.localizedTitle, 0, UIImage()) return } let image: UIImage? = ((objc_getAssociatedObject(collection, MGPhotoHandleManager.MGPhotoAssociate.mg_assetCollectionAssociate!)) as? UIImage) if image != nil { completion(collection.localizedTitle, UInt(assetResult.count), image) return } //开始重新获取图片 let scale = UIScreen.main.scale let newSize = CGSize(width: size.width * scale, height: size.height * scale) PHCachingImageManager.default().requestImage(for: assetResult.lastObject!, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: nil, resultHandler: { (realImage, _) in completion(collection.localizedTitle, UInt(assetResult.count), realImage) }) } /// 获取PHAsset的照片资源 /// - Parameters: /// - asset: 获取资源的对象 /// - size: 截取图片的大小 /// - completion: 获取的图片,以及当前的资源对象 public static func asset(representionIn asset: PHAsset, size: CGSize, completion: @escaping ((UIImage, PHAsset) -> Void)) { if let cacheAssociate = MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate, objc_getAssociatedObject(asset, cacheAssociate) == nil { objc_setAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!, [CGSize](), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } var caches: [CGSize] = objc_getAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!) as! [CGSize] let scale = UIScreen.main.scale let newSize = CGSize(width: size.width * scale, height: size.height * scale) //开始请求 let option = PHImageRequestOptions() option.resizeMode = .fast // 同步获得图片, 只会返回1张图片 option.isSynchronous = true option.isNetworkAccessAllowed = true//默认关闭 let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } PHCachingImageManager.default().requestImage(for: asset, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: option) { (image, info) in if !((info![PHImageResultIsDegradedKey] as? NSNumber)?.boolValue ?? false) { //这样只会走一次获取到高清图时 DispatchQueue.main.async(execute: { completion(image ?? UIImage(), asset) }) } } //进行缓存 if !caches.contains(newSize) { (PHCachingImageManager.default() as! PHCachingImageManager).startCachingImages(for: [asset], targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: PHImageRequestOptions()) caches.append(newSize) //重新赋值 objc_setAssociatedObject(asset, MGPhotoHandleManager.MGPhotoAssociate.mg_cacheAssociate!, caches, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } /// 获取PHAsset的高清图片资源 /// /// - Parameters: /// - asset: 获取资源的对象 /// - size: 获取图片的大小 /// - completion: 完成 public static func asset(hightQuarityFor asset: PHAsset, Size size: CGSize, completion: @escaping ((String) -> Void)) { let newSize = size if let assetCache = MGPhotoAssociate.mg_assetCacheSizeAssociate, objc_getAssociatedObject(asset, assetCache) == nil { let associateData = [String: Any]()//Dictionary<String, Any> objc_setAssociatedObject(asset, assetCache, associateData, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } /// 获得当前所有的存储 var assicciateData = objc_getAssociatedObject(asset, MGPhotoAssociate.mg_assetCacheSizeAssociate!) as! [String: Any] guard assicciateData.index(forKey: NSCoder.string(for: newSize)) == nil else { let index = assicciateData.index(forKey: NSCoder.string(for: newSize))//获得索引 let size = assicciateData[index!].value as! String//获得数据 completion(size); return } let options = PHImageRequestOptions() // options.deliveryMode = .highQualityFormat options.isSynchronous = true options.resizeMode = .fast options.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { options.version = .original } //请求数据 PHCachingImageManager.default().requestImageData(for: asset, options: options) { (data, _, _, _) in guard let data = data else { //回调 completion("0B") return } //进行数据转换 // let size = mg_dataSize((data?.count)!) let size = (data.count).mg_dataSize //新增值 assicciateData.updateValue(size, forKey: NSCoder.string(for: newSize)) //缓存 objc_setAssociatedObject(asset, MGPhotoAssociate.mg_assetCacheSizeAssociate!, assicciateData, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) //回调 completion(size) } } /// 获取PHFetchResult符合媒体类型的PHAsset对象 /// /// - Parameters: /// - result: 获取数据的对象 /// - type: 媒体类型 /// - enumerateObject: 每次获得符合媒体类型的对象调用一次 /// - matchedObject: 每次都会调用一次 /// - completion: 完成之后返回存放符合媒体类型的PHAsset数组 public static func fetchResult(in result: PHFetchResult<PHAsset>, type: PHAssetMediaType, enumerateObject: ((PHAsset) -> Void)?, matchedObject: ((PHAsset) -> Void)?, completion: (([PHAsset]) -> Void)?) { var assets = [PHAsset]() // 如果当前没有数据 guard result.count >= 0 else { completion?(assets);return } //开始遍历 result.enumerateObjects({ (obj, idx, _) in // 每次回调 enumerateObject?(obj) // 如果是类型相符合 if obj.mediaType == type { matchedObject?(obj) assets.append(obj) } if idx == result.count - 1 { // 说明完成 completion?(assets) } }) } /// 获取PHFetchResult符合媒体类型的PHAsset对象 /// /// - Parameters: /// - result: 获取资源的对象 /// - type: 媒体类型 /// - completion: 完成之后返回存放符合媒体类型的PHAsset数组 public static func fetchResult(in result: PHFetchResult<PHAsset>, type: PHAssetMediaType, completion: (([PHAsset]) -> Void)?) { fetchResult(in: result, type: type, enumerateObject: nil, matchedObject: nil, completion: completion) } /// 获得选择的资源数组 /// /// - Parameters: /// - assets: 存放资源的数组 /// - status: 对应资源的选中状态数组 /// - Returns: 筛选完毕的数组 public static func filter(assetsIn assets: [PHAsset], status: [Bool]) -> [PHAsset] { var assetHandle = [PHAsset]() for asset in assets { //如果状态为选中 if status[assets.firstIndex(of: asset)!] { assetHandle.append(asset) } } return assetHandle } } extension MGPhotoHandleManager { /// 获取资源中的图片对象 /// /// - Parameters: /// - assets: 需要请求的asset数组 /// - isHight: 图片是否需要高清图 /// - size: 当前图片的截取size /// - ignoreSize: 是否无视size属性,按照图片原本大小获取 /// - completion: 返回存放images的数组 static func startRequestImage(imagesIn assets: [PHAsset], isHight: Bool, size: CGSize, ignoreSize: Bool, completion: @escaping (([UIImage]) -> Void)) { var images = [UIImage]() var newSize = size for i in 0 ..< assets.count { //获取资源 let asset = assets[i] //重置大小 if ignoreSize { newSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) } //图片类型 let mode = isHight ? PHImageRequestOptionsDeliveryMode.highQualityFormat : PHImageRequestOptionsDeliveryMode.fastFormat //初始化option let option = PHImageRequestOptions() option.deliveryMode = mode option.isSynchronous = true option.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } //开始请求 PHImageManager.default().requestImage(for: asset, targetSize: newSize, contentMode: PHImageContentMode.aspectFill, options: option, resultHandler: { (image, _) in //添加 images.append(image!) if images.count == assets.count { completion(images) } }) } } /// 获取资源中图片的数据对象 /// /// - Parameters: /// - assets: 需要请求的asset数组 /// - isHight: 图片是否需要高清图 /// - completion: 返回存放images的数组 static func startRequestData(imagesIn assets: [PHAsset], isHight: Bool, completion: @escaping (([Data]) -> Void)) { var datas = [Data]() for i in 0 ..< assets.count { let asset = assets[i] let mode = isHight ? PHImageRequestOptionsDeliveryMode.highQualityFormat : PHImageRequestOptionsDeliveryMode.fastFormat //初始化option let option = PHImageRequestOptions() option.deliveryMode = mode option.isSynchronous = true option.isNetworkAccessAllowed = true let fileName: String? = asset.value(forKeyPath: "filename") as? String if let fileName = fileName, fileName.hasSuffix("GIF") { option.version = .original } //请求数据 PHImageManager.default().requestImageData(for: asset, options: option, resultHandler: { (data, _, _, _) in if let data = data { datas.append(data) } if datas.count == assets.count { completion(datas) } }) } } }
mit
2e8277c93417fb9e337768361c7eb27a
34.740741
207
0.591562
4.732049
false
false
false
false
kstaring/swift
test/PlaygroundTransform/init.swift
5
699
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test class B { init() { } } class C : B { var i : Int var j : Int override init() { i = 3 j = 5 i + j } } let c = C() // CHECK: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='8'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[c='main.C']
apache-2.0
3b194c27e4c39bc1c914fef274e8bd7a
23.964286
139
0.572246
2.88843
false
false
false
false
richardpiazza/SOSwift
Tests/SOSwiftTests/DateOnlyOrDateTimeTests.swift
1
2603
import XCTest @testable import SOSwift class DateOnlyOrDateTimeTests: XCTestCase { static var allTests = [ ("testDecode", testDecode), ("testEncode", testEncode), ("testEquatability", testEquatability), ] fileprivate class TestClass: Codable, Schema { var dateOnly: DateOnlyOrDateTime? var dateTime: DateOnlyOrDateTime? var multiple: [DateOnlyOrDateTime]? } private var dateOnlyComponents: DateComponents { return DateComponents(calendar: Calendar.current, timeZone: TimeZone.gmt, era: nil, year: 2017, month: 10, day: 26, hour: nil, minute: nil, second: nil, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil) } private var dateTimeComponents: DateComponents { return DateComponents(calendar: Calendar.current, timeZone: TimeZone.gmt, era: nil, year: 2017, month: 10, day: 26, hour: 7, minute: 58, second: 0, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil) } func testDecode() throws { let json = """ { "dateOnly" : "2017-10-26", "dateTime" : "2017-10-26T07:58:00Z" } """ let testClass = try TestClass.make(with: json) XCTAssertEqual(testClass.dateOnly?.dateOnly?.rawValue, dateOnlyComponents.date) XCTAssertNil(testClass.dateOnly?.dateTime) XCTAssertEqual(testClass.dateTime?.dateTime?.rawValue, dateTimeComponents.date) XCTAssertNil(testClass.dateTime?.dateOnly) } func testEncode() throws { let testClass = TestClass() testClass.dateOnly = .dateOnly(value: DateOnly(stringValue: "2019-06-16")!) testClass.dateTime = .dateTime(value: DateTime(stringValue: "2019-06-16T08:14:00-5000")!) let dictionary = try testClass.asDictionary() XCTAssertEqual(dictionary["dateOnly"] as? String, "2019-06-16") XCTAssertEqual(dictionary["dateTime"] as? String, "2019-06-16T13:14:00Z") } func testEquatability() throws { let date = Date() let t1 = DateOnlyOrDateTime(DateOnly(rawValue: date)) let t2 = DateOnlyOrDateTime(DateOnly(rawValue: date)) let t3 = DateOnlyOrDateTime(DateTime(rawValue: date)) let t4 = DateOnlyOrDateTime(DateTime(rawValue: date)) XCTAssertEqual(t1, t2) XCTAssertNotEqual(t1, t3) XCTAssertEqual(t3, t4) XCTAssertNotEqual(t2, t4) } }
mit
8411faa35c62b7307d13736a91806c2e
39.671875
285
0.650403
4.519097
false
true
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Renderers/ChartXAxisRendererRadarChart.swift
6
2997
// // ChartXAxisRendererRadarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ChartXAxisRendererRadarChart: ChartXAxisRenderer { public weak var chart: RadarChartView? public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil) self.chart = chart } public override func renderAxisLabels(context context: CGContext) { guard let xAxis = xAxis, chart = chart else { return } if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled) { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD let drawLabelAnchor = CGPoint(x: 0.5, y: 0.0) let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let modulus = xAxis.axisLabelModulus for var i = 0, count = xAxis.values.count; i < count; i += modulus { let label = xAxis.values[i] if (label == nil) { continue } let angle = (sliceangle * CGFloat(i) + chart.rotationAngle) % 360.0 let p = ChartUtils.getPosition(center: center, dist: CGFloat(chart.yRange) * factor + xAxis.labelRotatedWidth / 2.0, angle: angle) drawLabel(context: context, label: label!, xIndex: i, x: p.x, y: p.y - xAxis.labelRotatedHeight / 2.0, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: drawLabelAnchor, angleRadians: labelRotationAngleRadians) } } public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat) { guard let xAxis = xAxis else { return } let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } public override func renderLimitLines(context context: CGContext) { /// XAxis LimitLines on RadarChart not yet supported. } }
mit
f3fc7008b36f6ea97c9bb2b3f95e4b09
33.45977
274
0.635302
4.961921
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/LayoutExampleSceneViewController+Actions.swift
1
1208
import Cocoa extension LayoutExampleSceneViewController { @IBAction func previousButtonDidClick(_ sender: Any) { activeLayout.switchToPreviousLayout() configureBluePrintLayout() configureSceneLayoutTitle() } @IBAction func nextButtonDidClick(_ sender: Any) { activeLayout.switchToNextLayout() configureBluePrintLayout() configureSceneLayoutTitle() } @IBAction func applyButtonDidClick(_ sender: Any) { let currentLayoutConfiguration = currentlayoutConfiguration() if currentConfiguration != currentLayoutConfiguration { currentConfiguration = currentLayoutConfiguration itemsPerRow = (currentConfiguration?.itemsPerRow) ?? (Constants.ExampleLayoutDefaults.itemsPerRow) itemsPerColumn = (currentConfiguration?.itemsPerCollumn) ?? (Constants.ExampleLayoutDefaults.itemsPerColumn) minimumLineSpacing = (currentConfiguration?.minimumLineSpacing) ?? (Constants.ExampleLayoutDefaults.minimumLineSpacing) sectionInsets = (currentConfiguration?.sectionInsets) ?? (Constants.ExampleLayoutDefaults.sectionInsets) configureBluePrintLayout() } } }
mit
df0d5b72ac06f28e84926d6b8d2b1659
42.142857
131
0.726821
6.565217
false
true
false
false
Aishwarya-Ramakrishnan/sparkios
Source/Phone/Call/DtmfQueue.swift
1
4269
// Copyright 2016 Cisco Systems Inc // // 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 class DtmfQueue { typealias CompletionHandler = (Bool) -> Void var queue: [(event: String, completionHandler: CompletionHandler?)] let dispatchQueue: DispatchQueue weak var call: Call! var correlationId: Int var waitingForResponse: Bool private let deviceUrl = DeviceService.sharedInstance.deviceUrl init(_ call: Call) { queue = [] correlationId = 1 self.call = call dispatchQueue = DispatchQueue(label: "CallDtmfQueueDispatchQueue") waitingForResponse = false } func isValidEvents(_ events: String) -> Bool { let characterset = CharacterSet(charactersIn: "1234567890*#ABCDabcd") if events.rangeOfCharacter(from: characterset.inverted) != nil { return false } else { return true } } func push(_ event: String, completionHandler: CompletionHandler?) { if isValidEvents(event) { dispatchQueue.async { self.queue.append((event, completionHandler)) self.sendDtmfEvents(completionHandler) } } else { if let handler = completionHandler { handler(false) } } } func sendDtmfEvents(_ completionHandler: CompletionHandler?) { dispatchQueue.async { if self.queue.count > 0 && !self.waitingForResponse { var events = [String]() var completionHandlers = [CompletionHandler?]() for item in self.queue { events.append(item.event) completionHandlers.append(item.completionHandler) } let dtmfEvents = events.joined(separator: "") Logger.info("send Dtmf events \(dtmfEvents)") let participantUrl = self.call.info?.selfParticipantUrl self.waitingForResponse = true CallClient().sendDtmf(participantUrl!, deviceUrl: self.deviceUrl!, correlationId: self.correlationId, events: dtmfEvents, queue: self.dispatchQueue) { switch $0.result { case .success: Logger.info("Success: send Dtmf with correlationId \(self.correlationId - 1)") for completion in completionHandlers { DispatchQueue.main.async { completion?(true) } } case .failure(let error): Logger.error("Failure", error: error) for completion in completionHandlers { DispatchQueue.main.async { completion?(false) } } } self.waitingForResponse = false self.sendDtmfEvents(completionHandler) } self.correlationId += 1 self.queue.removeAll() } } } }
mit
8ede2b48fdbd7f466f42fa05c6779b64
39.657143
166
0.582806
5.522639
false
false
false
false
wyp767363905/TestKitchen_1606
TestKitchen/TestKitchen/classes/common/UIButton+Util.swift
1
1056
// // UIButton+Util.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 1606. All rights reserved. // import UIKit extension UIButton { class func createBtn(title: String?, bgImageName: String?, selectBgImageName: String?, target: AnyObject?, action: Selector) -> UIButton { let btn = UIButton(type: .Custom) if let btnTitle = title { btn.setTitle(btnTitle, forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Normal) } if let btnBgImageName = bgImageName { btn.setBackgroundImage(UIImage(named: btnBgImageName), forState: .Normal) } if let btnSelectBgImageName = selectBgImageName { btn.setBackgroundImage(UIImage(named: btnSelectBgImageName), forState: .Selected) } if let btnTarget = target { btn.addTarget(btnTarget, action: action, forControlEvents: .TouchUpInside) } return btn } }
mit
3a664cf6cb82eacba034e0233bb16e72
26.710526
142
0.603989
4.743243
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/CourseDashboardCell.swift
2
3288
// // CourseDashboardCell.swift // edX // // Created by Jianfeng Qiu on 13/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class CourseDashboardCell: UITableViewCell { static let identifier = "CourseDashboardCellIdentifier" //TODO: all these should be adjusted once the final UI is ready private let ICON_SIZE : CGFloat = OEXTextStyle.pointSizeForTextSize(OEXTextSize.XXLarge) private let ICON_MARGIN : CGFloat = 30.0 private let LABEL_MARGIN : CGFloat = 75.0 private let LABEL_SIZE_HEIGHT = 20.0 private let CONTAINER_SIZE_HEIGHT = 60.0 private let CONTAINER_MARGIN_BOTTOM = 15.0 private let INDICATOR_SIZE_WIDTH = 10.0 private let container = UIView() private let iconView = UIImageView() private let titleLabel = UILabel() private let detailLabel = UILabel() private let bottomLine = UIView() private var titleTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Base, color : OEXStyles.sharedStyles().neutralXDark()) } private var detailTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .XXSmall, color : OEXStyles.sharedStyles().neutralBase()) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configureViews() } func useItem(item : StandardCourseDashboardItem) { self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(item.title) self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(item.detail) self.iconView.image = item.icon.imageWithFontSize(ICON_SIZE) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViews() { self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight() applyStandardSeparatorInsets() self.container.addSubview(iconView) self.container.addSubview(titleLabel) self.container.addSubview(detailLabel) self.contentView.addSubview(container) self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator iconView.tintColor = OEXStyles.sharedStyles().neutralLight() container.snp_makeConstraints { make -> Void in make.edges.equalTo(contentView) } iconView.snp_makeConstraints { (make) -> Void in make.leading.equalTo(container).offset(ICON_MARGIN) make.centerY.equalTo(container) } titleLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(container).offset(LABEL_MARGIN) make.trailing.lessThanOrEqualTo(container) make.top.equalTo(container).offset(LABEL_SIZE_HEIGHT) make.height.equalTo(LABEL_SIZE_HEIGHT) } detailLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(titleLabel) make.trailing.lessThanOrEqualTo(container) make.top.equalTo(titleLabel.snp_bottom) make.height.equalTo(LABEL_SIZE_HEIGHT) } } }
apache-2.0
8873eed836fdb2734348a11436482c3c
35.533333
109
0.668187
4.914798
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Web/View/BTDisTableViewCell.swift
1
2525
// // BTDisTableViewCell.swift // BanTang // // Created by 张灿 on 16/5/24. // Copyright © 2016年 张灿. All rights reserved. // import UIKit import SDWebImage class BTDisTableViewCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var nickname: UILabel! @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var order_time_str: UILabel! @IBOutlet weak var views: UILabel! @IBOutlet weak var comments: UILabel! @IBOutlet weak var imageView0: UIImageView! @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView2: UIImageView! //设置cell的显示内容 var topicItem : BTTopicItem? { didSet { //先校验是否有值 guard let topicItem = topicItem else { return } title.text = topicItem.title order_time_str.text = topicItem.order_time_str views.text = topicItem.views comments.text = topicItem.comments nickname.text = topicItem.user?.nickname let url = NSURL(string: (topicItem.user?.avatar)!) avatar.sd_setImageWithURL(url, placeholderImage: UIImage(named: "default_user_loading_icon_100x100_")) setImageView(0, imageView: imageView0) setImageView(1, imageView: imageView1) setImageView(2, imageView: imageView2) } } //:MARK- 设置cell中间的图片 func setImageView(count: NSInteger, imageView: UIImageView) { if let dict: [String: String] = topicItem!.pics![count] { let urlStr = dict["url"]! let urlStr0 = (urlStr as NSString).stringByReplacingOccurrencesOfString("!300x300", withString: "") let url = NSURL(string: urlStr0) imageView.sd_setImageWithURL(url) } } override func awakeFromNib() { super.awakeFromNib() //设置头像圆角 avatar.layer.cornerRadius = self.avatar.frame.size.width * 0.5; avatar.layer.masksToBounds = true; } //重写frame方法,扩大cell间距,造成分割线 override var frame: CGRect{ didSet{ super.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height - 10) } } }
apache-2.0
c8e0e71fa234eb4109e787da19b604db
26.659091
127
0.569844
4.662835
false
false
false
false
csano/blink-api-swift
src/blinkapi/serviceMediator.swift
1
1522
public protocol EventArgs { } public enum Event { case Login case Network } public class LoginEventArgs : EventArgs { public var s = "Login" } public class NetworkEventArgs : EventArgs { public var s = "Network" } //typealias EventCallback = (EventArgs: EventArgs) -> Void public typealias EventCallbackType = (EventArgs?) -> Void public class EventRegistry { // TODO: ObjectIdentifier instead of String? private var registry: [Event: [EventCallbackType]] = [:] public func register(event: Event, callback: @escaping EventCallbackType) { if !registry.keys.contains(event) { registry[event] = [] } registry[event]?.append(callback) } subscript(event: Event) -> [EventCallbackType]! { get { return registry.keys.contains(event) ? registry[event] : [] } } } public class EventDispatcher { private var eventRegistry: EventRegistry; init(eventRegistry: EventRegistry) { self.eventRegistry = eventRegistry } func dispatch(event: Event, data: EventArgs) { for callback in eventRegistry[event] { callback(data) } } } public final class EventCallback<T: EventArgs> { func execute(EventArgs: Any?) -> Void { if let castData = EventArgs as? T { self.callback(castData) } } init(callback: @escaping (T?)-> Void){ self.callback = callback } private let callback : (T?) -> Void }
lgpl-3.0
794dcb68ad15bd07315138bed50558df
21.716418
79
0.616294
4.311615
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/GISTSocial/Reachability/ReachabilityHelper.swift
1
7049
// // ReachabilityHelper.swift // eGrocery // // Created by Shoaib on 3/27/15. // Copyright (c) 2015 cubixlabs. All rights reserved. // // import UIKit import Alamofire public var REACHABILITY_HELPER:ReachabilityHelper { get { return ReachabilityHelper.sharedInstance; } } //P.E. /// GISTApplication protocol to receive events @objc public protocol ReachabilityDelegate { @objc optional func reachabilityDidUpdate(_ status: Bool); } //F.E. public class ReachabilityHelper: NSObject { private var window: UIWindow? { get { return (UIApplication.shared.connectedScenes.first?.delegate as? BaseSceneDelegate)?.window; } } private var statusBarFrameHeight:CGFloat { return self.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0; } static var sharedInstance: ReachabilityHelper = ReachabilityHelper(); private var _reachability:NetworkReachabilityManager?; private var _internetConnected:Bool = false; private var internetConnected:Bool { get { return _internetConnected; } set { _internetConnected = newValue; self.internetConnectionLabelHidden = _internetConnected; } } //P.E. //Public Method public var isInternetConnected:Bool { get { if (self.internetConnectionLabelHidden != _internetConnected) { self.internetConnectionLabelHidden = _internetConnected; } else if (_internetConnected == false) { self.internetConnectionLbl.shake(); } return _internetConnected; } } //P.E. fileprivate var _internetConnectionLbl:BaseUIButton!; fileprivate var internetConnectionLbl:BaseUIButton { get { if (_internetConnectionLbl == nil) { let statusBarHeight:CGFloat = self.statusBarFrameHeight; let btnSize:CGSize = CGSize(width: UIScreen.main.bounds.width, height: 44 + statusBarHeight); _internetConnectionLbl = BaseUIButton(); _internetConnectionLbl.frame = CGRect(x: 0, y: -btnSize.height, width: btnSize.width, height: btnSize.height); _internetConnectionLbl.titleEdgeInsets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0); _internetConnectionLbl.setTitle("No Internet Connection", for: UIControl.State.normal); _internetConnectionLbl.setTitleColor(UIColor.white, for: UIControl.State.normal); _internetConnectionLbl.backgroundColor = UIColor.theme; _internetConnectionLbl.titleLabel?.font = UIFont.font("small"); //Adding Target _internetConnectionLbl.addTarget(self, action: #selector(ReachabilityHelper.internetConnectionLabelTapHandler(_:)) , for: UIControl.Event.touchUpInside) self.window?.addSubview(_internetConnectionLbl); } return _internetConnectionLbl; } } //P.E. fileprivate var _internetConnectionLabelHidden:Bool!; fileprivate var internetConnectionLabelHidden:Bool { set { if (_internetConnectionLabelHidden != newValue) { _internetConnectionLabelHidden = newValue; var newFrame = self.internetConnectionLbl.frame; if (_internetConnectionLabelHidden == true) { newFrame.origin.y = -(44 + self.statusBarFrameHeight); } else { newFrame.origin.y = 0; self.window?.bringSubviewToFront(self.internetConnectionLbl); } UIView.animate(withDuration: 0.35, animations: { () -> Void in self.internetConnectionLbl.frame = newFrame; }); } } get { return (_internetConnectionLabelHidden == nil) ?true:_internetConnectionLabelHidden; } } //P.E. /// Holding a collection fo weak delegate instances private var _delegates:NSHashTable<Weak<ReachabilityDelegate>> = NSHashTable(); //MARK: - setupReachability public func setupReachability() { _reachability = NetworkReachabilityManager(); _reachability!.startListening(onUpdatePerforming: reachabilityUpdate); } //F.E. func reachabilityUpdate(_ status:NetworkReachabilityManager.NetworkReachabilityStatus) { print("status : \(status)") switch status { case .notReachable: //Show error state self.internetConnected = false; break; case .reachable(_), .unknown: //Hide error state self.internetConnected = true; break; } //Calling Delegate Methods let enumerator:NSEnumerator = self._delegates.objectEnumerator(); while let wTarget:Weak<ReachabilityDelegate> = enumerator.nextObject() as? Weak<ReachabilityDelegate> { wTarget.value?.reachabilityDidUpdate?(self.internetConnected); } } //F.E. @objc func internetConnectionLabelTapHandler(_ btn:AnyObject) { self.internetConnectionLabelHidden = true; } //F.E. /** Registers delegate targets. It may register multiple targets. */ public func registerDelegate(_ target:ReachabilityDelegate) { if self.weakDelegateForTarget(target) == nil { //Adding if not added _delegates.add(Weak<ReachabilityDelegate>(value: target)) } } //F.E. /** Unregisters a delegate target. It should be called when, the target does not want to reveice application events. */ public func unregisterDelegate(_ target:ReachabilityDelegate) { if let wTarget:Weak<ReachabilityDelegate> = self.weakDelegateForTarget(target) { _delegates.remove(wTarget); } } //F.E. /// Retrieving weak instance of a given target /// /// - Parameter target: GISTApplicationDelegate /// - Returns: an optional weak target of a target (e.g. Weak<GISTApplicationDelegate>?). private func weakDelegateForTarget(_ target:ReachabilityDelegate) -> Weak<ReachabilityDelegate>?{ let instances = _delegates.allObjects; for i:Int in 0 ..< instances.count { let wTarget:Weak<ReachabilityDelegate> = instances[i]; if (wTarget.value == nil) { //Removing if lost target already _delegates.remove(wTarget); } else if ((target as AnyObject).isEqual(wTarget.value)) { return wTarget; } } return nil; } //F.E. } //CLS END
agpl-3.0
5fe8596150a881afdcfa8f5dd0f09af9
33.724138
168
0.596255
5.6392
false
false
false
false
iXieYi/Weibo_DemoTest
Weibo_DemoTest/Weibo_DemoTest/Common.swift
1
1188
// // Common.swift // Weibo_DemoTest // // Created by 谢毅 on 16/12/13. // Copyright © 2016年 xieyi. All rights reserved. // /// 目的:提供全局共享属性、方法,类似于pch文件 import UIKit /// MARK:- 全局通知定义 //切换根视图控制器通知 - 一定要与系统区别,一定要有前缀 let WBSwitchRootViewControllerNotification = "WBSwitchRootViewControllerNotification" //选中照片的通知 let WBStatusSelectPhotoNotification = "WBStatusSelectPhotoNotification" /// 选中照片的KEY -indexpath let WBStatusSelectPhotoIndexPath = "WBStatusSelectPhotoIndexPath" /// 图片数组 - url数组 let WBStatusSelectPhotoUrlKey = "WBStatusSelectPhotoUrlKey" //全局外观渲染颜色->延展出皮肤的管理类, let WBAppearanceTintColor = UIColor.orangeColor() ///MARK:-全局函数 /// 延迟在主线程执行的函数 /// /// - parameter delta: 延迟时间 /// - parameter callFunc: 要执行的闭包 func delay(delta:Double,callFunc:()->()){ //延迟方法 dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(delta * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { callFunc() } }
mit
8c3d4ae58a9eda6c6f7a88e851d04431
22.170732
85
0.714436
3.329825
false
false
false
false
ChangweiZhang/lovenote
source/lovenote/AppDelegate.swift
1
4102
// // AppDelegate.swift // lovenote // // Created by 张昌伟 on 15/9/26. // Copyright © 2015年 changwei. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //umeng service configure MobClick.startWithAppkey("54673ab3fd98c519b1000dc4", reportPolicy: BATCH, channelId: nil) let version=NSBundle.mainBundle().infoDictionary as NSDictionary! MobClick.setAppVersion(version.objectForKey("CFBundleShortVersionString") as! String) UMSocialData.setAppKey("54673ab3fd98c519b1000dc4") UMSocialWechatHandler.setWXAppId("wx6f6cad81064db3c6", appSecret: "ba0173a81ed02db7ec6e97eed032e5fb", url: "http://9std.net") UMSocialSinaHandler.openSSOWithRedirectURL("http://sns.whalecloud.com/sina2/callback") UMSocialConfig.hiddenNotInstallPlatforms([UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline]) UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green: 102.0/255.0, blue: 204.0/255.0, alpha: 1) UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UINavigationBar.appearance().barStyle = .BlackTranslucent //change app theme UINavigationBar.appearance().backIndicatorImage = UIImage(named: "Back") UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -64), forBarMetrics: UIBarMetrics.Default) UIBarButtonItem.appearance().tintColor = UIColor.whiteColor() // UITabBar.appearance().itemPositioning = UITabBarItemPositioning.Fill //UITabBarItem.appearance().imageInsets = UIEdgeInsets(top: 9, left: 0, bottom: -9, right: 0) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return UMSocialSnsService.handleOpenURL(url) } func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { return UMSocialSnsService.handleOpenURL(url) } }
mit
0970e8b91146f243b55bc060eb79eca8
52.855263
285
0.743464
5.078164
false
false
false
false
vnu/vTweetz
Pods/SwiftDate/SwiftDate_src/DateInRegion+Equations.swift
2
2315
// // SwiftDate, an handy tool to manage date and timezones in swift // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Equations extension DateInRegion: Equatable {} /// Returns true when the given date is equal to the receiver. /// Just the dates are compared. Calendars, time zones are irrelevant. /// /// - Parameters: /// - date: a date to compare against /// /// - Returns: a boolean indicating whether the receiver is equal to the given date /// public func ==(left: DateInRegion, right: DateInRegion) -> Bool { // Compare the content, first the date guard left.absoluteTime.isEqualToDate(right.absoluteTime) else { return false } // Then the calendar guard left.calendar.calendarIdentifier == right.calendar.calendarIdentifier else { return false } // Then the time zone guard left.timeZone.secondsFromGMTForDate(left.absoluteTime) == right.timeZone.secondsFromGMTForDate(right.absoluteTime) else { return false } // Then the locale guard left.locale.localeIdentifier == right.locale.localeIdentifier else { return false } // We have made it! They are equal! return true }
apache-2.0
1ead0a8cbaad967b7df9ca58d3b02505
34.615385
131
0.72743
4.443378
false
false
false
false
dflax/amazeballs
Legacy Versions/Swift 3.x Version/AmazeBalls/BallScene.swift
1
7082
// // BallScene.swift // AmazeBalls // // Created by Daniel Flax on 5/18/15. // Copyright (c) 2015 Daniel Flax. All rights reserved. // // The MIT License (MIT) // // 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 SpriteKit import CoreMotion class BallScene: SKScene, SKPhysicsContactDelegate { var contentCreated : Bool! var currentGravity : Float! var activeBall : Int! var bouncyness : Float! var boundingWall : Bool! var accelerometerSetting: Bool! let motionManager: CMMotionManager = CMMotionManager() required init?(coder aDecoder: NSCoder) { fatalError("init(coder) is not used in this app") } override init(size: CGSize) { super.init(size: size) } override func didMove(to view: SKView) { // Set the overall physicsWorld and outer wall characteristics physicsWorld.contactDelegate = self physicsBody?.categoryBitMask = CollisionCategories.EdgeBody // Load the brickwall background let wallTexture = SKTexture(imageNamed: "brickwall") let wallSprite = SKSpriteNode(texture: wallTexture) wallSprite.size = ScreenSize wallSprite.position = ScreenCenter wallSprite.zPosition = -10 self.addChild(wallSprite) // Load the floor for the bottom of the scene let floor = Floor() floor.zPosition = 100 self.addChild(floor) updateWorldPhysicsSettings() } override func touchesBegan(_ touches: Set<NSObject>, with event: UIEvent) { // Go though all touch points in the set for touch in (touches as! Set<UITouch>) { let location = touch.location(in: self) // If it's not already a ball, drop a new ball at that location self.addChild(Ball(location: location, ballType: activeBall, bouncyness: CGFloat(bouncyness))) if touch.tapCount == 2 { self.stopBalls() } } } //MARK: - Detect Collisions and Handle // SKPhysicsContactDelegate - to handle collisions between objects func didBegin(_ contact: SKPhysicsContact) { var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // Check if the collision is between Ball and Floor if ((firstBody.categoryBitMask & CollisionCategories.Ball != 0) && (secondBody.categoryBitMask & CollisionCategories.Floor != 0)) { // Ball and Floor collided // println("Ball and Floor collided") } // Checck if the collision is between Ball and Floor if ((firstBody.categoryBitMask & CollisionCategories.Ball != 0) && (secondBody.categoryBitMask & CollisionCategories.EdgeBody != 0)) { // println("Ball and wall collide") } } // Stop all balls from moving func stopBalls() { self.enumerateChildNodes(withName: "ball") { node, stop in node.speed = 0 } } // Use to remove any balls that have fallen off the screen override func update(_ currentTime: TimeInterval) { } // Loop through all ballNodes, and execute the passed in block if they've falled more than 500 points below the screen, they aren't coming back. override func didSimulatePhysics() { self.enumerateChildNodes(withName: "ball") { node, stop in if node.position.y < -500 { node.removeFromParent() } } } //MARK: - Settings for the Physics World // This is the main method to update the physics for the scene based on the settings the user has entered on the Settings View. func updateWorldPhysicsSettings() { // Grab the standard user defaults handle let userDefaults = UserDefaults.standard // Pull values for the different settings. Substitute in defaults if the NSUserDefaults doesn't include any value currentGravity = userDefaults.value(forKey: "gravityValue") != nil ? -1*abs(userDefaults.value(forKey: "gravityValue") as! Float) : -9.8 activeBall = userDefaults.value(forKey: "activeBall") != nil ? userDefaults.value(forKey: "activeBall") as! Int : 2000 bouncyness = userDefaults.value(forKey: "bouncyness") != nil ? userDefaults.value(forKey: "bouncyness") as! Float : 0.5 boundingWall = userDefaults.value(forKey: "boundingWallSetting") != nil ? userDefaults.value(forKey: "boundingWallSetting") as! Bool : false accelerometerSetting = userDefaults.value(forKey: "accelerometerSetting") != nil ? userDefaults.value(forKey: "accelerometerSetting") as! Bool : false // If no Accelerometer, set the simple gravity for the world if (!accelerometerSetting) { physicsWorld.gravity = CGVector(dx: 0.0, dy: CGFloat(currentGravity)) // In case it's on, turn off the accelerometer motionManager.stopAccelerometerUpdates() } else { // Turn on the accelerometer to handle setting the gravityself startComplexGravity() } // Loop through all balls and update their bouncyness values self.enumerateChildNodes(withName: "ball") { node, stop in node.physicsBody?.restitution = CGFloat(self.bouncyness) } // Set whether there is a bounding wall (edge loop) around the frame if boundingWall == true { self.physicsBody = SKPhysicsBody(edgeLoopFrom: ScreenRect) } else { self.physicsBody = nil } } //MARK: - Accelerate Framework Methods // If the user selects to have the accelerometer active, complex gravity must be calculated whenever the Core Motion delegate is called func startComplexGravity() { // Check if the accelerometer is available if (motionManager.isAccelerometerAvailable) { motionManager.startAccelerometerUpdates(to: OperationQueue()) { (data, error) in // Take the x and y acceleration vectors and multiply by the gravity values to come up with a full gravity vector let xGravity = CGFloat((data?.acceleration.x)!) * CGFloat(self.currentGravity) let yGravity = CGFloat((data?.acceleration.y)!) * CGFloat(self.currentGravity) self.physicsWorld.gravity = CGVector(dx: yGravity, dy: -xGravity) } } } }
mit
b9659c0656c9768f7493b24091d963b4
34.58794
154
0.719288
4.14152
false
false
false
false
aamct2/MCTDataStructures
Sources/MCTDataStructures/MCTDeque.swift
1
8492
// // MCTDeque.swift // MCTDataStructures // // Created by opensource on 8/19/15. // Copyright © 2015 Aaron McTavish. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Generic implementation of a double-ended queue collection. public struct MCTDeque<Element: CustomStringConvertible>: CustomStringConvertible, Sequence { // MARK: - Properties /// Underlying container (array) representation of deque. fileprivate var items = [Element]() /// The number of elements in the deque. public var size: Int { return items.count } /// Test whether the deque is empty. public var empty: Bool { return items.isEmpty } // MARK: - Initializers public init() {} // MARK: - C++11 Functions /** Remove the last element of the deque. - returns: The last element of the deque, if it exists. */ public mutating func pop_back() -> Element? { if empty { return nil } return items.remove(at: size - 1) } /** Remove the first element of the deque. - returns: The first element of the deque, if it exists. */ public mutating func pop_front() -> Element? { if empty { return nil } return items.remove(at: 0) } /** Insert element at the end of the deque. - parameter newObject: Element to push onto the deque. */ public mutating func push_back(_ newObject: Element) { items.append(newObject) } /** Insert element at the beginning of the deque. - parameter newObject: Element to push onto the deque. */ public mutating func push_front(_ newObject: Element) { items.insert(newObject, at: 0) } /** Access the next element of the deque without removing it. - returns: The next element of the deque, if it exists. */ public func front() -> Element? { if empty { return nil } return items[0] } /** Access the last element of the deque without removing it. - returns: The last element of the deque, if it exists. */ public func back() -> Element? { if empty { return nil } return items[size - 1] } /** Removes all elements from the deque. */ public mutating func clear() { items.removeAll() } /** Removes an element at a specific index. - parameter index: Index at which to remove the element. */ public mutating func erase(_ index: Int) { guard index >= 0 && index < size else { return } items.remove(at: index) } /** Removes a range of elements inclusive of the `startIndex` and exclusive of the `endIndex`. Effectively, it is the range [`startIndex`, `endIndex`). - parameter startIndex: Index of first object to remove. - parameter endIndex: Index after the last object to remove. */ public mutating func erase(_ startIndex: Int, endIndex: Int) { guard startIndex >= 0 && startIndex < size && endIndex > startIndex && endIndex <= size else { return } items.removeSubrange(startIndex ..< endIndex) } } // MARK: - Additional Convenience Functions public extension MCTDeque { /// A text representation of the deque. public var description: String { var result = "" for curObject in items { result += "::\(curObject)" } return result } /** Returns a `MCTDeque` containing the elements of `self` in reverse order. - returns: A `MCTDeque` containing the elements of `self` in reverse order. */ public func reverseDeque() -> MCTDeque<Element> { var newDeque = MCTDeque<Element>() newDeque.items = items.reversed() return newDeque } /** Returns the deque as an array object. - returns: Array representation of the deque. */ public func dequeAsArray() -> [Element] { return items } /// Return a *generator* over the elements. /// /// - Complexity: O(1). public func makeIterator() -> MCTDequeGenerator<Element> { return MCTDequeGenerator<Element>(items: items[0 ..< items.count]) } } // MARK: - Deque Generator Type public struct MCTDequeGenerator<Element> : IteratorProtocol { public mutating func next() -> Element? { if items.isEmpty { return nil } let ret = items.first items.removeFirst() return ret } var items: ArraySlice<Element> } // MARK: - Relational Operators for Deques /** Returns true if these deques contain the same elements. - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: True if these deques contain the same elements. Otherwise returns false. */ public func ==<Element: Equatable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { guard lhs.size == rhs.size else { return false } for index in 0 ..< lhs.size where lhs.items[index] != rhs.items[index] { return false } return true } /** Returns result of equivalent operation !(lhs == rhs). - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: Returns result of equivalent operation !(lhs == rhs). */ public func !=<Element: Equatable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { return !(lhs == rhs) } /** Compares elements sequentially using operator< and stops at the first occurance where a<b or b<a. - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: Returns true if the first element in which the deques differ, the left hand element is less than the right hand element. Otherwise returns false. */ public func <<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { for index in 0 ..< lhs.size { if index >= rhs.size { return false } if lhs.items[index] < rhs.items[index] { return true } else if rhs.items[index] < lhs.items[index] { return false } } return false } /** Returns result of equivalent operation rhs < lhs. - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: Returns result of equivalent operation rhs < lhs. */ public func ><Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { return rhs < lhs } /** Returns result of equivalent operation !(rhs < lhs). - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: Returns result of equivalent operation !(rhs < lhs). */ public func <=<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { return !(rhs < lhs) } /** Returns result of equivalent operation !(lhs < rhs). - parameter lhs: The left-hand deque. - parameter rhs: The right-hand deque. - returns: Returns result of equivalent operation !(lhs < rhs). */ public func >=<Element: Comparable>(lhs: MCTDeque<Element>, rhs: MCTDeque<Element>) -> Bool { return !(lhs < rhs) }
mit
da75a8d002cbed73b65c1b6220269f6c
25.785489
97
0.623955
4.466597
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/FindInPageBar.swift
1
7317
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared protocol FindInPageBarDelegate: AnyObject { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) func findInPageDidPressClose(_ findInPage: FindInPageBar) } private struct FindInPageUX { static let ButtonColor = UIColor.black static let MatchCountColor = UIColor.Photon.Grey40 static let MatchCountFont = UIConstants.DefaultChromeFont static let SearchTextColor = UIColor.Photon.Orange60 static let SearchTextFont = UIConstants.DefaultChromeFont static let TopBorderColor = UIColor.Photon.Grey20 } class FindInPageBar: UIView { weak var delegate: FindInPageBarDelegate? fileprivate let searchText = UITextField() fileprivate let matchCountView = UILabel() fileprivate let previousButton = UIButton() fileprivate let nextButton = UIButton() var currentResult = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } } } var totalResults = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } previousButton.isEnabled = totalResults > 1 nextButton.isEnabled = previousButton.isEnabled } } var text: String? { get { return searchText.text } set { searchText.text = newValue didTextChange(searchText) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white searchText.addTarget(self, action: #selector(didTextChange), for: .editingChanged) searchText.textColor = FindInPageUX.SearchTextColor searchText.font = FindInPageUX.SearchTextFont searchText.autocapitalizationType = .none searchText.autocorrectionType = .no searchText.inputAssistantItem.leadingBarButtonGroups = [] searchText.inputAssistantItem.trailingBarButtonGroups = [] searchText.enablesReturnKeyAutomatically = true searchText.returnKeyType = .search searchText.accessibilityIdentifier = "FindInPage.searchField" searchText.delegate = self addSubview(searchText) matchCountView.textColor = FindInPageUX.MatchCountColor matchCountView.font = FindInPageUX.MatchCountFont matchCountView.isHidden = true matchCountView.accessibilityIdentifier = "FindInPage.matchCount" addSubview(matchCountView) previousButton.setImage(UIImage(named: "find_previous"), for: []) previousButton.setTitleColor(FindInPageUX.ButtonColor, for: []) previousButton.accessibilityLabel = .FindInPagePreviousAccessibilityLabel previousButton.addTarget(self, action: #selector(didFindPrevious), for: .touchUpInside) previousButton.accessibilityIdentifier = "FindInPage.find_previous" addSubview(previousButton) nextButton.setImage(UIImage(named: "find_next"), for: []) nextButton.setTitleColor(FindInPageUX.ButtonColor, for: []) nextButton.accessibilityLabel = .FindInPageNextAccessibilityLabel nextButton.addTarget(self, action: #selector(didFindNext), for: .touchUpInside) nextButton.accessibilityIdentifier = "FindInPage.find_next" addSubview(nextButton) let closeButton = UIButton() closeButton.setImage(UIImage(named: "find_close"), for: []) closeButton.setTitleColor(FindInPageUX.ButtonColor, for: []) closeButton.accessibilityLabel = .FindInPageDoneAccessibilityLabel closeButton.addTarget(self, action: #selector(didPressClose), for: .touchUpInside) closeButton.accessibilityIdentifier = "FindInPage.close" addSubview(closeButton) let topBorder = UIView() topBorder.backgroundColor = FindInPageUX.TopBorderColor addSubview(topBorder) searchText.snp.makeConstraints { make in make.leading.top.bottom.equalTo(self).inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)) } searchText.setContentHuggingPriority(.defaultLow, for: .horizontal) searchText.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) matchCountView.snp.makeConstraints { make in make.leading.equalTo(searchText.snp.trailing) make.centerY.equalTo(self) } matchCountView.setContentHuggingPriority(.defaultHigh, for: .horizontal) matchCountView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) previousButton.snp.makeConstraints { make in make.leading.equalTo(matchCountView.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } nextButton.snp.makeConstraints { make in make.leading.equalTo(previousButton.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } closeButton.snp.makeConstraints { make in make.leading.equalTo(nextButton.snp.trailing) make.size.equalTo(self.snp.height) make.trailing.centerY.equalTo(self) } topBorder.snp.makeConstraints { make in make.height.equalTo(1) make.left.right.top.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult override func becomeFirstResponder() -> Bool { searchText.becomeFirstResponder() return super.becomeFirstResponder() } @objc fileprivate func didFindPrevious(_ sender: UIButton) { delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "") } @objc fileprivate func didFindNext(_ sender: UIButton) { delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "") } @objc fileprivate func didTextChange(_ sender: UITextField) { matchCountView.isHidden = searchText.text?.trimmingCharacters(in: .whitespaces).isEmpty ?? true delegate?.findInPage(self, didTextChange: searchText.text ?? "") } @objc fileprivate func didPressClose(_ sender: UIButton) { delegate?.findInPageDidPressClose(self) } } extension FindInPageBar: UITextFieldDelegate { // Keyboard with a .search returnKeyType doesn't dismiss when return pressed. Handle this manually. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { textField.resignFirstResponder() return false } return true } }
mpl-2.0
03ae2994a4d5ee9478a12ed845b4bc48
38.128342
129
0.679923
5.356515
false
false
false
false
Pstoppani/swipe
network/SwipePrefetcher.swift
2
5404
// // SwipePrefetcher.swift // sample // // Created by satoshi on 10/12/15. // Copyright © 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) import Cocoa #else import UIKit #endif private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { NSLog(text) } } class SwipePrefetcher { private var urls = [URL:String]() private var urlsFetching = [URL]() private var urlsFetched = [URL:URL]() private var urlsFailed = [URL]() private var errors = [NSError]() private var fComplete = false private var _progress = Float(0) var progress:Float { return _progress } init(urls:[URL:String]) { self.urls = urls } func start(_ callback:@escaping (Bool, [URL], [NSError]) -> Void) { if fComplete { MyLog("SWPrefe already completed", level:1) callback(true, self.urlsFailed, self.errors) return } let manager = SwipeAssetManager.sharedInstance() var count = 0 _progress = 0 let fileManager = FileManager.default for (url,prefix) in urls { if url.scheme == "file" { if fileManager.fileExists(atPath: url.path) { urlsFetched[url] = url } else { // On-demand resource support urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil) MyLog("SWPrefe onDemand resource at \(urlsFetched[url]) instead of \(url)", level:1) } } else { count += 1 urlsFetching.append(url) manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in if let urlL = urlLocal { self.urlsFetched[url] = urlL } else { self.urlsFailed.append(url) if let error = error { self.errors.append(error) } } count -= 1 if (count == 0) { self.fComplete = true self._progress = 1 MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1) callback(true, self.urlsFailed, self.errors) } else { self._progress = Float(self.urls.count - count) / Float(self.urls.count) callback(false, self.urlsFailed, self.errors) } }) } } if count == 0 { self.fComplete = true self._progress = 1 callback(true, urlsFailed, errors) } } func append(_ urls:[URL:String], callback:@escaping (Bool, [URL], [NSError]) -> Void) { let manager = SwipeAssetManager.sharedInstance() var count = 0 _progress = 0 let fileManager = FileManager.default for (url,prefix) in urls { self.urls[url] = prefix if url.scheme == "file" { if fileManager.fileExists(atPath: url.path) { urlsFetched[url] = url } else { // On-demand resource support urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil) MyLog("SWPrefe onDemand resource at \(urlsFetched[url]) instead of \(url)", level:1) } } else { count += 1 urlsFetching.append(url) manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in if let urlL = urlLocal { self.urlsFetched[url] = urlL } else if let error = error { self.urlsFailed.append(url) self.errors.append(error) } count -= 1 if (count == 0) { self.fComplete = true self._progress = 1 MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1) callback(true, self.urlsFailed, self.errors) } else { self._progress = Float(self.urls.count - count) / Float(self.urls.count) callback(false, self.urlsFailed, self.errors) } }) } } if count == 0 { self.fComplete = true self._progress = 1 callback(true, urlsFailed, errors) } } func map(_ url:URL) -> URL? { return urlsFetched[url] } static func extensionForType(_ memeType:String) -> String { let ext:String if memeType == "video/quicktime" { ext = ".mov" } else if memeType == "video/mp4" { ext = ".mp4" } else { ext = "" } return ext } static func isMovie(_ mimeType:String) -> Bool { return mimeType == "video/quicktime" || mimeType == "video/mp4" } }
mit
75b7620cdf008cda1196360ac120226f
33.858065
128
0.481029
4.876354
false
false
false
false
nathawes/swift
test/decl/protocol/special/coding/Inputs/struct_codable_simple_multi1.swift
12
957
// RUN: %target-typecheck-verify-swift // Simple structs with all Codable properties should get derived conformance to // Codable. struct SimpleStruct : Codable { var x: Int var y: Double static var z: String = "foo" // These lines have to be within the SimpleStruct type because CodingKeys // should be private. func foo() { // They should receive a synthesized CodingKeys enum. let _ = SimpleStruct.CodingKeys.self // The enum should have a case for each of the vars. let _ = SimpleStruct.CodingKeys.x let _ = SimpleStruct.CodingKeys.y // Static vars should not be part of the CodingKeys enum. let _ = SimpleStruct.CodingKeys.z // expected-error {{type 'SimpleStruct.CodingKeys' has no member 'z'}} } } // SR-13137 Ensure unqualified lookup installs CodingKeys regardless of the // order of primaries. struct A: Codable { var property: String static let propertyName = CodingKeys.property.stringValue }
apache-2.0
1f353a0aec20e5ee9ee0f1d8383a5541
29.870968
108
0.718913
4.35
false
false
false
false
tdgunes/Polly
Polly/Polly/BeaconService.swift
1
1855
// // BeaconService.swift // Polly // // Created by Taha Doğan Güneş on 29/06/15. // Copyright (c) 2015 Taha Doğan Güneş. All rights reserved. // import Foundation class BeaconService { var nkit = NetKit() var onSuccessCallback: (([Beacon])->())? var onErrorCallback: (()->())? init(successCallback: (([Beacon])->())? = nil, errorCallback: (()->())? = nil) { self.onSuccessCallback = successCallback self.onErrorCallback = errorCallback } func setURL(url:String){ nkit.baseURL = url if !IS_TARGET_IPHONE_SIMULATOR { nkit.baseURL = url.stringByReplacingOccurrencesOfString("127.0.0.1", withString: "192.168.1.109") } } func fetchBeacons(){ let apiMethod = "/api/beacons" nkit.get(url: apiMethod, completionHandler: self.onSuccess, errorHandler: self.onError) } func onError(nkerror:NKError, nserror:NSError?) { println("\(nkerror): \(nserror)") if let callback = self.onErrorCallback { callback() } } func onSuccess(response:NKResponse) { println(response.string!) var beacons:[Beacon] = [] if let callback = self.onSuccessCallback, let json = response.json, let jsonArray = json.asArray { for jsonObject in jsonArray { if let name = jsonObject["name"].asString, let uuid = jsonObject["uuid"].asString { var beacon = Beacon(name: name, uuid: uuid) beacons.append(beacon) } } callback(beacons) } } }
gpl-3.0
3a0f47733b4122aa44d5da642962a734
26.191176
109
0.507842
4.853018
false
false
false
false
takev/DimensionsCAM
DimensionsCAM/OpenSCADCSGParser.swift
1
10445
// DimensionsCAM - A multi-axis tool path generator for a milling machine // Copyright (C) 2015 Take Vos // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import simd struct OpenSCADCSGParser { var grammar: OpenSCADCSGGrammar init(text: String, filename: String) { grammar = OpenSCADCSGGrammar(text: text, filename: filename) } /// A group is not really a node, and simply returns the one child node it contains. func parseGroupFunction(ast: OpenSCADCSGAST, child_objects: [CSGObject]) throws -> CSGObject { guard child_objects.count == 1 else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Multimatrix does not have exactly 1 child") } return child_objects[0] } /// A union function combines all children. func parseUnionFunction(ast: OpenSCADCSGAST, child_objects: [CSGObject]) throws -> CSGObject { let parent = CSGUnion() for child in child_objects { parent.addChild(child) } return parent } /// A intersection function takes only the overalp of all children. func parseIntersectionFunction(ast: OpenSCADCSGAST, child_objects: [CSGObject]) throws -> CSGObject { let parent = CSGIntersection() for child in child_objects { parent.addChild(child) } return parent } /// A difference function removes 2 to n children from child 1. func parseDifferenceFunction(ast: OpenSCADCSGAST, child_objects: [CSGObject]) throws -> CSGObject { let parent = CSGDifference() for child in child_objects { parent.addChild(child) } return parent } func getArgument(arguments_node: OpenSCADCSGAST, name: String = "", index: Int = -1) throws -> OpenSCADCSGAST { guard case .BRANCH(let type, let argument_nodes) = arguments_node where type == "arguments" else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(arguments_node, "Expect a 'arguments' branch.") } var i = 0 for argument_node in argument_nodes { guard case .BRANCH(let type, let name_value_nodes) = argument_node where type == "argument" && name_value_nodes.count == 2 else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(argument_node, "Expecting 'argument' node with 2 childs") } let name_node = name_value_nodes[0] let value_node = name_value_nodes[1] switch (name_node) { case .NULL: if i == index { return value_node } case .LEAF_NAME(let leaf_name): if leaf_name == name { return value_node } default: throw OpenSCADCSGError.UNEXPECTED_ASTNODE(name_node, "Expecting NULL or Name") } i++ } throw OpenSCADCSGError.UNEXPECTED_ASTNODE(.NULL, "Could not find argument of '\(name)'") } func getBooleanArgument(arguments_node: OpenSCADCSGAST, name: String = "", index: Int = -1) throws -> Bool { let value_node = try getArgument(arguments_node, name: name, index: index) if case .LEAF_BOOLEAN(let value) = value_node { return value } else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(value_node, "Expecting boolean leaf node.") } } func getNumberArgument(arguments_node: OpenSCADCSGAST, name: String = "", index: Int = -1) throws -> Double { let value_node = try getArgument(arguments_node, name: name, index: index) if case .LEAF_NUMBER(let value) = value_node { return value } else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(value_node, "Expecting number leaf node.") } } func getVectorArgument(arguments_node: OpenSCADCSGAST, name: String = "", index: Int = -1) throws -> double4 { let value_node = try getArgument(arguments_node, name: name, index: index) if case .LEAF_VECTOR(let value) = value_node { return value } else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(value_node, "Expecting vector leaf node.") } } func getMatrixArgument(arguments_node: OpenSCADCSGAST, name: String = "", index: Int = -1) throws -> double4x4 { let value_node = try getArgument(arguments_node, name: name, index: index) if case .LEAF_MATRIX(let value) = value_node { return value } else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(value_node, "Expecting matrix leaf node.") } } func parseCubeFunction(ast: OpenSCADCSGAST, arguments_node: OpenSCADCSGAST) throws -> CSGObject { let size = try getVectorArgument(arguments_node, name:"size") let center = try getBooleanArgument(arguments_node, name:"center") let object = CSGBox(size:size.xyz) if !center { // Move the cube which is normally has its center on the origin to having its corner on the origin. // Just move it half of its own size. object.localTransformations.insert(double4x4(translate:size * 0.5), atIndex:0) } return object } func parseCylinderFunction(ast: OpenSCADCSGAST, arguments_node: OpenSCADCSGAST) throws -> CSGObject { var d1: Double var d2: Double if let r1 = try? getNumberArgument(arguments_node, name:"r1") { d1 = r1 * 2.0 } else { d1 = try getNumberArgument(arguments_node, name:"d1") } if let r2 = try? getNumberArgument(arguments_node, name:"r2") { d2 = r2 * 2.0 } else { d2 = try getNumberArgument(arguments_node, name:"d2") } let h = try getNumberArgument(arguments_node, name:"h") let center = try getBooleanArgument(arguments_node, name:"center") let object = CSGCappedCone(height: h, diameter_bottom: d1, diameter_top: d2) if !center { // Move the cylinder which is normally has its center on the origin to having its bottom cap's center on the origin. // Just move it half of its height. object.localTransformations.insert(double4x4(translate:double4(0.0, 0.0, h * 0.5, 0.0)), atIndex:0) } return object } func parseSphereFunction(ast: OpenSCADCSGAST, arguments_node: OpenSCADCSGAST) throws -> CSGObject { var d: Double if let r = try? getNumberArgument(arguments_node, name:"r") { d = r * 2.0 } else { d = try getNumberArgument(arguments_node, name:"d") } let size = double3(d, d, d) return CSGElipsoid(size:size) } /// A multmatrix modifies its single child node. func parseMultmatrixFunction(ast: OpenSCADCSGAST, child_objects: [CSGObject], arguments_node: OpenSCADCSGAST) throws -> CSGObject { guard child_objects.count == 1 else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Multimatrix does not have exactly 1 child") } let child = child_objects[0] let value = try getMatrixArgument(arguments_node, index:0) child.localTransformations.insert(value, atIndex: 0) return child } func parseBlocks(ast: OpenSCADCSGAST) throws -> [CSGObject] { guard case .BRANCH(let type, let block_nodes) = ast where type == "block" else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Expect a 'block' branch.") } // Recurse the blocks. var child_objects: [CSGObject] = [] for block_node in block_nodes { let child_object = try parseFunction(block_node) child_objects.append(child_object) } return child_objects } func parseFunction(ast: OpenSCADCSGAST) throws -> CSGObject { guard case .BRANCH(let type, let children) = ast where type == "function" && children.count == 3 else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Expect a 'function' branch with 3 children.") } let name_node = children[0] let arguments_node = children[1] let block_node = children[2] guard case .LEAF_NAME(let name) = name_node else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(name_node, "Expect a name leaf.") } let child_objects = try parseBlocks(block_node) switch name { case "group": return try parseGroupFunction(ast, child_objects: child_objects) case "multmatrix": return try parseMultmatrixFunction(ast, child_objects: child_objects, arguments_node: arguments_node) case "difference": return try parseDifferenceFunction(ast, child_objects: child_objects) case "union": return try parseUnionFunction(ast, child_objects: child_objects) case "intersection": return try parseIntersectionFunction(ast, child_objects: child_objects) case "cube": return try parseCubeFunction(ast, arguments_node: arguments_node) case "cylinder": return try parseCylinderFunction(ast, arguments_node: arguments_node) case "sphere": return try parseSphereFunction(ast, arguments_node: arguments_node) default: throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Unknown funcion: '\(name)'.") } } mutating func parseProgram() throws -> CSGObject { let ast = try grammar.parseProgram() guard case .BRANCH(let type, let children) = ast where type == "program" && children.count == 1 else { throw OpenSCADCSGError.UNEXPECTED_ASTNODE(ast, "Expect a 'program' branch with 1 child.") } return try parseFunction(children[0]) } }
gpl-3.0
b036d8c82a9f6b941277f36f0c8a8e2f
37.400735
141
0.627573
4.439014
false
false
false
false
oddnetworks/odd-sample-apps
apple/tvos/tvOSSampleApp/tvOSSampleApp/UIView+Parallax.swift
1
1383
// // UIView+Parallax.swift // ParallaxView // // Created by Patrick McConnell on 1/27/16. // Copyright © 2016 Odd Networks. All rights reserved. // import UIKit extension UIView { func addParallaxMotionEffects(_ tiltValue : CGFloat = 0.25, panValue: CGFloat = 5) { var xTilt = UIInterpolatingMotionEffect() var yTilt = UIInterpolatingMotionEffect() var xPan = UIInterpolatingMotionEffect() var yPan = UIInterpolatingMotionEffect() let motionGroup = UIMotionEffectGroup() xTilt = UIInterpolatingMotionEffect(keyPath: "layer.transform.rotation.y", type: .tiltAlongHorizontalAxis) xTilt.minimumRelativeValue = -tiltValue xTilt.maximumRelativeValue = tiltValue yTilt = UIInterpolatingMotionEffect(keyPath: "layer.transform.rotation.x", type: .tiltAlongVerticalAxis) yTilt.minimumRelativeValue = -tiltValue yTilt.maximumRelativeValue = tiltValue xPan = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) xPan.minimumRelativeValue = -panValue xPan.maximumRelativeValue = panValue yPan = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) yPan.minimumRelativeValue = -panValue yPan.maximumRelativeValue = panValue motionGroup.motionEffects = [xTilt, yTilt, xPan, yPan] self.addMotionEffect( motionGroup ) } }
apache-2.0
00b17c564689520fe2da5f17bd60e230
31.904762
110
0.736614
4.832168
false
false
false
false
apple/swift-corelibs-xctest
Sources/XCTest/Public/XCTAssert.swift
1
19913
// 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 // // // XCTAssert.swift // private enum _XCTAssertion { case equal case equalWithAccuracy case identical case notIdentical case greaterThan case greaterThanOrEqual case lessThan case lessThanOrEqual case notEqual case notEqualWithAccuracy case `nil` case notNil case unwrap case `true` case `false` case fail case throwsError case noThrow var name: String? { switch(self) { case .equal: return "XCTAssertEqual" case .equalWithAccuracy: return "XCTAssertEqual" case .identical: return "XCTAssertIdentical" case .notIdentical: return "XCTAssertNotIdentical" case .greaterThan: return "XCTAssertGreaterThan" case .greaterThanOrEqual: return "XCTAssertGreaterThanOrEqual" case .lessThan: return "XCTAssertLessThan" case .lessThanOrEqual: return "XCTAssertLessThanOrEqual" case .notEqual: return "XCTAssertNotEqual" case .notEqualWithAccuracy: return "XCTAssertNotEqual" case .`nil`: return "XCTAssertNil" case .notNil: return "XCTAssertNotNil" case .unwrap: return "XCTUnwrap" case .`true`: return "XCTAssertTrue" case .`false`: return "XCTAssertFalse" case .throwsError: return "XCTAssertThrowsError" case .noThrow: return "XCTAssertNoThrow" case .fail: return nil } } } private enum _XCTAssertionResult { case success case expectedFailure(String?) case unexpectedFailure(Swift.Error) var isExpected: Bool { switch self { case .unexpectedFailure(_): return false default: return true } } func failureDescription(_ assertion: _XCTAssertion) -> String { let explanation: String switch self { case .success: explanation = "passed" case .expectedFailure(let details?): explanation = "failed: \(details)" case .expectedFailure(_): explanation = "failed" case .unexpectedFailure(let error): explanation = "threw error \"\(error)\"" } if let name = assertion.name { return "\(name) \(explanation)" } else { return explanation } } } private func _XCTEvaluateAssertion(_ assertion: _XCTAssertion, message: @autoclosure () -> String, file: StaticString, line: UInt, expression: () throws -> _XCTAssertionResult) { let result: _XCTAssertionResult do { result = try expression() } catch { result = .unexpectedFailure(error) } switch result { case .success: return default: if let currentTestCase = XCTCurrentTestCase { currentTestCase.recordFailure( withDescription: "\(result.failureDescription(assertion)) - \(message())", inFile: String(describing: file), atLine: Int(line), expected: result.isExpected) } } } /// This function emits a test failure if the general `Boolean` expression passed /// to it evaluates to `false`. /// /// - Requires: This and all other XCTAssert* functions must be called from /// within a test method, as passed to `XCTMain`. /// Assertion failures that occur outside of a test method will *not* be /// reported as failures. /// /// - Parameter expression: A boolean test. If it evaluates to `false`, the /// assertion fails and emits a test failure. /// - Parameter message: An optional message to use in the failure if the /// assertion fails. If no message is supplied a default message is used. /// - Parameter file: The file name to use in the error message if the assertion /// fails. Default is the file containing the call to this function. It is /// rare to provide this parameter when calling this function. /// - Parameter line: The line number to use in the error message if the /// assertion fails. Default is the line number of the call to this function /// in the calling file. It is rare to provide this parameter when calling /// this function. /// /// - Note: It is rare to provide the `file` and `line` parameters when calling /// this function, although you may consider doing so when creating your own /// assertion functions. For example, consider the following custom assertion: /// /// ``` /// // AssertEmpty.swift /// /// func AssertEmpty<T>(_ elements: [T]) { /// XCTAssertEqual(elements.count, 0, "Array is not empty") /// } /// ``` /// /// Calling this assertion will cause XCTest to report the failure occurred /// in the file where `AssertEmpty()` is defined, and on the line where /// `XCTAssertEqual` is called from within that function: /// /// ``` /// // MyFile.swift /// /// AssertEmpty([1, 2, 3]) // Emits "AssertEmpty.swift:3: error: ..." /// ``` /// /// To have XCTest properly report the file and line where the assertion /// failed, you may specify the file and line yourself: /// /// ``` /// // AssertEmpty.swift /// /// func AssertEmpty<T>(_ elements: [T], file: StaticString = #file, line: UInt = #line) { /// XCTAssertEqual(elements.count, 0, "Array is not empty", file: file, line: line) /// } /// ``` /// /// Now calling failures in `AssertEmpty` will be reported in the file and on /// the line that the assert function is *called*, not where it is defined. public func XCTAssert(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(try expression(), message(), file: file, line: line) } public func XCTAssertEqual<T: Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.equal, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 == value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is not equal to (\"\(value2)\")") } } } private func areEqual<T: Numeric>(_ exp1: T, _ exp2: T, accuracy: T) -> Bool { // Test with equality first to handle comparing inf/-inf with itself. if exp1 == exp2 { return true } else { // NaN values are handled implicitly, since the <= operator returns false when comparing any value to NaN. let difference = (exp1.magnitude > exp2.magnitude) ? exp1 - exp2 : exp2 - exp1 return difference.magnitude <= accuracy.magnitude } } public func XCTAssertEqual<T: FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTAssertEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } public func XCTAssertEqual<T: Numeric>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTAssertEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } private func _XCTAssertEqual<T: Numeric>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String, file: StaticString, line: UInt) { _XCTEvaluateAssertion(.equalWithAccuracy, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if areEqual(value1, value2, accuracy: accuracy) { return .success } else { return .expectedFailure("(\"\(value1)\") is not equal to (\"\(value2)\") +/- (\"\(accuracy)\")") } } } @available(*, deprecated, renamed: "XCTAssertEqual(_:_:accuracy:file:line:)") public func XCTAssertEqualWithAccuracy<T: FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } private func describe(_ object: AnyObject?) -> String { return object == nil ? String(describing: object) : String(describing: object!) } /// Asserts that two values are identical. public func XCTAssertIdentical(_ expression1: @autoclosure () throws -> AnyObject?, _ expression2: @autoclosure () throws -> AnyObject?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.identical, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 === value2 { return .success } else { return .expectedFailure("(\"\(describe(value1))\") is not identical to (\"\(describe(value2))\")") } } } /// Asserts that two values aren't identical. public func XCTAssertNotIdentical(_ expression1: @autoclosure () throws -> AnyObject?, _ expression2: @autoclosure () throws -> AnyObject?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.notIdentical, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 !== value2 { return .success } else { return .expectedFailure("(\"\(describe(value1))\") is identical to (\"\(describe(value2))\")") } } } public func XCTAssertFalse(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.`false`, message: message(), file: file, line: line) { let value = try expression() if !value { return .success } else { return .expectedFailure(nil) } } } public func XCTAssertGreaterThan<T: Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.greaterThan, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 > value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is not greater than (\"\(value2)\")") } } } public func XCTAssertGreaterThanOrEqual<T: Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.greaterThanOrEqual, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 >= value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is less than (\"\(value2)\")") } } } public func XCTAssertLessThan<T: Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.lessThan, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 < value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is not less than (\"\(value2)\")") } } } public func XCTAssertLessThanOrEqual<T: Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.lessThanOrEqual, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 <= value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is greater than (\"\(value2)\")") } } } public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.`nil`, message: message(), file: file, line: line) { let value = try expression() if value == nil { return .success } else { return .expectedFailure("\"\(value!)\"") } } } public func XCTAssertNotEqual<T: Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.notEqual, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if value1 != value2 { return .success } else { return .expectedFailure("(\"\(value1)\") is equal to (\"\(value2)\")") } } } public func XCTAssertNotEqual<T: FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTAssertNotEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } public func XCTAssertNotEqual<T: Numeric>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTAssertNotEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } private func _XCTAssertNotEqual<T: Numeric>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String, file: StaticString, line: UInt) { _XCTEvaluateAssertion(.notEqualWithAccuracy, message: message(), file: file, line: line) { let (value1, value2) = (try expression1(), try expression2()) if !areEqual(value1, value2, accuracy: accuracy) { return .success } else { return .expectedFailure("(\"\(value1)\") is equal to (\"\(value2)\") +/- (\"\(accuracy)\")") } } } @available(*, deprecated, renamed: "XCTAssertNotEqual(_:_:accuracy:file:line:)") public func XCTAssertNotEqualWithAccuracy<T: FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertNotEqual(try expression1(), try expression2(), accuracy: accuracy, message(), file: file, line: line) } public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.notNil, message: message(), file: file, line: line) { let value = try expression() if value != nil { return .success } else { return .expectedFailure(nil) } } } /// Asserts that an expression is not `nil`, and returns its unwrapped value. /// /// Generates a failure if `expression` returns `nil`. /// /// - Parameters: /// - expression: An expression of type `T?` to compare against `nil`. Its type will determine the type of the /// returned value. /// - message: An optional description of the failure. /// - file: The file in which failure occurred. Defaults to the file name of the test case in which this function was /// called. /// - line: The line number on which failure occurred. Defaults to the line number on which this function was called. /// - Returns: A value of type `T`, the result of evaluating and unwrapping the given `expression`. /// - Throws: An error if `expression` returns `nil`. If `expression` throws an error, then that error will be rethrown instead. public func XCTUnwrap<T>(_ expression: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) throws -> T { var value: T? var caughtErrorOptional: Swift.Error? _XCTEvaluateAssertion(.unwrap, message: message(), file: file, line: line) { do { value = try expression() } catch { caughtErrorOptional = error return .unexpectedFailure(error) } if value != nil { return .success } else { return .expectedFailure("expected non-nil value of type \"\(T.self)\"") } } if let unwrappedValue = value { return unwrappedValue } else if let error = caughtErrorOptional { throw error } else { throw XCTestErrorWhileUnwrappingOptional() } } public func XCTAssertTrue(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.`true`, message: message(), file: file, line: line) { let value = try expression() if value { return .success } else { return .expectedFailure(nil) } } } public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.fail, message: message, file: file, line: line) { return .expectedFailure(nil) } } public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Swift.Error) -> Void = { _ in }) { let rethrowsOverload: (() throws -> T, () -> String, StaticString, UInt, (Swift.Error) throws -> Void) throws -> Void = XCTAssertThrowsError try? rethrowsOverload(expression, message, file, line, errorHandler) } public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Swift.Error) throws -> Void = { _ in }) rethrows { _XCTEvaluateAssertion(.throwsError, message: message(), file: file, line: line) { var caughtErrorOptional: Swift.Error? do { _ = try expression() } catch { caughtErrorOptional = error } if let caughtError = caughtErrorOptional { try errorHandler(caughtError) return .success } else { return .expectedFailure("did not throw error") } } } public func XCTAssertNoThrow<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { _XCTEvaluateAssertion(.noThrow, message: message(), file: file, line: line) { do { _ = try expression() return .success } catch let error { return .expectedFailure("threw error \"\(error)\"") } } }
apache-2.0
dd6d3df4f1e481a1ff47e14c697c7351
43.849099
255
0.62994
4.375522
false
false
false
false
iOSTestApps/WordPress-iOS
WordPress/WordPressTest/AccountServiceTests.swift
15
3407
import UIKit import XCTest class AccountServiceTests: XCTestCase { var contextManager: TestContextManager! var accountService: AccountService! override func setUp() { super.setUp() contextManager = TestContextManager() accountService = AccountService(managedObjectContext: contextManager.mainContext)! } override func tearDown() { super.tearDown() contextManager = nil accountService = nil } func testCreateWordPressComAccountUUID() { let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") XCTAssertNotNil(account.uuid, "UUID should be set") } func testSetDefaultWordPressComAccountCheckUUID() { let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") accountService.setDefaultWordPressComAccount(account) let uuid = NSUserDefaults.standardUserDefaults().stringForKey("AccountDefaultDotcomUUID") XCTAssertNotNil(uuid, "Default UUID should be set") XCTAssertEqual(uuid!, account.uuid, "UUID should be set as default") } func testGetDefaultWordPressComAccountNoneSet() { XCTAssertNil(accountService.defaultWordPressComAccount(), "No default account should be set") } func testGetDefaultWordPressComAccount() { let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") accountService.setDefaultWordPressComAccount(account) let defaultAccount = accountService.defaultWordPressComAccount() XCTAssertNotNil(defaultAccount, "Default account should be set") XCTAssertEqual(defaultAccount, account, "Default account should the one created") } func testNumberOfAccountsNoAccounts() { XCTAssertTrue(0 == accountService.numberOfAccounts(), "There should be zero accounts") } func testNumberOfAccountsOneAccount() { let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") XCTAssertTrue(1 == accountService.numberOfAccounts(), "There should be one account") } func testNumberOfAccountsTwoAccounts() { let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") let account2 = accountService.createOrUpdateAccountWithUsername("username2", authToken: "authtoken2") XCTAssertTrue(2 == accountService.numberOfAccounts(), "There should be two accounts") } func testRemoveDefaultWordPressComAccountNoAccount() { accountService.removeDefaultWordPressComAccount() XCTAssertTrue(true, "Test passes if no exception thrown") } func testRemoveDefaultWordPressComAccountAccountSet() { accountService.removeDefaultWordPressComAccount() let account = accountService.createOrUpdateAccountWithUsername("username", authToken: "authtoken") accountService.setDefaultWordPressComAccount(account) accountService.removeDefaultWordPressComAccount() XCTAssertNil(accountService.defaultWordPressComAccount(), "No default account should be set") XCTAssertTrue(account.fault, "Account should be deleted") } }
gpl-2.0
c52a78baf1affd7d84fee8b7fe72159f
38.16092
109
0.706193
6.602713
false
true
false
false
Minecodecraft/50DaysOfSwift
Day 2 - ControlledButton/ControlledButton/ControlledButton/ViewController.swift
1
6373
// // ViewController.swift // ControlledButton // // Created by Minecode on 2017/6/19. // Copyright © 2017年 org.minecode. All rights reserved. // import UIKit fileprivate let kButtonH: CGFloat = 200 class ViewController: UIViewController, UIGestureRecognizerDelegate { // 控件 @IBOutlet weak var segmentBar: UISegmentedControl! var mainButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupUI() } @IBAction func segmentAction(_ sender: UISegmentedControl) { NSLog("Segment Selected") switch sender.selectedSegmentIndex { case 0: self.mainButton.backgroundColor = UIColor.red case 1: self.mainButton.backgroundColor = UIColor.green case 2: self.mainButton.backgroundColor = UIColor.blue case 3: self.mainButton.backgroundColor = UIColor.randomColor() default: self.mainButton.backgroundColor = UIColor.yellow } } } extension ViewController { func setupUI() { // 设置界面背景 let backgroundLayer = CAGradientLayer() backgroundLayer.colors = [UIColor.yellow.cgColor, UIColor.white.cgColor] backgroundLayer.startPoint = CGPoint(x: 0.5, y: 0) backgroundLayer.endPoint = CGPoint(x: 0.5, y: 1) backgroundLayer.frame = self.view.bounds self.view.layer.addSublayer(backgroundLayer) // 避免渐变背景遮挡选项卡 self.view.bringSubview(toFront: segmentBar) // 添加交互按钮 self.mainButton = UIButton() mainButton.frame.size = CGSize(width: kButtonH, height: kButtonH) mainButton.layer.cornerRadius = kButtonH/2 mainButton.backgroundColor = UIColor.red mainButton.center = self.view.center mainButton.setTitle("Minecode", for: .normal) mainButton.titleLabel?.font = UIFont.systemFont(ofSize: 24) mainButton.titleLabel?.textColor = UIColor.white self.view.addSubview(mainButton) addGesture() } func addGesture() { let singleTapGes = UITapGestureRecognizer(target: self, action: #selector(signleTapAction(_:))) singleTapGes.numberOfTapsRequired = 1 self.mainButton.addGestureRecognizer(singleTapGes) let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:))) longPressGes.allowableMovement = 10 longPressGes.minimumPressDuration = 1 self.mainButton.addGestureRecognizer(longPressGes) let panGes = UIPanGestureRecognizer(target: self, action: #selector(panAction(_:))) panGes.minimumNumberOfTouches = 1 panGes.maximumNumberOfTouches = 1 self.mainButton.addGestureRecognizer(panGes) let pinchGes = UIPinchGestureRecognizer(target: self, action: #selector(pinchAction(_:))) pinchGes.delegate = self self.mainButton.addGestureRecognizer(pinchGes) let rotationGes = UIRotationGestureRecognizer(target: self, action: #selector(rotationAction(_:))) rotationGes.delegate = self self.mainButton.addGestureRecognizer(rotationGes) } } // 手势实现 extension ViewController { func signleTapAction(_ signleTapGes: UITapGestureRecognizer) { NSLog("Signle Tap") let animation = CABasicAnimation(keyPath: "transform.rotation.z") // 周期 animation.duration = 0.08 animation.repeatCount = 4 // 抖动角度 animation.fromValue = (-M_1_PI) animation.toValue = (M_1_PI) // 恢复原样 animation.autoreverses = true // 设置抖动中心点 self.mainButton.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.mainButton.layer.add(animation, forKey: "rotation.z") } func longPressAction(_ longPressGes: UILongPressGestureRecognizer) { NSLog("Long Press") let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") // 周期 animation.duration = 0.08 animation.repeatCount = 2 // 抖动幅度 animation.values = [0, -self.mainButton.frame.width/4, self.mainButton.frame.width/4, 0] // 恢复原样 animation.autoreverses = true // 设置抖动中心 self.mainButton.layer.add(animation, forKey: "rotation.x") } func panAction(_ panGes: UIPanGestureRecognizer) { NSLog("Drag") // 获取坐标并修改 let movePoint = panGes.translation(in: self.view) var curPoint = self.mainButton.center curPoint.x += movePoint.x curPoint.y += movePoint.y self.mainButton.center = curPoint // 清空一下,防止坐标叠加 panGes.setTranslation(CGPoint.zero, in: self.view) } func pinchAction(_ pinchGes: UIPinchGestureRecognizer) { NSLog("Pinch Action") // 获取缩放比例 let pinchScale = pinchGes.scale self.mainButton.transform = self.mainButton.transform.scaledBy(x: pinchScale, y: pinchScale); // 清空一下,防止比例叠加 pinchGes.scale = 1.0 } func rotationAction(_ rotationGes: UIRotationGestureRecognizer) { NSLog("Rotation Action") let rotationR = rotationGes.rotation self.mainButton.transform = self.mainButton.transform.rotated(by: rotationR) // 清空一下,防止角度叠加 rotationGes.rotation = 0.0 } // 允许同时响应多个手势 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension UIColor { // 子类使用convenience初始化方法,必须调用父类的designated方法 convenience init(r: CGFloat, g: CGFloat, b: CGFloat) { self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0) } class func randomColor() -> UIColor { return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256))) } }
mit
fd47481b9430818eeb7aa4c4fb428b4f
31.59893
157
0.635171
4.721921
false
false
false
false
nuclearace/SwiftDiscord
Sources/SwiftDiscord/DiscordClient.swift
1
37215
// The MIT License (MIT) // Copyright (c) 2016 Erik Little // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without // limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import Foundation import Dispatch /// /// The base class for SwiftDiscord. Most interaction with Discord will be done through this class. /// /// See `DiscordEndpointConsumer` for methods dealing with sending to Discord. /// /// Creating a client: /// /// ```swift /// self.client = DiscordClient(token: "Bot mysupersecretbottoken", configuration: [.log(.info)]) /// ``` /// /// Once a client is created, you need to set its delegate so that you can start receiving events: /// /// ```swift /// self.client.delegate = self /// ``` /// /// See `DiscordClientDelegate` for a list of delegate methods that can be implemented. /// open class DiscordClient : DiscordClientSpec, DiscordDispatchEventHandler, DiscordEndpointConsumer { // MARK: Properties /// The rate limiter for this client. public var rateLimiter: DiscordRateLimiterSpec! /// The Discord JWT token. public let token: DiscordToken /// The client's delegate. public weak var delegate: DiscordClientDelegate? /// If true, the client does not store presences. public var discardPresences = false /// The queue that callbacks are called on. In addition, any reads from any properties of DiscordClient should be /// made on this queue, as this is the queue where modifications on them are made. public var handleQueue = DispatchQueue.main /// The manager for this client's shards. public var shardManager: DiscordShardManager! /// If we should only represent a single shard, this is the shard information. public var shardingInfo = try! DiscordShardInformation(shardRange: 0..<1, totalShards: 1) /// Whether large guilds should have their users fetched as soon as they are created. public var fillLargeGuilds = false /// Whether the client should query the API for users who aren't in the guild public var fillUsers = false /// Whether the client should remove users from guilds when they go offline. public var pruneUsers = false /// Whether or not this client is connected. public private(set) var connected = false /// The direct message channels this user is in. public private(set) var directChannels = [ChannelID: DiscordTextChannel]() /// The guilds that this user is in. public private(set) var guilds = [GuildID: DiscordGuild]() /// The relationships this user has. Only valid for non-bot users. public private(set) var relationships = [[String: Any]]() /// The DiscordUser this client is connected to. public private(set) var user: DiscordUser? /// A manager for the voice engines. public private(set) var voiceManager: DiscordVoiceManager! var channelCache = [ChannelID: DiscordChannel]() private var logType: String { return "DiscordClient" } private let voiceQueue = DispatchQueue(label: "voiceQueue") // MARK: Initializers /// /// - parameter token: The discord token of the user /// - parameter delegate: The delegate for this client. /// - parameter configuration: An array of DiscordClientOption that can be used to customize the client /// public required init(token: DiscordToken, delegate: DiscordClientDelegate, configuration: [DiscordClientOption] = []) { self.token = token self.shardManager = DiscordShardManager(delegate: self) self.voiceManager = DiscordVoiceManager(delegate: self) self.delegate = delegate for config in configuration { switch config { case let .handleQueue(queue): handleQueue = queue case let .log(level): DefaultDiscordLogger.Logger.level = level case let .logger(logger): DefaultDiscordLogger.Logger = logger case let .rateLimiter(limiter): self.rateLimiter = limiter case let .shardingInfo(shardingInfo): self.shardingInfo = shardingInfo case let .voiceConfiguration(config): self.voiceManager.engineConfiguration = config case .discardPresences: discardPresences = true case .fillLargeGuilds: fillLargeGuilds = true case .fillUsers: fillUsers = true case .pruneUsers: pruneUsers = true } } rateLimiter = rateLimiter ?? DiscordRateLimiter(callbackQueue: handleQueue, failFast: false) } // MARK: Methods /// /// Begins the connection to Discord. Once this is called, wait for a `connect` event before trying to interact /// with the client. /// open func connect() { DefaultDiscordLogger.Logger.log("Connecting", type: logType) shardManager.manuallyShatter(withInfo: shardingInfo) shardManager.connect() } /// /// Disconnects from Discord. A `disconnect` event is fired when the client has successfully disconnected. /// /// Calling this method turns off automatic resuming, set `resume` to `true` before calling `connect()` again. /// open func disconnect() { DefaultDiscordLogger.Logger.log("Disconnecting", type: logType) connected = false shardManager.disconnect() for (_, engine) in voiceManager.get(voiceManager.voiceEngines) { engine.disconnect() } } /// /// Finds a channel by its snowflake. /// /// - parameter fromId: A channel snowflake /// - returns: An optional containing a `DiscordChannel` if one was found. /// public func findChannel(fromId channelId: ChannelID) -> DiscordChannel? { if let channel = channelCache[channelId] { DefaultDiscordLogger.Logger.debug("Got cached channel \(channel)", type: logType) return channel } let channel: DiscordChannel if let guild = guildForChannel(channelId), let guildChannel = guild.channels[channelId] { channel = guildChannel } else if let dmChannel = directChannels[channelId] { channel = dmChannel } else { DefaultDiscordLogger.Logger.debug("Couldn't find channel \(channelId)", type: logType) return nil } channelCache[channel.id] = channel DefaultDiscordLogger.Logger.debug("Found channel \(channel)", type: logType) return channel } // Handling /// /// Handles a dispatch event. This will call one of the other handle methods or the standard event handler. /// /// - parameter event: The dispatch event /// - parameter data: The dispatch event's data /// open func handleDispatch(event: DiscordDispatchEvent, data: DiscordGatewayPayloadData) { guard case let .object(eventData) = data else { DefaultDiscordLogger.Logger.error("Got dispatch event without an object: \(event), \(data)", type: "DiscordDispatchEventHandler") return } switch event { case .presenceUpdate: handlePresenceUpdate(with: eventData) case .messageCreate: handleMessageCreate(with: eventData) case .messageUpdate: handleMessageUpdate(with: eventData) case .guildMemberAdd: handleGuildMemberAdd(with: eventData) case .guildMembersChunk: handleGuildMembersChunk(with: eventData) case .guildMemberUpdate: handleGuildMemberUpdate(with: eventData) case .guildMemberRemove: handleGuildMemberRemove(with: eventData) case .guildRoleCreate: handleGuildRoleCreate(with: eventData) case .guildRoleDelete: handleGuildRoleRemove(with: eventData) case .guildRoleUpdate: handleGuildRoleUpdate(with: eventData) case .guildCreate: handleGuildCreate(with: eventData) case .guildDelete: handleGuildDelete(with: eventData) case .guildUpdate: handleGuildUpdate(with: eventData) case .guildEmojisUpdate: handleGuildEmojiUpdate(with: eventData) case .channelUpdate: handleChannelUpdate(with: eventData) case .channelCreate: handleChannelCreate(with: eventData) case .channelDelete: handleChannelDelete(with: eventData) case .voiceServerUpdate: handleVoiceServerUpdate(with: eventData) case .voiceStateUpdate: handleVoiceStateUpdate(with: eventData) case .ready: handleReady(with: eventData) default: delegate?.client(self, didNotHandleDispatchEvent: event, withData: eventData) } } /// /// Gets the `DiscordGuild` for a channel snowflake. /// /// - parameter channelId: A channel snowflake /// - returns: An optional containing a `DiscordGuild` if one was found. /// public func guildForChannel(_ channelId: ChannelID) -> DiscordGuild? { return guilds.filter({ $0.1.channels[channelId] != nil }).map({ $0.1 }).first } /// /// Joins a voice channel. A `voiceEngine.ready` event will be fired when the client has joined the channel. /// /// - parameter channelId: The snowflake of the voice channel you would like to join /// open func joinVoiceChannel(_ channelId: ChannelID) { guard let guild = guildForChannel(channelId), let channel = guild.channels[channelId] as? DiscordGuildVoiceChannel else { return } DefaultDiscordLogger.Logger.log("Joining voice channel: \(channel)", type: self.logType) shardManager.sendPayload(DiscordGatewayPayload(code: .gateway(.voiceStatusUpdate), payload: .object(["guild_id": String(describing: guild.id), "channel_id": String(describing: channel.id), "self_mute": false, "self_deaf": false ]) ), onShard: guild.shardNumber(assuming: shardingInfo.totalShards)) } /// /// Leaves the voice channel that is associated with the guild specified. /// /// - parameter onGuild: The snowflake of the guild that you want to leave. /// open func leaveVoiceChannel(onGuild guildId: GuildID) { DefaultDiscordLogger.Logger.log("Leaving voice channel on guild: \(guildId)", type: logType) voiceManager.leaveVoiceChannel(onGuild: guildId) } /// /// Requests all users from Discord for the guild specified. Use this when you need to get all users on a large /// guild. Multiple `guildMembersChunk` will be fired. /// /// - parameter on: The snowflake of the guild you wish to request all users. /// open func requestAllUsers(on guildId: GuildID) { let requestObject: [String: Any] = [ "guild_id": guildId, "query": "", "limit": 0 ] guard let shardNum = guilds[guildId]?.shardNumber(assuming: shardingInfo.totalShards) else { return } shardManager.sendPayload(DiscordGatewayPayload(code: .gateway(.requestGuildMembers), payload: .object(requestObject)), onShard: shardNum) } /// /// Sets the user's presence. /// /// - parameter presence: The new presence object /// open func setPresence(_ presence: DiscordPresenceUpdate) { shardManager.sendPayload(DiscordGatewayPayload(code: .gateway(.statusUpdate), payload: .customEncodable(presence)), onShard: 0) } private func startVoiceConnection(_ guildId: GuildID) { voiceManager.startVoiceConnection(guildId) } // MARK: DiscordShardManagerDelegate conformance. /// /// Signals that the manager has finished connecting. /// /// - parameter manager: The manager. /// - parameter didConnect: Should always be true. /// open func shardManager(_ manager: DiscordShardManager, didConnect connected: Bool) { handleQueue.async { self.connected = true self.delegate?.client(self, didConnect: true) } } /// /// Signals that the manager has disconnected. /// /// - parameter manager: The manager. /// - parameter didDisconnectWithReason: The reason the manager disconnected. /// open func shardManager(_ manager: DiscordShardManager, didDisconnectWithReason reason: String) { handleQueue.async { self.connected = false self.delegate?.client(self, didDisconnectWithReason: reason) } } /// /// Signals that the manager received an event. The client should handle this. /// /// - parameter manager: The manager. /// - parameter shouldHandleEvent: The event to be handled. /// - parameter withPayload: The payload that came with the event. /// open func shardManager(_ manager: DiscordShardManager, shouldHandleEvent event: DiscordDispatchEvent, withPayload payload: DiscordGatewayPayload) { handleQueue.async { self.handleDispatch(event: event, data: payload.payload) } } /// /// Called when an engine disconnects. /// /// - parameter manager: The manager. /// - parameter engine: The engine that disconnected. /// open func voiceManager(_ manager: DiscordVoiceManager, didDisconnectEngine engine: DiscordVoiceEngine) { handleQueue.async { guard let shardNum = self.guilds[engine.guildId]?.shardNumber(assuming: self.shardingInfo.totalShards) else { return } let payload = DiscordGatewayPayloadData.object(["guild_id": String(describing: engine.guildId), "channel_id": EncodableNull(), "self_mute": false, "self_deaf": false]) self.shardManager.sendPayload(DiscordGatewayPayload(code: .gateway(.voiceStatusUpdate), payload: payload), onShard: shardNum) } } /// /// Called when a voice engine receives opus voice data. /// /// - parameter manager: The manager. /// - parameter didReceiveVoiceData: The data received. /// - parameter fromEngine: The engine that received the data. /// open func voiceManager(_ manager: DiscordVoiceManager, didReceiveOpusVoiceData data: DiscordOpusVoiceData, fromEngine engine: DiscordVoiceEngine) { voiceQueue.async { self.delegate?.client(self, didReceiveOpusVoiceData: data, fromEngine: engine) } } /// /// Called when a voice engine receives raw voice data. /// /// - parameter manager: The manager. /// - parameter didReceiveVoiceData: The data received. /// - parameter fromEngine: The engine that received the data. /// open func voiceManager(_ manager: DiscordVoiceManager, didReceiveRawVoiceData data: DiscordRawVoiceData, fromEngine engine: DiscordVoiceEngine) { voiceQueue.async { self.delegate?.client(self, didReceiveRawVoiceData: data, fromEngine: engine) } } /// /// Called when a voice engine needs a data source. /// /// **Not called on the handleQueue** /// /// - parameter manager: The manager that is requesting an encoder. /// - parameter needsDataSourceForEngine: The engine that needs an encoder /// - returns: An encoder. /// open func voiceManager(_ manager: DiscordVoiceManager, needsDataSourceForEngine engine: DiscordVoiceEngine) throws -> DiscordVoiceDataSource? { return try delegate?.client(self, needsDataSourceForEngine: engine) } /// /// Called when a voice engine is ready. /// /// - parameter manager: The manager. /// - parameter engine: The engine that's ready. /// open func voiceManager(_ manager: DiscordVoiceManager, engineIsReady engine: DiscordVoiceEngine) { handleQueue.async { self.delegate?.client(self, isReadyToSendVoiceWithEngine: engine) } } // MARK: DiscordDispatchEventHandler Conformance /// /// Handles channel creates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didCreateChannel` delegate method. /// /// - parameter with: The data from the event /// open func handleChannelCreate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling channel create", type: logType) guard let channel = channelFromObject(data, withClient: self) else { return } switch channel { case let guildChannel as DiscordGuildChannel: guilds[guildChannel.guildId]?.channels[guildChannel.id] = guildChannel case let dmChannel as DiscordDMChannel: directChannels[channel.id] = dmChannel case let groupChannel as DiscordGroupDMChannel: directChannels[channel.id] = groupChannel default: break } DefaultDiscordLogger.Logger.verbose("Created channel: \(channel)", type: logType) delegate?.client(self, didCreateChannel: channel) } /// /// Handles channel deletes from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didDeleteChannel` delegate method. /// /// - parameter with: The data from the event /// open func handleChannelDelete(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling channel delete", type: logType) guard let type = DiscordChannelType(rawValue: data["type"] as? Int ?? -1) else { return } guard let channelId = Snowflake(data["id"] as? String) else { return } let removedChannel: DiscordChannel switch type { case .text, .voice, .category: guard let guildId = Snowflake(data["guild_id"] as? String), let guildChannel = guilds[guildId]?.channels.removeValue(forKey: channelId) else { return } removedChannel = guildChannel case .direct, .groupDM: guard let direct = directChannels.removeValue(forKey: channelId) else { return } removedChannel = direct } channelCache.removeValue(forKey: channelId) DefaultDiscordLogger.Logger.verbose("Removed channel: \(removedChannel)", type: logType) delegate?.client(self, didDeleteChannel: removedChannel) } /// /// Handles channel updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateChannel` delegate method. /// /// - parameter with: The data from the event /// open func handleChannelUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling channel update", type: logType) guard let channel = guildChannel(fromObject: data, guildID: nil, client: self) else { return } DefaultDiscordLogger.Logger.verbose("Updated channel: \(channel)", type: logType) guilds[channel.guildId]?.channels[channel.id] = channel channelCache.removeValue(forKey: channel.id) delegate?.client(self, didUpdateChannel: channel) } /// /// Handles guild creates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didCreateGuild` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildCreate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild create", type: logType) let guild = DiscordGuild(guildObject: data, client: self) DefaultDiscordLogger.Logger.verbose("Created guild: \(guild)", type: self.logType) guilds[guild.id] = guild delegate?.client(self, didCreateGuild: guild) guard fillLargeGuilds && guild.large else { return } // Fill this guild with users immediately DefaultDiscordLogger.Logger.debug("Fill large guild \(guild.id) with all users", type: logType) requestAllUsers(on: guild.id) } /// /// Handles guild deletes from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didDeleteGuild` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildDelete(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild delete", type: logType) guard let guildId = Snowflake(data["id"] as? String) else { return } guard let removedGuild = guilds.removeValue(forKey: guildId) else { return } for channel in removedGuild.channels.keys { channelCache[channel] = nil } DefaultDiscordLogger.Logger.verbose("Removed guild: \(removedGuild)", type: logType) delegate?.client(self, didDeleteGuild: removedGuild) } /// /// Handles guild emoji updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateEmojis:onGuild:` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildEmojiUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild emoji update", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let emojis = data["emojis"] as? [[String: Any]] else { return } let discordEmojis = DiscordEmoji.emojisFromArray(emojis) DefaultDiscordLogger.Logger.verbose("Created guild emojis: \(discordEmojis)", type: logType) guild.emojis = discordEmojis delegate?.client(self, didUpdateEmojis: discordEmojis, onGuild: guild) } /// /// Handles guild member adds from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didAddGuildMember` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildMemberAdd(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild member add", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } let guildMember = DiscordGuildMember(guildMemberObject: data, guildId: guild.id, guild: guild) DefaultDiscordLogger.Logger.verbose("Created guild member: \(guildMember)", type: logType) guild.members[guildMember.user.id] = guildMember guild.memberCount += 1 delegate?.client(self, didAddGuildMember: guildMember) } /// /// Handles guild member removes from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didRemoveGuildMember` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildMemberRemove(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild member remove", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let user = data["user"] as? [String: Any], let id = Snowflake(user["id"] as? String) else { return } guild.memberCount -= 1 guard let removedGuildMember = guild.members.removeValue(forKey: id) else { return } DefaultDiscordLogger.Logger.verbose("Removed guild member: \(removedGuildMember)", type: logType) delegate?.client(self, didRemoveGuildMember: removedGuildMember) } /// /// Handles guild member updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateGuildMember` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildMemberUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild member update", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let user = data["user"] as? [String: Any], let id = Snowflake(user["id"] as? String) else { return } guard let guildMember = guild.members[id]?.updateMember(data) else { return } DefaultDiscordLogger.Logger.verbose("Updated guild member: \(guildMember)", type: logType) delegate?.client(self, didUpdateGuildMember: guildMember) } /// /// Handles guild members chunks from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didHandleGuildMemberChunk:forGuild:` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildMembersChunk(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild members chunk", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let members = data["members"] as? [[String: Any]] else { return } let guildMembers = DiscordGuildMember.guildMembersFromArray(members, withGuildId: guildId, guild: guild) guild.members.updateValues(withOtherDict: guildMembers) delegate?.client(self, didHandleGuildMemberChunk: guildMembers, forGuild: guild) } /// /// Handles guild role creates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didCreateRole` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildRoleCreate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild role create", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let roleObject = data["role"] as? [String: Any] else { return } let role = DiscordRole(roleObject: roleObject) DefaultDiscordLogger.Logger.verbose("Created role: \(role)", type: logType) guild.roles[role.id] = role delegate?.client(self, didCreateRole: role, onGuild: guild) } /// /// Handles guild role removes from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didDeleteRole` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildRoleRemove(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild role remove", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let roleId = Snowflake(data["role_id"] as? String) else { return } guard let removedRole = guild.roles.removeValue(forKey: roleId) else { return } DefaultDiscordLogger.Logger.verbose("Removed role: \(removedRole)", type: logType) delegate?.client(self, didDeleteRole: removedRole, fromGuild: guild) } /// /// Handles guild member updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateRole` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildRoleUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild role update", type: logType) // Functionally the same as adding guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let roleObject = data["role"] as? [String: Any] else { return } let role = DiscordRole(roleObject: roleObject) DefaultDiscordLogger.Logger.verbose("Updated role: \(role)", type: logType) guild.roles[role.id] = role delegate?.client(self, didUpdateRole: role, onGuild: guild) } /// /// Handles guild updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateGuild` delegate method. /// /// - parameter with: The data from the event /// open func handleGuildUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling guild update", type: logType) guard let guildId = Snowflake(data["id"] as? String) else { return } guard let updatedGuild = guilds[guildId]?.updateGuild(fromGuildUpdate: data) else { return } DefaultDiscordLogger.Logger.verbose("Updated guild: \(updatedGuild)", type: logType) delegate?.client(self, didUpdateGuild: updatedGuild) } /// /// Handles message updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didUpdateMessage` delegate method. /// /// - parameter with: The data from the event /// open func handleMessageUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling message update", type: logType) let message = DiscordMessage(messageObject: data, client: self) DefaultDiscordLogger.Logger.verbose("Message: \(message)", type: logType) delegate?.client(self, didUpdateMessage: message) } /// /// Handles message creates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didCreateMessage` delegate method. /// /// - parameter with: The data from the event /// open func handleMessageCreate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling message create", type: logType) let message = DiscordMessage(messageObject: data, client: self) DefaultDiscordLogger.Logger.verbose("Message: \(message)", type: logType) delegate?.client(self, didCreateMessage: message) } /// /// Handles presence updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didReceivePresenceUpdate` delegate method. /// /// - parameter with: The data from the event /// open func handlePresenceUpdate(with data: [String: Any]) { guard let guildId = Snowflake(data["guild_id"] as? String), let guild = guilds[guildId] else { return } guard let user = data["user"] as? [String: Any], let userId = Snowflake(user["id"] as? String) else { return } var presence = guild.presences[userId] if presence != nil { presence!.updatePresence(presenceObject: data) } else { presence = DiscordPresence(presenceObject: data, guildId: guildId) } if !discardPresences { DefaultDiscordLogger.Logger.debug("Updated presence: \(presence!)", type: logType) guild.presences[userId] = presence! } delegate?.client(self, didReceivePresenceUpdate: presence!) guild.updateGuild(fromPresence: presence!, fillingUsers: fillUsers, pruningUsers: pruneUsers) } /// /// Handles the ready event from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didReceiveReady` delegate method. /// /// - parameter with: The data from the event /// open func handleReady(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling ready", type: logType) if let user = data["user"] as? [String: Any] { self.user = DiscordUser(userObject: user) } if let guilds = data["guilds"] as? [[String: Any]] { for (id, guild) in DiscordGuild.guildsFromArray(guilds, client: self) { self.guilds.updateValue(guild, forKey: id) } } if let relationships = data["relationships"] as? [[String: Any]] { self.relationships += relationships } if let privateChannels = data["private_channels"] as? [[String: Any]] { for (id, channel) in privateChannelsFromArray(privateChannels, client: self) { self.directChannels.updateValue(channel, forKey: id) } } delegate?.client(self, didReceiveReady: data) } /// /// Handles voice server updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// - parameter with: The data from the event /// open func handleVoiceServerUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling voice server update", type: logType) DefaultDiscordLogger.Logger.verbose("Voice server update: \(data)", type: logType) let info = DiscordVoiceServerInformation(voiceServerInformationObject: data) voiceManager.voiceServerInformations[info.guildId] = info self.startVoiceConnection(info.guildId) } /// /// Handles voice state updates from Discord. You shouldn't need to call this method directly. /// /// Override to provide additional customization around this event. /// /// Calls the `didReceiveVoiceStateUpdate` delegate method. /// /// - parameter with: The data from the event /// open func handleVoiceStateUpdate(with data: [String: Any]) { DefaultDiscordLogger.Logger.log("Handling voice state update", type: logType) guard let guildId = Snowflake(data["guild_id"] as? String) else { return } let state = DiscordVoiceState(voiceStateObject: data, guildId: guildId) DefaultDiscordLogger.Logger.verbose("Voice state: \(state)", type: logType) if state.channelId == 0 { guilds[guildId]?.voiceStates[state.userId] = nil } else { guilds[guildId]?.voiceStates[state.userId] = state } if state.userId == user?.id { if state.channelId == 0 { voiceManager.protected { self.voiceManager.voiceStates[state.guildId] = nil } } else { voiceManager.protected { self.voiceManager.voiceStates[state.guildId] = state } startVoiceConnection(state.guildId) } } delegate?.client(self, didReceiveVoiceStateUpdate: state) } }
mit
11f681380e92aba6235c33093fc42174
38.464475
130
0.644498
4.94683
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Controllers/AttributeController.swift
1
3388
// // AttributeController.swift // Webretail // // Created by Gerardo Grisolini on 17/02/17. // // import PerfectLib import PerfectHTTP class AttributeController { private let repository: AttributeProtocol init() { self.repository = ioCContainer.resolve() as AttributeProtocol } func getRoutes() -> Routes { var routes = Routes() routes.add(method: .get, uri: "/api/attribute", handler: attributesHandlerGET) routes.add(method: .get, uri: "/api/attribute/{id}", handler: attributeHandlerGET) routes.add(method: .get, uri: "/api/attribute/{id}/value", handler: attributevalueHandlerGET) routes.add(method: .post, uri: "/api/attribute", handler: attributeHandlerPOST) routes.add(method: .put, uri: "/api/attribute/{id}", handler: attributeHandlerPUT) routes.add(method: .delete, uri: "/api/attribute/{id}", handler: attributeHandlerDELETE) return routes } func attributesHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { do { let items = try self.repository.getAll() try response.setJson(items) response.completed(status: .ok) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } func attributeHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { let id = request.urlVariables["id"]! do { let item = try self.repository.get(id: Int(id)!) try response.setJson(item) response.completed(status: .ok) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } func attributevalueHandlerGET(request: HTTPRequest, _ response: HTTPResponse) { let id = request.urlVariables["id"]! do { let item = try self.repository.getValues(id: Int(id)!) try response.setJson(item) response.completed(status: .created) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } func attributeHandlerPOST(request: HTTPRequest, _ response: HTTPResponse) { do { let item: Attribute = request.getJson()! try self.repository.add(item: item) try response.setJson(item) response.completed(status: .created) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } func attributeHandlerPUT(request: HTTPRequest, _ response: HTTPResponse) { let id = request.urlVariables["id"]! do { let item: Attribute = request.getJson()! try self.repository.update(id: Int(id)!, item: item) try response.setJson(item) response.completed(status: .accepted) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } func attributeHandlerDELETE(request: HTTPRequest, _ response: HTTPResponse) { let id = request.urlVariables["id"]! do { try self.repository.delete(id: Int(id)!) response.completed(status: .noContent) } catch { response.badRequest(error: "\(request.uri) \(request.method): \(error)") } } }
apache-2.0
bed2d2bf0a9836e3719f755d562467e3
33.927835
101
0.595041
4.434555
false
false
false
false
andykkt/BFWControls
BFWControls/Modules/Transition/View/MorphSegue.swift
1
3913
// // MorphSegue.swift // // Created by Tom Brodhurst-Hill on 26/10/2015. // Copyright (c) 2015 BareFeetWare. Free to use and modify, without warranty. // // Work in progress. Unfinished. import UIKit open class MorphSegue: UIStoryboardSegue { // MARK: - Public variables @IBOutlet open lazy var fromView: UIView? = { return self.source.view }() @IBInspectable var duration: TimeInterval = 1.0 var animationOptions = UIViewAnimationOptions() // MARK: - UIStoryboardSegue open override func perform() { let destinationVCView = destination.view! let sourceVCView = source.view // Force frames to match constraints, in case misplaced. destinationVCView.setNeedsLayout() destinationVCView.layoutIfNeeded() destinationVCView.frame = (sourceVCView?.frame)! if let cell = fromView as? UITableViewCell { cell.isSelected = false } var morphingView: UIView? var contentView: UIView? let useCopyForMorphingView = true if useCopyForMorphingView { // Create a copy of the view hierarchy for morphing, so the original is not changed. if let cell = fromView as? UITableViewCell { morphingView = cell.copied morphingView?.copySubviews(cell.contentView.subviews, includeConstraints: false) } else if let fromView = fromView { morphingView = fromView.copied(withSubviews: fromView.subviews, includeConstraints: false) } if let morphingView = morphingView { sourceVCView?.addSubview(morphingView) morphingView.pinToSuperviewEdges() contentView = morphingView } } else { // morphingView = fromView // if let cell = fromView as? UITableViewCell { // contentView = cell.contentView // } // TODO: finish } if let morphingView = morphingView { // Add destination constraints, which will animate frames when layout is updated, inside animation block below. morphingView.copyDescendantConstraints(from: destinationVCView) UIView.animate( withDuration: duration, delay: 0.0, options: animationOptions, animations: { // morphingView.setNeedsLayout() // morphingView.layoutIfNeeded() if let _ = self.fromView as? UITableViewCell { morphingView.frame = (sourceVCView?.bounds)! contentView?.frame = morphingView.bounds } if let subviews = contentView?.subviews { for subview in subviews { if let destinationSubview = destinationVCView.subview(matching: subview) { subview.frame = destinationSubview.superview!.convert(destinationSubview.frame, to: destinationVCView) // subview.frame.origin.y += 64.0 // Nav bar hack subview.copyAnimatableProperties(from: destinationSubview) } else { subview.alpha = 0.0 } } } }) { finished in self.source.navigationController?.pushViewController(self.destination, animated: false) if useCopyForMorphingView { morphingView.removeFromSuperview() // morphingView.hidden = true // Keep it for reverse animation? } } } } }
mit
a15848ad21f851f23914b689f5681ea3
37.742574
134
0.544339
6.057276
false
false
false
false
Ossey/WeiBo
XYWeiBo/XYWeiBo/Classes/Compose(发布)/View/XYComposeTitleView.swift
1
3744
// // XYComposeTitleView.swift // XYWeiBo // // Created by mofeini on 16/10/2. // Copyright © 2016年 sey. All rights reserved. // import UIKit class XYComposeTitleView: UIView { class func titleViewFromNib() -> XYComposeTitleView { return Bundle.main.loadNibNamed("XYComposeTitleView", owner: nil, options: nil)?.first as! XYComposeTitleView } // MARK:- 属性 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! // MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() titleLabel.font = UIFont.systemFont(ofSize: 16) screenNameLabel.font = UIFont.systemFont(ofSize: 14) screenNameLabel.textColor = UIColor.lightGray // 4.设置文字内容 titleLabel.text = "发微博" screenNameLabel.text = XYUserAccountViewModel.shareInstance.userAccount?.screen_name } // // MARK:- 懒加载属性 // lazy var titleLabel : UILabel = UILabel() // lazy var screeenNameLabel : UILabel = UILabel() // // // MARK:- 系统回调函数 // override init(frame: CGRect) { // super.init(frame: frame) // // addSubview(titleLabel) //// addSubview(screeenNameLabel) // // // setupUI() // // // } // // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } } // MARK:- 设置UI界面 extension XYComposeTitleView { func setupUI() { // 禁止AutoResizing自动转换为约束 // self.translatesAutoresizingMaskIntoConstraints = false // // // 设置约束 // // titleLabel中心点X的约束 // let titleLabelCenterX = NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0) // self.addConstraint(titleLabelCenterX) // // // titleLabel顶部约束 // let titleLabelTop = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) // self.addConstraint(titleLabelTop) // let titleLabelWidth = NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0.0) // self.addConstraint(titleLabelWidth) // let titleLabelHeight = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0.0) // self.addConstraint(titleLabelHeight) // screeenNameLabel中心点X的约束 // let screeenNameLabelCenterX = NSLayoutConstraint(item: screeenNameLabel, attribute: .centerX, relatedBy: .equal, toItem: titleLabel, attribute: .centerX, multiplier: 1.0, constant: 0) // self.addConstraint(screeenNameLabelCenterX) // // // screeenNameLabel顶部约束 // let screeenNameLabelTop = NSLayoutConstraint(item: screeenNameLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: -3) // self.addConstraint(screeenNameLabelTop) // 3.设置空间的属性 // titleLabel.font = UIFont.systemFont(ofSize: 16) // screeenNameLabel.font = UIFont.systemFont(ofSize: 14) // // screeenNameLabel.textColor = UIColor.lightGray // // // 4.设置文字内容 // titleLabel.text = "发微博" // screeenNameLabel.text = XYUserAccountViewModel.shareInstance.userAccount?.screen_name } }
apache-2.0
f1a2b80c3651dfa8328e7785319078f3
33.786408
193
0.634385
4.348301
false
false
false
false
Eonil/EditorLegacy
Modules/Editor/Sources/MenuControllers.swift
1
2618
//// //// MenuControllers.swift //// Editor //// //// Created by Hoon H. on 2015/02/20. //// Copyright (c) 2015 Eonil. All rights reserved. //// // //import Foundation //import AppKit //import EditorUIComponents //import EditorModel // //// //// Dynamic Menus //// ------------- //// //// `ApplicationAgent` is responsible to manage dynamic state of all menus. //// See implementation of the class for details. //// // // ///// ///// MARK: Dynamic Menus ///// MARK: - ///// // // // //class ProjectMenuController: MenuController { // let run = NSMenuItem(title: "Run", shortcut: Command+"r") // let test = NSMenuItem(title: "Test", shortcut: Command+"u") // let documentate = NSMenuItem(title: "Documentate", shortcut: None) // let benchmark = NSMenuItem(title: "Benchmark", shortcut: None) // // let build = NSMenuItem(title: "Build", shortcut: Command+"b") // let clean = NSMenuItem(title: "Clean", shortcut: Command+Shift+"k") // let stop = NSMenuItem(title: "Stop", shortcut: Command+".") // // init() { // let m = NSMenu() // m.autoenablesItems = false // m.title = "Project" // m.allMenuItems = [ // run, // test, // documentate, // benchmark, // NSMenuItem.separatorItem(), // build, // clean, // stop, // ] // super.init(m) // } // // func reconfigureWithModelState(s: Set<Cargo.Command>) { // MenuController.menuOfController(self).allMenuItems.map({ $0.enabled = false }) // for c in s { // switch c { // case .Clean: // clean.enabled = true; // case .Build: // build.enabled = true; // case .Run: // run.enabled = true; // case .Documentate: // documentate.enabled = true; // case .Test: // test.enabled = true; // case .Benchmark: // benchmark.enabled = true; // } // } // } //} // //final class DebugMenuController: MenuController { // let stepOver = NSMenuItem(title: "Step Over", shortcut: Command+"1") // let stepInto = NSMenuItem(title: "Step Into", shortcut: Command+"2") // let stepOut = NSMenuItem(title: "Step Out", shortcut: Command+"3") // // init() { // let m = NSMenu() // m.autoenablesItems = false // m.title = "Debug" // m.allMenuItems = [ // stepOver, // stepInto, // stepOut, // ] // super.init(m) // } // // func reconfigureWithModelState(s: Set<Debugger.Command>) { // MenuController.menuOfController(self).allMenuItems.map({ $0.enabled = false }) // for c in s { // switch c { // // case .StepOver: // stepOver.enabled = true // case .StepInto: // stepInto.enabled = true // case .StepOut: // stepOut.enabled = true // } // } // } //} // // // // // // // // //
mit
fe10e5622d0784e7981edd3bb39df8c5
21.186441
82
0.595493
2.647118
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/TopSites/DataManagement/TopSiteHistoryManager.swift
2
3198
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Storage // Manages the top site class TopSiteHistoryManager: DataObserver { private let profile: Profile weak var delegate: DataObserverDelegate? private let topSiteCacheSize: Int32 = 32 private let dataQueue = DispatchQueue(label: "com.moz.topSiteHistory.queue") private let topSitesProvider: TopSitesProvider init(profile: Profile) { self.profile = profile self.topSitesProvider = TopSitesProviderImplementation(browserHistoryFetcher: profile.history, prefs: profile.prefs) profile.history.setTopSitesCacheSize(topSiteCacheSize) } /// RefreshIfNeeded will refresh the underlying caches for TopSites. /// By default this will only refresh topSites if KeyTopSitesCacheIsValid is false /// - Parameter forced: Refresh can be forced by setting this to true func refreshIfNeeded(forceRefresh forced: Bool) { guard !profile.isShutdown else { return } // KeyTopSitesCacheIsValid is false when we want to invalidate. Thats why this logic is so backwards let shouldInvalidateTopSites = forced || !(profile.prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false) guard shouldInvalidateTopSites else { return } // Flip the `KeyTopSitesCacheIsValid` flag now to prevent subsequent calls to refresh // from re-invalidating the cache. profile.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid) profile.recommendations.repopulate(invalidateTopSites: shouldInvalidateTopSites).uponQueue(dataQueue) { [weak self] _ in guard let self = self else { return } self.delegate?.didInvalidateDataSource(forceRefresh: forced) } } func getTopSites(completion: @escaping ([Site]?) -> Void) { topSitesProvider.getTopSites { [weak self] result in guard self != nil else { return } completion(result) } } func removeTopSite(site: Site) { profile.history.removeFromPinnedTopSites(site).uponQueue(dataQueue) { [weak self] result in guard result.isSuccess, let self = self else { return } self.refreshIfNeeded(forceRefresh: true) } } /// If the default top sites contains the siteurl. also wipe it from default suggested sites. func removeDefaultTopSitesTile(site: Site) { let url = site.tileURL.absoluteString if topSitesProvider.defaultTopSites(profile.prefs).contains(where: { $0.url == url }) { deleteTileForSuggestedSite(url) } } private func deleteTileForSuggestedSite(_ siteURL: String) { var deletedSuggestedSites = profile.prefs.arrayForKey(topSitesProvider.defaultSuggestedSitesKey) as? [String] ?? [] deletedSuggestedSites.append(siteURL) profile.prefs.setObject(deletedSuggestedSites, forKey: topSitesProvider.defaultSuggestedSitesKey) } }
mpl-2.0
2c86bd09af93c29bd88976bfcc454903
42.216216
128
0.69606
4.95814
false
false
false
false
benlangmuir/swift
benchmark/single-source/StringSwitch.swift
10
6253
//===--- StringSwitch.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 - 2021 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 // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = [ BenchmarkInfo( name: "StringSwitch", runFunction: run_StringSwitch, tags: [.validation, .api]) ] @inline(never) func getIndex(_ s: String) -> Int { switch s { case "Swift": return 0 case "is": return 1 case "a": return 2 case "general-purpose": return 3 case "programming language": return 4 case "built": return 5 case "using": return 6 case "modern": return 7 case "approach": return 8 case "to": return 9 case "safety,": return 10 case "performance,": return 11 case "and": return 12 case "software": return 13 case "design": return 14 case "patterns.": return 15 case "": return 16 case "The": return 17 case "goal": return 18 case "of": return 19 case "the": return 20 case "project": return 21 case "create": return 22 case "best": return 23 case "available": return 24 case "for": return 25 case "uses": return 26 case "ranging": return 27 case "from": return 28 case "systems": return 29 case "mobile": return 30 case "desktop": return 31 case "apps,": return 32 case "scaling": return 33 case "up": return 34 case "cloud": return 35 case "services.": return 36 case "Most": return 37 case "importantly,": return 38 case "designed": return 39 case "make": return 40 case "writing": return 41 case "maintaining": return 42 case "correct": return 43 case "programs": return 44 case "easier": return 45 case "developer.": return 46 case "To": return 47 case "achieve": return 48 case "this": return 49 case "goal,": return 50 case "we": return 51 case "believe": return 52 case "that": return 53 case "most": return 54 case "obvious": return 55 case "way": return 56 case "write": return 57 case "code": return 58 case "must": return 59 case "also": return 60 case "be:": return 61 case "Safe.": return 62 case "should": return 63 case "behave": return 64 case "in": return 65 case "safe": return 66 case "manner.": return 67 case "Undefined": return 68 case "behavior": return 69 case "enemy": return 70 case "developer": return 71 case "mistakes": return 72 case "be": return 73 case "caught": return 74 case "before": return 75 case "production.": return 76 case "Opting": return 77 case "safety": return 78 case "sometimes": return 79 case "means": return 80 case "will": return 81 case "feel": return 82 case "strict,": return 83 case "but": return 84 case "clarity": return 85 case "saves": return 86 case "time": return 87 case "long": return 88 case "run.": return 89 case "Fast.": return 90 case "intended": return 91 case "as": return 92 case "replacement": return 93 case "C-based": return 94 case "languages": return 95 case "(C, C++, Objective-C).": return 96 case "As": return 97 case "such,": return 98 case "comparable": return 99 case "those": return 100 case "performance": return 101 case "tasks.": return 102 case "Performance": return 103 case "predictable": return 104 case "consistent,": return 105 case "not": return 106 case "just": return 107 case "fast": return 108 case "short": return 109 case "bursts": return 110 case "require": return 111 case "clean-up": return 112 case "later.": return 113 case "There": return 114 case "are": return 115 case "lots": return 116 case "with": return 117 case "novel": return 118 case "features": return 119 case "x": return 120 case "being": return 121 case "rare.": return 122 case "Expressive.": return 123 case "benefits": return 124 case "decades": return 125 case "advancement": return 126 case "computer": return 127 case "science": return 128 case "offer": return 129 case "syntax": return 130 case "joy": return 131 case "use,": return 132 case "developers": return 133 case "expect.": return 134 case "But": return 135 case "never": return 136 case "done.": return 137 case "We": return 138 case "monitor": return 139 case "advancements": return 140 case "embrace": return 141 case "what": return 142 case "works,": return 143 case "continually": return 144 case "evolving": return 145 case "even": return 146 case "better.": return 147 case "Tools": return 148 case "critical": return 149 case "part": return 150 case "ecosystem.": return 151 case "strive": return 152 case "integrate": return 153 case "well": return 154 case "within": return 155 case "developerss": return 156 case "toolset,": return 157 case "build": return 158 case "quickly,": return 159 case "present": return 160 case "excellent": return 161 case "diagnostics,": return 162 case "enable": return 163 case "interactive": return 164 case "development": return 165 case "experiences.": return 166 case "can": return 167 case "so": return 168 case "much": return 169 case "more": return 170 case "powerful,": return 171 case "like": return 172 case "Swift-based": return 173 case "playgrounds": return 174 case "do": return 175 case "Xcode,": return 176 case "or": return 177 case "web-based": return 178 case "REPL": return 179 case "when": return 180 case "working": return 181 case "Linux": return 182 case "server-side": return 183 case "code.": return 184 default: return -1 } } @inline(never) func test(_ s: String) { blackHole(getIndex(s)) } @inline(never) public func run_StringSwitch(n: Int) { let first = "Swift" let short = "To" let long = "(C, C++, Objective-C)." let last = "code." let none = "non existent string" for _ in 1...100*n { test(first) test(short) test(long) test(last) test(none) } }
apache-2.0
a57a9c74f6456306b796b91c6950136b
25.722222
80
0.650088
3.791995
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/MLBusinessAppDataService.swift
1
1917
import Foundation struct MLBusinessAppDataService { enum AppIdentifier: String { case meli = "ML" case mp = "MP" case other = "OTHER" } private let meliName: String = "mercadolibre" private let mpName: String = "mercadopago" private let meliDeeplink: String = "meli://instore/scan_qr" private let mpDeeplink: String = "mercadopago://instore/scan_qr" private func getAppName() -> String { guard let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return "" } return appName.lowercased() } } // MARK: Public methods. extension MLBusinessAppDataService { func getAppIdentifier() -> AppIdentifier { return isMeli() ? .meli : .mp } func getAppVersion() -> String { let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String return version ?? "" } func isMeli() -> Bool { return getAppName().contains(meliName) } func isMp() -> Bool { return getAppName().contains(mpName) } func isMeliAlreadyInstalled() -> Bool { let url = URL(fileURLWithPath: meliDeeplink) return UIApplication.shared.canOpenURL(url) } func isMpAlreadyInstalled() -> Bool { let url = URL(fileURLWithPath: mpDeeplink) return UIApplication.shared.canOpenURL(url) } func appendLandingURLToString(_ urlString: String) -> String { if (isMeli() || isMp()), !["meli://", "mercadopago://"].contains(where: urlString.contains), let encodedURL = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { let prefix = MLBusinessAppDataService().isMeli() ? "meli://" : "mercadopago://" let landingURL = "\(prefix)webview/?url=\(encodedURL)" return landingURL } return urlString } }
mit
3655946ada2abf04974918c8e472be11
30.95
114
0.63276
4.608173
false
false
false
false
buyiyang/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketRequestManage.swift
3
6002
// // SocketPacketManage.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit //import XCGLogger class SocketRequestManage: NSObject { static let shared = SocketRequestManage(); fileprivate var socketRequests = [UInt64: SocketRequest]() fileprivate var _timer: Timer? fileprivate var _lastHeardBeatTime:TimeInterval! fileprivate var _lastConnectedTime:TimeInterval! fileprivate var _reqeustId:UInt32 = 10000 fileprivate var _socketHelper:SocketHelper? fileprivate var _sessionId:UInt64 = 0 fileprivate var timelineRequest: SocketRequest? var receiveMatching:CompleteBlock? var receiveOrderResult:CompleteBlock? var operate_code = 0 func start() { _lastHeardBeatTime = timeNow() _lastConnectedTime = timeNow() stop() _timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(didActionTimer), userInfo: nil, repeats: true) #if true _socketHelper = APISocketHelper() #else _socketHelper = LocalSocketHelper() #endif _socketHelper?.connect() } func stop() { _timer?.invalidate() _timer = nil objc_sync_enter(self) _socketHelper?.disconnect() _socketHelper = nil objc_sync_exit(self) } var sessionId:UInt64 { get { objc_sync_enter(self) if _sessionId > 2000000000 { _sessionId = 10000 } _sessionId += 1 objc_sync_exit(self) return _sessionId; } } func notifyResponsePacket(_ packet: SocketDataPacket) { objc_sync_enter(self) var socketReqeust = socketRequests[packet.session_id] if packet.operate_code == SocketConst.OPCode.timeLine.rawValue + 1{ socketReqeust = timelineRequest }else if packet.operate_code == SocketConst.OPCode.receiveMatching.rawValue { let response:SocketJsonResponse = SocketJsonResponse(packet:packet) if receiveMatching != nil{ receiveMatching!(response) } }else if packet.operate_code == SocketConst.OPCode.orderResult.rawValue{ let response:SocketJsonResponse = SocketJsonResponse(packet:packet) if receiveOrderResult != nil{ receiveOrderResult!(response) } }else if packet.operate_code == SocketConst.OPCode.onlyLogin.rawValue{ stop() NotificationCenter.default.post(name: Notification.Name.init(rawValue: AppConst.NoticeKey.onlyLogin.rawValue), object: nil, userInfo: nil) }else{ socketRequests.removeValue(forKey: packet.session_id) } objc_sync_exit(self) let response:SocketJsonResponse = SocketJsonResponse(packet:packet) let statusCode:Int = response.statusCode; if statusCode == AppConst.frozeCode{ ShareDataModel.share().controlSwitch = false return } if response.result < 0{ socketReqeust?.onError(response.result) return } if ( statusCode < 0) && packet.data?.count != 0 { socketReqeust?.onError(statusCode) } else { socketReqeust?.onComplete(response) } } func checkReqeustTimeout() { objc_sync_enter(self) for (key,reqeust) in socketRequests { if reqeust.isReqeustTimeout() { socketRequests.removeValue(forKey: key) reqeust.onError(-11011) print(">>>>>>>>>>>>>>>>>>>>>>>>>>\(key)") break } } objc_sync_exit(self) } fileprivate func sendRequest(_ packet: SocketDataPacket) { let block:()->() = { [weak self] in self?._socketHelper?.sendData(packet.serializableData()!) } objc_sync_enter(self) if _socketHelper == nil { SocketRequestManage.shared.start() let when = DispatchTime.now() + Double((Int64)(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: when,execute: block) } else { block() } objc_sync_exit(self) } func startJsonRequest(_ packet: SocketDataPacket, complete: CompleteBlock?, error: ErrorBlock?) { let socketReqeust = SocketRequest(); socketReqeust.error = error; socketReqeust.complete = complete; packet.request_id = 0; packet.session_id = sessionId; operate_code = Int(packet.operate_code) objc_sync_enter(self) if packet.operate_code == SocketConst.OPCode.timeLine.rawValue{ timelineRequest = socketReqeust } else { socketRequests[packet.session_id] = socketReqeust } objc_sync_exit(self) sendRequest(packet) } fileprivate func timeNow() ->TimeInterval { return Date().timeIntervalSince1970 } fileprivate func lastTimeNow(_ last:TimeInterval) ->TimeInterval { return timeNow() - last } fileprivate func isDispatchInterval(_ lastTime:inout TimeInterval,interval:TimeInterval) ->Bool { if timeNow() - lastTime >= interval { lastTime = timeNow() return true } return false } fileprivate func sendHeart() { let packet = SocketDataPacket(opcode: .heart,dict:[SocketConst.Key.uid: 0 as AnyObject]) sendRequest(packet) } func didActionTimer() { if _socketHelper != nil && _socketHelper!.isConnected { _lastConnectedTime = timeNow() } else if( isDispatchInterval(&_lastConnectedTime!,interval: 10) ) { _socketHelper?.connect() } checkReqeustTimeout() } }
gpl-3.0
52a9befaf68fcfbfd62f1cae3ceecf67
30.909574
150
0.595433
4.85749
false
false
false
false
grandiere/box
box/Metal/Basic/MetalColour.swift
1
1138
import UIKit import MetalKit class MetalColour:MetalBufferableProtocol { class func color(device:MTLDevice, originalColor:UIColor) -> MTLBuffer { let color:MetalColour = MetalColour(originalColor:originalColor) let metalBuffer:MTLBuffer = device.generateBuffer( bufferable:color) return metalBuffer } private let red:Float private let green:Float private let blue:Float private let alpha:Float private init(originalColor:UIColor) { var red:CGFloat = 0 var green:CGFloat = 0 var blue:CGFloat = 0 var alpha:CGFloat = 0 originalColor.getRed( &red, green:&green, blue:&blue, alpha:&alpha) self.red = Float(red) self.green = Float(green) self.blue = Float(blue) self.alpha = Float(alpha) } //MARK: bufferableProtocol func buffer() -> [Float] { let bufferArray:[Float] = [ red, green, blue ] return bufferArray } }
mit
a01568c2b68132e13df512e05d447f9b
21.313725
74
0.550967
4.741667
false
false
false
false
PeteShearer/SwiftNinja
030-Unwinding Segues/MasterDetail/MasterDetail/DetailViewController.swift
4
1239
// // DetailViewController.swift // MasterDetail // // Created by Peter Shearer on 12/12/16. // Copyright © 2016 Peter Shearer. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var episodeName: UILabel! @IBOutlet weak var episodeNumber: UILabel! @IBOutlet weak var episodeWriter: UILabel! @IBOutlet weak var episodeDoctor: UILabel! var detailItem: Episode? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let _: Episode = self.detailItem { episodeName?.text = detailItem?.episodeTitle episodeNumber?.text = detailItem?.episodeNumber episodeWriter?.text = detailItem?.writerName episodeDoctor?.text = detailItem?.doctorName detailDescriptionLabel?.text = detailItem?.synopsis } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } }
bsd-2-clause
2634dd66c7e11249fafc889171d6f5db
26.511111
80
0.634895
5.223629
false
true
false
false
rudkx/swift
test/Concurrency/Runtime/async_initializer.swift
1
3959
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking %import-libdispatch) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.1, *) actor NameGenerator { private var counter = 0 private var prefix : String init(_ title: String) { self.prefix = title } func getName() -> String { counter += 1 return "\(prefix) \(counter)" } } @available(SwiftStdlib 5.1, *) protocol Person { init() async var name : String { get set } } @available(SwiftStdlib 5.1, *) class EarthPerson : Person { private static let oracle = NameGenerator("Earthling") var name : String required init() async { self.name = await EarthPerson.oracle.getName() } init(name: String) async { self.name = await (detach { name }).get() } } @available(SwiftStdlib 5.1, *) class NorthAmericaPerson : EarthPerson { private static let oracle = NameGenerator("NorthAmerican") required init() async { await super.init() self.name = await NorthAmericaPerson.oracle.getName() } override init(name: String) async { await super.init(name: name) } } @available(SwiftStdlib 5.1, *) class PrecariousClass { init?(nilIt : Int) async { let _ : Optional<Int> = await (detach { nil }).get() return nil } init(throwIt : Double) async throws { if await (detach { 0 }).get() != 1 { throw Something.bogus } } init?(nilOrThrowIt shouldThrow: Bool) async throws { let flag = await (detach { shouldThrow }).get() if flag { throw Something.bogus } return nil } init!(crashOrThrowIt shouldThrow: Bool) async throws { let flag = await (detach { shouldThrow }).get() if flag { throw Something.bogus } return nil } } enum Something : Error { case bogus } @available(SwiftStdlib 5.1, *) struct PrecariousStruct { init?(nilIt : Int) async { let _ : Optional<Int> = await (detach { nil }).get() return nil } init(throwIt : Double) async throws { if await (detach { 0 }).get() != 1 { throw Something.bogus } } } // CHECK: Earthling 1 // CHECK-NEXT: Alice // CHECK-NEXT: Earthling 2 // CHECK-NEXT: Bob // CHECK-NEXT: Earthling 3 // CHECK-NEXT: Alex // CHECK-NEXT: NorthAmerican 1 // CHECK-NEXT: NorthAmerican 2 // CHECK-NEXT: Earthling 6 // CHECK-NEXT: class was nil // CHECK-NEXT: class threw // CHECK-NEXT: nilOrThrowIt init was nil // CHECK-NEXT: nilOrThrowIt init threw // CHECK-NEXT: crashOrThrowIt init threw // CHECK-NEXT: struct was nil // CHECK-NEXT: struct threw // CHECK: done @available(SwiftStdlib 5.1, *) @main struct RunIt { static func main() async { let people : [Person] = [ await EarthPerson(), await NorthAmericaPerson(name: "Alice"), await EarthPerson(), await NorthAmericaPerson(name: "Bob"), await EarthPerson(), await NorthAmericaPerson(name: "Alex"), await NorthAmericaPerson(), await NorthAmericaPerson(), await EarthPerson() ] for p in people { print(p.name) } // ---- if await PrecariousClass(nilIt: 0) == nil { print("class was nil") } do { let _ = try await PrecariousClass(throwIt: 0.0) } catch { print("class threw") } if try! await PrecariousClass(nilOrThrowIt: false) == nil { print("nilOrThrowIt init was nil") } do { let _ = try await PrecariousClass(nilOrThrowIt: true) } catch { print("nilOrThrowIt init threw") } do { let _ = try await PrecariousClass(crashOrThrowIt: true) } catch { print("crashOrThrowIt init threw") } if await PrecariousStruct(nilIt: 0) == nil { print("struct was nil") } do { let _ = try await PrecariousStruct(throwIt: 0.0) } catch { print("struct threw") } print("done") } }
apache-2.0
8bd151217ddf8c3b68c28f1dfcc0a69b
21.494318
130
0.639808
3.93148
false
false
false
false
youngsoft/TangramKit
TangramKit/TGPathLayout.swift
1
43363
// // TGPathLayout.swift // TangramKit // // Created by X on 2016/12/5. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** * 定义子视图在路径布局中的距离的类型。 */ public enum TGPathSpaceType{ /// 浮动距离,子视图之间的距离根据路径布局的尺寸和子视图的数量而确定。 case flexed /// 固定距离,就是子视图之间的距离是固定的某个数值。 case fixed(CGFloat) /// 固定数量距离,就是子视图之间的距离根据路径布局的尺寸和某个具体的数量而确定。 case count(Int) } /** * 实现枚举类TGPathSpaceType的比较接口 */ extension TGPathSpaceType : Equatable{ public static func ==(lhs: TGPathSpaceType, rhs: TGPathSpaceType) -> Bool { switch (lhs,rhs) { case ( TGPathSpaceType.flexed , TGPathSpaceType.flexed): return true case (let TGPathSpaceType.fixed(value1),let TGPathSpaceType.fixed(value2)): return value1 == value2 case (let TGPathSpaceType.count(count1),let TGPathSpaceType.count(count2)): return count1 == count2 default: return false } } } /** * 坐标轴设置类,用来描述坐标轴的信息。一个坐标轴具有原点、坐标系类型、开始和结束点、坐标轴对应的值这四个方面的内容。 */ open class TGCoordinateSetting { /** * 坐标原点的位置,位置是相对位置,默认是(0,0), 假如设置为(0.5,0.5)则在视图的中间。 */ public var origin : CGPoint = CGPoint.zero { didSet{ if !_tgCGPointEqual(oldValue, origin){ pathLayout?.setNeedsLayout() } } } /** * 指定是否是数学坐标系,默认为NO,表示绘图坐标系。 数学坐标系y轴向上为正,向下为负;绘图坐标系则反之。 */ public var isMath : Bool = false{ didSet{ if isMath != oldValue{ pathLayout?.setNeedsLayout() } } } /** * 指定是否是y轴和x轴互换,默认为NO,如果设置为YES则方程提供的变量是y轴的值,方程返回的是x轴的值。 */ public var isReverse : Bool = false{ didSet{ if isReverse != oldValue{ pathLayout?.setNeedsLayout() } } } /** * 开始位置和结束位置。如果不设置则根据坐标原点设置以及视图的尺寸自动确定.默认是nil */ public var start:CGFloat! { didSet{ if start != oldValue { pathLayout?.setNeedsLayout() } } } public var end:CGFloat! { didSet{ if end != oldValue { pathLayout?.setNeedsLayout() } } } public weak var pathLayout : TGPathLayout? init(pathLayout:TGPathLayout) { self.pathLayout = pathLayout } /** * 恢复默认设置 */ public func reset(){ start = nil end = nil isMath = false isReverse = false origin = CGPoint.zero pathLayout?.setNeedsLayout() } } /** *路径布局类。路径布局通过坐标轴的设置,曲线路径函数方程,子视图中心点之间的距离三个要素来确定其中子视图的位置。因此通过路径布局可以实现一些非常酷炫的布局效果。 */ open class TGPathLayout : TGBaseLayout,TGPathLayoutViewSizeClass { /* 你可以从TGPathLayout中派生出一个子类。并实现如下方法: +(Class)layerClass { return [CAShapeLayer class]; } 也就是说TGPathLayout的派生类返回一个CAShapeLayer,那么系统将自动会在每次布局时将layer的path属性进行赋值操作。 */ /** * 坐标系设置,您可以调整坐标系的各种参数来完成下列两个方法中的坐标到绘制的映射转换。 */ public private(set) lazy var tg_coordinateSetting : TGCoordinateSetting = { [unowned self] in return TGCoordinateSetting(pathLayout:self) }() /** * 直角坐标普通方程,x是坐标系里面x轴的位置,返回y = f(x)。要求函数在定义域内是连续的,否则结果不确定。如果返回的y无效则函数要返回nil */ public var tg_rectangularEquation : ((CGFloat)->CGFloat?)?{ didSet{ if tg_rectangularEquation != nil{ tg_parametricEquation = nil tg_polarEquation = nil setNeedsLayout() } } } /** * 直角坐标参数方程,t是参数, 返回CGPoint是x轴和y轴的值。要求函数在定义域内是连续的,否则结果不确定。如果返回的点无效,则请返回nil */ public var tg_parametricEquation : ((CGFloat)->CGPoint?)?{ didSet{ if tg_parametricEquation != nil { tg_rectangularEquation = nil tg_polarEquation = nil setNeedsLayout() } } } /** * 极坐标方程,入参是极坐标的弧度,返回r半径。要求函数在定义域内是连续的,否则结果不确定。如果返回的点无效,则请返回nil */ public var tg_polarEquation : ((TGRadian)->CGFloat?)?{ didSet{ if tg_polarEquation != nil { tg_rectangularEquation = nil tg_parametricEquation = nil setNeedsLayout() } } } /** * 设置子视图在路径曲线上的距离的类型,一共有flexed, fixed, count,默认是flexed, */ public var tg_spaceType : TGPathSpaceType = TGPathSpaceType.flexed { didSet{ if tg_spaceType != oldValue { setNeedsLayout() } } } /** * 设置和获取布局视图中的原点视图,默认是nil。如果设置了原点视图则总会将原点视图作为布局视图中的最后一个子视图。原点视图将会显示在路径的坐标原点中心上,因此原点布局是不会参与在路径中的布局的。因为中心原点视图是布局视图中的最后一个子视图,而TGPathLayout重写了addSubview方法,因此可以正常的使用这个方法来添加子视图。 */ public var tg_originView : UIView?{ get{ return tgHasOriginView && subviews.count > 0 ? subviews.last : nil } set{ guard tgHasOriginView else { if (newValue != nil){ super.addSubview(newValue!) tgHasOriginView = true } return } guard let originView = newValue else { if subviews.count > 0{ subviews.last?.removeFromSuperview() tgHasOriginView = false } return } if subviews.count > 0 { if subviews.last != originView{ subviews.last?.removeFromSuperview() super.addSubview(originView) } }else{ addSubview(originView) } } } /** * 返回布局视图中所有在曲线路径中排列的子视图。如果设置了原点视图则返回subviews里面除最后一个子视图外的所有子视图,如果没有原点子视图则返回subviews */ public var tg_pathSubviews : [UIView]{ get{ guard tgHasOriginView && subviews.count > 0 else { return subviews } var pathsbs = [UIView]() for i in 0..<subviews.count-1{ pathsbs.append(subviews[i]) } return pathsbs } } /** * 设置获取子视图距离的误差值。默认是0.5,误差越小则距离的精确值越大,误差最低值不能<=0。一般不需要调整这个值,只有那些要求精度非常高的场景才需要微调这个值,比如在一些曲线路径较短的情况下,通过调小这个值来子视图之间间距的精确计算。 */ public var tg_distanceError : CGFloat = 0.5 /** * 得到子视图在曲线路径中定位时的函数的自变量的值。也就是说在函数中当值等于下面的返回值时,这个视图的位置就被确定了。方法如果返回nil则表示这个子视图没有定位。 */ public func tg_argumentFrom(subview:UIView)->CGFloat?{ #if swift(>=5.0) guard let index = subviews.firstIndex(of: subview) else { return nil } #else guard let index = subviews.index(of: subview) else { return nil } #endif if tg_originView == subview { return nil } if index < tgArgumentArray.count{ if (self.tg_polarEquation != nil) { return CGFloat(TGRadian(angle:tgArgumentArray[index])) } else { return tgArgumentArray[index] } } return nil } /** * 下面三个函数用来获取两个子视图之间的曲线路径数据,在调用tg_getSubviewPathPoint方法之前请先调用tg_beginSubviewPathPoint方法,而调用完毕后请调用endSubviewPathPoint方法,否则getSubviewPathPoint返回的结果未可知。 */ //开始和结束获取子视图路径数据的方法,full表示getSubviewPathPoint获取的是否是全部路径点。如果为NO则只会获取子视图的位置的点。 public func tg_beginSubviewPathPoint(full:Bool){ var pointIndexs:[Int]? = full ? [Int]() : nil tgPathPoints = tgCalcPoints(sbs: tg_pathSubviews, path: nil, pointIndexArray: &pointIndexs) tgPointIndexs = full ? pointIndexs : nil } public func tg_endSubviewPathPoint(){ tgPathPoints = nil tgPointIndexs = nil } /** * 创建从某个子视图到另外一个子视图之间的路径点,返回NSValue数组,里面的值是CGPoint。 * fromIndex指定开始的子视图的索引位置,toIndex指定结束的子视图的索引位置。如果有原点子视图时,这两个索引值不能算上原点子视图的索引值。 */ public func tg_getSubviewPathPoint(fromIndex:Int,toIndex:Int) -> [CGPoint]?{ if tgPathPoints == nil { return nil } let realFromIndex = fromIndex let realToIndex = toIndex if realFromIndex == realToIndex { return [CGPoint]() } //要求外界传递进来的索引要考虑原点视图的索引。 var retPoints = [CGPoint]() if realFromIndex < realToIndex { var start : Int var end : Int if tgPointIndexs == nil { start = realFromIndex end = realToIndex }else{ if tgPointIndexs!.count <= realFromIndex || tgPointIndexs!.count <= realToIndex { return nil } start = tgPointIndexs![realFromIndex] end = tgPointIndexs![realToIndex] } for i in start...end { retPoints.append(tgPathPoints![i]) } }else{ if tgPointIndexs!.count <= realFromIndex || tgPointIndexs!.count <= realToIndex { return nil } var end = tgPointIndexs![realFromIndex] let start = tgPointIndexs![realToIndex] while end >= start { retPoints.append(tgPathPoints![end]) end-=1 } } return retPoints } /** * 创建布局的曲线的路径。用户需要负责销毁返回的值。调用者可以用这个方法来获得曲线的路径,进行一些绘制的工作。 * subviewCount:指定这个路径上子视图的数量的个数,如果设置为-1则是按照布局视图的子视图的数量来创建。需要注意的是如果布局视图的tg_spaceType为.flexed,.count的话则这个参数设置无效。 */ public func tg_createPath(subviewCount:Int) -> CGPath{ let retPath = CGMutablePath() var pathLen : CGFloat? = nil var pointIndexArray : [Int]? = [] switch tg_spaceType { case let .fixed(value): var subviewCount = subviewCount if subviewCount == -1{ subviewCount = tg_pathSubviews.count } _ = tgCalcPathPoints(showPath: retPath, pPathLen: &pathLen, subviewCount: subviewCount, pointIndexArray: &pointIndexArray, viewSpace: value) default: _ = tgCalcPathPoints(showPath: retPath, pPathLen: &pathLen, subviewCount: -1, pointIndexArray: &pointIndexArray, viewSpace: 0) } return retPath } open override func insertSubview(_ view: UIView, at index: Int) { var index = index if tg_originView != nil { if index == subviews.count { index -= 1 } } super.insertSubview(view, at: index) } open override func addSubview(_ view: UIView) { if tg_originView != nil { super.insertSubview(view, at: subviews.count - 1) }else{ super.addSubview(view) } } #if swift(>=4.2) open override func sendSubviewToBack(_ view: UIView) { if tg_originView == view { return } super.sendSubviewToBack(view) } #else open override func sendSubview(toBack view: UIView) { if tg_originView == view { return } super.sendSubview(toBack: view) } #endif open override func willRemoveSubview(_ subview: UIView) { super.willRemoveSubview(subview) if tgHasOriginView { if subviews.count > 0 && subview == subviews.last{ tgHasOriginView = false } } } override internal func tgCalcLayoutRect(_ size:CGSize, isEstimate:Bool, hasSubLayout:inout Bool!, sbs:[UIView]!, type :TGSizeClassType) -> CGSize { var selfSize = super.tgCalcLayoutRect(size, isEstimate:isEstimate, hasSubLayout:&hasSubLayout, sbs:sbs, type:type) var sbs:[UIView]! = sbs if sbs == nil { sbs = tgGetLayoutSubviews() } let lsc = self.tgCurrentSizeClass as! TGPathLayoutViewSizeClassImpl let sbs2:[UIView] = sbs for sbv in sbs{ let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate{ sbvtgFrame.frame = sbv.bounds tgCalcSizeFromSizeWrapSubview(sbv,sbvsc:sbvsc, sbvtgFrame:sbvtgFrame) } if sbv.isKind(of: TGBaseLayout.self){ let sbvl = sbv as! TGBaseLayout if hasSubLayout != nil && sbvsc.isSomeSizeWrap { hasSubLayout = true } if isEstimate && (sbvsc.isSomeSizeWrap){ _ = sbvl.tg_sizeThatFits(sbvtgFrame.frame.size, inSizeClass: type) if sbvtgFrame.multiple { sbvtgFrame.sizeClass = sbv.tgMatchBestSizeClass(type) //因为tg_sizeThatFits执行后会还原,所以这里要重新设置 } } } } // var maxSize = CGSize(width: lsc.tgLeftPadding, height: lsc.tgTopPadding) //记录最小的y值和最大的y值 var minYPos = CGFloat.greatestFiniteMagnitude var maxYPos = -CGFloat.greatestFiniteMagnitude var minXPos = CGFloat.greatestFiniteMagnitude var maxXPos = -CGFloat.greatestFiniteMagnitude //算路径子视图的。 sbs = tgGetLayoutSubviewsFrom(sbsFrom: tg_pathSubviews) var path:CGMutablePath? = nil if layer.isKind(of: CAShapeLayer.self) && !isEstimate{ path = CGMutablePath() } var pointIndexArray : [Int]? = nil let pts = tgCalcPoints(sbs: sbs, path: path, pointIndexArray: &pointIndexArray) if (path != nil){ let slayer = layer as! CAShapeLayer slayer.path = path } for i in 0..<sbs.count{ let sbv = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) var pt = CGPoint.zero if pts != nil && pts!.count > i{ pt = pts![i] } //计算得到最大的高度和最大的宽度。 var rect = sbv.tgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) if let t = sbvsc.width.sizeVal { if t === lsc.width.realSize{ rect.size.width = sbvsc.width.measure(selfSize.width - lsc.tgLeftPadding - lsc.tgRightPadding) }else{ rect.size.width = sbvsc.width.measure(t.view.tg_estimatedFrame.size.width) } } rect.size.width = tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) rect.size.height = sbvsc.height.numberSize(rect.size.height) if let t = sbvsc.height.sizeVal { if t === lsc.height.realSize{ rect.size.height = sbvsc.height.measure(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) }else{ rect.size.height = sbvsc.height.measure(t.view.tg_estimatedFrame.size.height) } } if sbvsc.height.isFlexHeight { rect.size.height = tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) //中心点的位置。。 let leftMargin = sbvsc.left.absPos let topMargin = sbvsc.top.absPos let rightMargin = sbvsc.right.absPos let bottomMargin = sbvsc.bottom.absPos rect.origin.x = pt.x - rect.size.width * sbv.layer.anchorPoint.x + leftMargin - rightMargin rect.origin.y = pt.y - rect.size.height * sbv.layer.anchorPoint.y + topMargin - bottomMargin if _tgCGFloatLess(rect.minY , minYPos) { minYPos = rect.minY } if _tgCGFloatGreat(rect.maxY , maxYPos) { maxYPos = rect.maxY } if _tgCGFloatLess(rect.minX , minXPos) { minXPos = rect.minX } if _tgCGFloatGreat(rect.maxX , maxXPos) { maxXPos = rect.maxX } sbvtgFrame.frame = rect } //特殊填充中心视图。 if let sbv = tg_originView{ let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) var rect = sbvtgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) if let t = sbvsc.width.sizeVal { if t === lsc.width.realSize { rect.size.width = sbvsc.width.measure(selfSize.width - lsc.tgLeftPadding - lsc.tgRightPadding) }else{ rect.size.width = sbvsc.width.measure(t.view.tg_estimatedFrame.size.width) } } rect.size.width = tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) rect.size.height = sbvsc.height.numberSize(rect.size.height) if let t = sbvsc.height.sizeVal { if (t === lsc.height.realSize){ rect.size.height = sbvsc.height.measure(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) }else{ rect.size.height = sbvsc.height.measure(t.view.tg_estimatedFrame.size.height) } } if sbvsc.height.isFlexHeight { rect.size.height = tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) //位置在原点位置。。 let leftMargin = sbvsc.left.absPos let topMargin = sbvsc.top.absPos let rightMargin = sbvsc.right.absPos let bottomMargin = sbvsc.bottom.absPos rect.origin.x = (selfSize.width - lsc.tgLeftPadding - lsc.tgRightPadding)*tg_coordinateSetting.origin.x - rect.size.width * sbv.layer.anchorPoint.x + leftMargin - rightMargin + lsc.tgLeftPadding rect.origin.y = (selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding)*tg_coordinateSetting.origin.y - rect.size.height * sbv.layer.anchorPoint.y + topMargin - bottomMargin + lsc.tgTopPadding if _tgCGFloatLess(rect.minY , minYPos) { minYPos = rect.minY } if _tgCGFloatGreat(rect.maxY , maxYPos) { maxYPos = rect.maxY } if _tgCGFloatLess(rect.minX , minXPos) { minXPos = rect.minX } if _tgCGFloatGreat(rect.maxX , maxXPos) { maxXPos = rect.maxX } sbv.tgFrame.frame = rect } if minYPos == CGFloat.greatestFiniteMagnitude { minYPos = 0 } if maxYPos == -CGFloat.greatestFiniteMagnitude { maxYPos = lsc.tgTopPadding + lsc.tgBottomPadding } if minXPos == CGFloat.greatestFiniteMagnitude { minXPos = 0 } if maxXPos == -CGFloat.greatestFiniteMagnitude { maxXPos = lsc.tgLeftPadding + lsc.tgRightPadding } if lsc.width.isWrap { selfSize.width = maxXPos - minXPos } if lsc.height.isWrap { selfSize.height = maxYPos - minYPos } tgAdjustLayoutSelfSize(selfSize: &selfSize, lsc: lsc) tgAdjustSubviewsLayoutTransform(sbs: sbs, lsc: lsc, selfSize: selfSize) return self.tgAdjustSizeWhenNoSubviews(size: selfSize, sbs: sbs2, lsc:lsc) } override func tgCreateInstance() -> AnyObject { return TGPathLayoutViewSizeClassImpl(view:self) } fileprivate var tgHasOriginView = false fileprivate var tgPathPoints : [CGPoint]? fileprivate var tgPointIndexs : [Int]? fileprivate var tgArgumentArray = { return [CGFloat]() }() } //MARK: -- Private Method extension TGPathLayout{ fileprivate func tgCalcPoints(sbs:[UIView],path:CGMutablePath?,pointIndexArray:inout [Int]?) -> [CGPoint]?{ if sbs.count > 0{ var pathLen : CGFloat? = nil var sbvcount = sbs.count switch tg_spaceType { case let TGPathSpaceType.fixed(value): return tgCalcPathPoints(showPath: path, pPathLen: &pathLen, subviewCount: sbs.count, pointIndexArray: &pointIndexArray, viewSpace: value) case let TGPathSpaceType.count(count): sbvcount = count default: break } pathLen = 0 let tempArray = tgCalcPathPoints(showPath: path, pPathLen: &pathLen, subviewCount: -1, pointIndexArray: &pointIndexArray, viewSpace: 0) var bClose = false if tempArray.count > 1{ let p1 = tempArray.first let p2 = tempArray.last bClose = tgCalcDistance(pt1: p1!, pt2: p2!) <= 1 } var viewSpace : CGFloat = 0 if sbvcount > 1{ let n = bClose ? 0 : 1 viewSpace = pathLen! / CGFloat(sbvcount - n) } pathLen = nil return tgCalcPathPoints(showPath: nil, pPathLen: &pathLen, subviewCount: sbs.count, pointIndexArray: &pointIndexArray, viewSpace: viewSpace) } return nil } fileprivate func tgCalcPathPoints(showPath:CGMutablePath?, pPathLen:inout CGFloat?, subviewCount:Int, pointIndexArray:inout [Int]?, viewSpace:CGFloat) ->[CGPoint] { var pathPointArray = [CGPoint]() let lsc = self.tgCurrentSizeClass as! TGLayoutViewSizeClassImpl let selfWidth = bounds.width - lsc.tgLeftPadding - lsc.tgRightPadding let selfHeight = bounds.height - lsc.tgTopPadding - lsc.tgBottomPadding var startArg : CGFloat var endArg : CGFloat if let rectangularEquation = tg_rectangularEquation{ startArg = 0 - selfWidth*tg_coordinateSetting.origin.x if tg_coordinateSetting.isReverse{ if tg_coordinateSetting.isMath{ startArg = -1 * selfHeight * (1 - tg_coordinateSetting.origin.y) }else{ startArg = selfHeight * (0 - tg_coordinateSetting.origin.y) } } if tg_coordinateSetting.start != nil{ startArg = tg_coordinateSetting.start } endArg = selfWidth - selfWidth * tg_coordinateSetting.origin.x if tg_coordinateSetting.isReverse{ if tg_coordinateSetting.isMath{ endArg = -1 * selfHeight * (0 - tg_coordinateSetting.origin.y) }else{ endArg = selfHeight * (1 - tg_coordinateSetting.origin.y) } } if tg_coordinateSetting.end != nil { endArg = tg_coordinateSetting.end } tgCalcPathPointsHelper(pathPointArray: &pathPointArray, showPath: showPath, pPathLen: &pPathLen, subviewCount: subviewCount, pointIndexArray: &pointIndexArray, viewSpace: viewSpace, startArg: startArg, endArg: endArg){ arg in if let val = rectangularEquation(arg){ if tg_coordinateSetting.isReverse{ let x = val + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y = (tg_coordinateSetting.isMath ? -arg : arg) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y) }else{ let x = arg + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y = (tg_coordinateSetting.isMath ? -val : val) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y) } }else{ return nil } } } else if let parametricEquation = tg_parametricEquation{ startArg = 0 - selfWidth * tg_coordinateSetting.origin.x if tg_coordinateSetting.isReverse{ if tg_coordinateSetting.isMath{ startArg = -1 * selfHeight * (1 - tg_coordinateSetting.origin.y) }else{ startArg = selfHeight * (0 - tg_coordinateSetting.origin.y) } } if tg_coordinateSetting.start != nil{ startArg = tg_coordinateSetting.start } endArg = selfWidth - selfWidth * tg_coordinateSetting.origin.x if tg_coordinateSetting.isReverse{ if tg_coordinateSetting.isMath{ endArg = -1 * selfHeight * (0 - tg_coordinateSetting.origin.y) }else{ endArg = selfHeight * (1 - tg_coordinateSetting.origin.y) } } if tg_coordinateSetting.end != nil{ endArg = tg_coordinateSetting.end } tgCalcPathPointsHelper(pathPointArray: &pathPointArray, showPath: showPath, pPathLen: &pPathLen, subviewCount: subviewCount, pointIndexArray: &pointIndexArray, viewSpace: viewSpace, startArg: startArg, endArg: endArg){ arg in if let val = parametricEquation(arg){ if tg_coordinateSetting.isReverse{ let x = val.y + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y = (tg_coordinateSetting.isMath ? -val.x : val.x) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y) }else{ let x = val.x + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y = (tg_coordinateSetting.isMath ? -val.y : val.y) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y) } }else{ return nil } } } else if let polarEquation = tg_polarEquation{ startArg = 0 if tg_coordinateSetting.start != nil { startArg = TGRadian(value:tg_coordinateSetting.start).angle } endArg = 360 if tg_coordinateSetting.end != nil { endArg = TGRadian(value:tg_coordinateSetting.end).angle } tgCalcPathPointsHelper(pathPointArray: &pathPointArray, showPath: showPath, pPathLen: &pPathLen, subviewCount: subviewCount, pointIndexArray: &pointIndexArray, viewSpace: viewSpace, startArg: startArg, endArg: endArg){ arg in //计算用弧度 let rad = TGRadian(angle:arg) if let r = polarEquation(rad){ if tg_coordinateSetting.isReverse{ let y = r * cos(rad.value) let x = r * sin(rad.value) + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y1 = (tg_coordinateSetting.isMath ? -y : y) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y1) }else{ let y = r * sin(rad.value) let x = r * cos(rad.value) + selfWidth * tg_coordinateSetting.origin.x + lsc.tgLeftPadding let y1 = (tg_coordinateSetting.isMath ? -y : y) + selfHeight * tg_coordinateSetting.origin.y + lsc.tgTopPadding return CGPoint(x: x, y: y1) } }else{ return nil } } } return pathPointArray } fileprivate func tgCalcPathPointsHelper(pathPointArray:inout [CGPoint], showPath:CGMutablePath?, pPathLen:inout CGFloat?, subviewCount:Int, pointIndexArray:inout [Int]?, viewSpace:CGFloat, startArg:CGFloat, endArg:CGFloat, function:(CGFloat)->CGPoint?) { if tg_distanceError <= 0{ tg_distanceError = 0.5 } tgArgumentArray.removeAll() var distance : CGFloat = 0 var lastXY = CGPoint.zero var arg = startArg var lastValidArg = arg var isStart = true var startCount = 0 var subviewCount = subviewCount while (true){ if (subviewCount < 0){ if (arg - endArg > 0.1){ //这里不能用arg > endArg 的原因是有精度问题。 break } }else if (subviewCount == 0){ break }else{ if (isStart && startCount >= 1){ if (pointIndexArray != nil){ pointIndexArray!.append(pathPointArray.count) } pathPointArray.append(lastXY) tgArgumentArray.append(arg) showPath?.addLine(to: lastXY) break } } var realXY = function(arg) if realXY != nil{ if (isStart){ isStart = false startCount += 1 if (subviewCount > 0 && startCount == 1){ subviewCount-=1 lastValidArg = arg pointIndexArray?.append(pathPointArray.count) tgArgumentArray.append(arg) } pathPointArray.append(realXY!) showPath?.move(to: realXY!) }else{ if (subviewCount >= 0){ let oldDistance = distance distance += tgCalcDistance(pt1: realXY!, pt2: lastXY) if (distance >= viewSpace){ if (distance - viewSpace >= tg_distanceError){ realXY = tgGetNearestDistancePoint(startArg: arg, lastXY: lastXY, distance: oldDistance, viewSpace: viewSpace, pLastValidArg: &lastValidArg, function: function) }else{ lastValidArg = arg } if (pointIndexArray == nil){ pathPointArray.append(realXY!) }else{ pointIndexArray!.append(pathPointArray.count) } distance = 0 subviewCount -= 1 tgArgumentArray.append(lastValidArg) }else if (distance - viewSpace > -1 * tg_distanceError){ if (pointIndexArray == nil){ pathPointArray.append(realXY!) }else{ pointIndexArray!.append(pathPointArray.count) } distance = 0 subviewCount -= 1 lastValidArg = arg tgArgumentArray.append(arg) }else{ lastValidArg = arg } }else{ if (pointIndexArray == nil){ pathPointArray.append(realXY!) } } if (pointIndexArray != nil){ pathPointArray.append(realXY!) } showPath?.addLine(to: realXY!) if (pPathLen != nil){ pPathLen! += tgCalcDistance(pt1: realXY!, pt2: lastXY) } } lastXY = realXY! }else{ isStart = true } arg += 1 } } fileprivate func tgCalcDistance(pt1:CGPoint,pt2:CGPoint) -> CGFloat{ return sqrt(pow(pt1.x - pt2.x, 2) + pow(pt1.y - pt2.y, 2)) } fileprivate func tgGetNearestDistancePoint(startArg:CGFloat, lastXY:CGPoint, distance:CGFloat, viewSpace:CGFloat, pLastValidArg:inout CGFloat, function:(CGFloat)->CGPoint?) -> CGPoint { //判断pLastValidArg和Arg的差距如果超过1则按pLastValidArg + 1作为开始计算的变量。 var startArg = startArg var lastXY = lastXY if startArg - pLastValidArg > 1{ startArg = pLastValidArg + 1 } var step : CGFloat = 1 var distance = distance while true { var arg = startArg - step + step/10 while arg - startArg < 0.0001{ if let realXY = function(arg){ let oldDistance = distance distance += tgCalcDistance(pt1: realXY, pt2: lastXY) if distance >= viewSpace{ if distance - viewSpace <= tg_distanceError{ pLastValidArg = arg return realXY }else{ distance = oldDistance break } } lastXY = realXY } arg += step / 10 } if arg > startArg { startArg += 1 step = 1 }else{ startArg = arg step /= 10 } if step <= 0.0001 { pLastValidArg = arg break } } return lastXY } } // MARK: - TGRadian 弧度类 /// 弧度类 TGRadian(angle:90).value public struct TGRadian: Any { public private(set) var value:CGFloat //用角度值构造出一个弧度对象。 public init(angle:CGFloat) { value = angle / 180 * .pi } public init(angle: Int) { self.init(angle:CGFloat(angle)) } public init(angle: Int8) { self.init(angle:CGFloat(angle)) } public init(angle: Int16) { self.init(angle:CGFloat(angle)) } public init(angle: Int32) { self.init(angle:CGFloat(angle)) } public init(angle: Int64) { self.init(angle:CGFloat(angle)) } public init(angle: UInt) { self.init(angle:CGFloat(angle)) } public init(angle: UInt8) { self.init(angle:CGFloat(angle)) } public init(angle: UInt16) { self.init(angle:CGFloat(angle)) } public init(angle: UInt32) { self.init(angle:CGFloat(angle)) } public init(angle: UInt64) { self.init(angle:CGFloat(angle)) } public init(angle: Double) { self.init(angle:CGFloat(angle)) } public init(angle: Float) { self.init(angle:CGFloat(angle)) } //用弧度值构造出一个弧度对象。 public init(value:CGFloat) { self.value = value } public init(value: Int) { self.init(value:CGFloat(value)) } public init(value: Int8) { self.init(value:CGFloat(value)) } public init(value: Int16) { self.init(value:CGFloat(value)) } public init(value: Int32) { self.init(value:CGFloat(value)) } public init(value: Int64) { self.init(value:CGFloat(value)) } public init(value: UInt) { self.init(value:CGFloat(value)) } public init(value: UInt8) { self.init(value:CGFloat(value)) } public init(value: UInt16) { self.init(value:CGFloat(value)) } public init(value: UInt32) { self.init(value:CGFloat(value)) } public init(value: UInt64) { self.init(value:CGFloat(value)) } public init(value: Double) { self.init(value:CGFloat(value)) } public init(value: Float) { self.init(value:CGFloat(value)) } public init(_ val: TGRadian) { self.value = val.value } //角度值 public var angle:CGFloat { return self.value / .pi * 180 } } extension TGRadian:Equatable{ public static func ==(lhs: TGRadian, rhs: TGRadian) -> Bool { return lhs.value == rhs.value } } //弧度运算符重载。 public func +(lhs:TGRadian, rhs:CGFloat) ->CGFloat { return lhs.value + rhs } public func +(lhs:CGFloat, rhs:TGRadian) ->CGFloat { return lhs + rhs.value } public func *(lhs:TGRadian, rhs:CGFloat) ->CGFloat { return lhs.value * rhs } public func *(lhs:CGFloat, rhs:TGRadian) ->CGFloat { return lhs * rhs.value } public func /(lhs:TGRadian, rhs:CGFloat) ->CGFloat { return lhs.value / rhs } public func /(lhs:CGFloat, rhs:TGRadian) ->CGFloat { return lhs / rhs.value } public func -(lhs:TGRadian, rhs:CGFloat) ->CGFloat { return lhs.value - rhs } public func -(lhs:CGFloat, rhs:TGRadian) ->CGFloat { return lhs - rhs.value } //扩展CGFloat类型的初始化方法,用一个弧度对象来构造CGFloat值,得到的是一个弧度值。 extension CGFloat { public init(_ value: TGRadian) { self.init(value.value) } } postfix operator ° /// 弧度对象的初始化简易方法:90° <==> TGRadian(angle:90) public postfix func °(_ angle:CGFloat) -> TGRadian { return TGRadian(angle:angle) } public postfix func °(_ angle:Int) -> TGRadian { return TGRadian(angle:angle) } public postfix func °(_ angle:UInt) -> TGRadian { return TGRadian(angle:angle) }
mit
b48f476f2e9882aecbb40ae487a51ad9
30.587214
230
0.506109
4.833454
false
false
false
false
lady12/firefox-ios
Client/Frontend/Settings/Clearables.swift
9
5982
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared // A base protocol for something that can be cleared. protocol Clearable { func clear() -> Success } class ClearableError : MaybeErrorType { private let msg: String init(msg: String) { self.msg = msg } var description: String { return msg } } // Clears our browsing history, including favicons and thumbnails. class HistoryClearable : Clearable { let profile: Profile init(profile: Profile) { self.profile = profile } // TODO: This can be cleaned up! func clear() -> Success { let deferred = Success() profile.history.clearHistory().upon { success in SDImageCache.sharedImageCache().clearDisk() SDImageCache.sharedImageCache().clearMemory() deferred.fill(Maybe(success: ())) } return deferred } } // Clear all stored passwords. This will clear both Firefox's SQLite storage and the system shared // Credential storage. class PasswordsClearable : Clearable { let profile: Profile init(profile: Profile) { self.profile = profile } func clear() -> Success { // Clear our storage return profile.logins.removeAll() >>== { res in let storage = NSURLCredentialStorage.sharedCredentialStorage() let credentials = storage.allCredentials for (space, credentials) in credentials { for (_, credential) in credentials { storage.removeCredential(credential, forProtectionSpace: space) } } return succeed() } } } struct ClearableErrorType: MaybeErrorType { let err: ErrorType init(err: ErrorType) { self.err = err } var description: String { return "Couldn't clear: \(err)." } } // Clear the web cache. Note, this has to close all open tabs in order to ensure the data // cached in them isn't flushed to disk. class CacheClearable : Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } func clear() -> Success { // First ensure we close all open tabs first. tabManager.removeAll() // Reset the process pool to ensure no cached data is written back tabManager.resetProcessPool() // Remove the basic cache. NSURLCache.sharedURLCache().removeAllCachedResponses() // Now lets finish up by destroying our Cache directory. do { try deleteLibraryFolderContents("Caches") } catch { return deferMaybe(ClearableErrorType(err: error)) } return succeed() } } private func deleteLibraryFolderContents(folder: String) throws { let manager = NSFileManager.defaultManager() let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0] let dir = library.URLByAppendingPathComponent(folder) let contents = try manager.contentsOfDirectoryAtPath(dir.path!) for content in contents { try manager.removeItemAtURL(dir.URLByAppendingPathComponent(content)) } } private func deleteLibraryFolder(folder: String) throws { let manager = NSFileManager.defaultManager() let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0] let dir = library.URLByAppendingPathComponent(folder) try manager.removeItemAtURL(dir) } // Removes all site data stored for sites. This should include things like IndexedDB or websql storage. class SiteDataClearable : Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } func clear() -> Success { // First, close all tabs to make sure they don't hold any thing in memory. tabManager.removeAll() // Then we just wipe the WebKit directory from our Library. do { try deleteLibraryFolder("WebKit") } catch { return deferMaybe(ClearableErrorType(err: error)) } return succeed() } } // Remove all cookies stored by the site. class CookiesClearable : Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } func clear() -> Success { // First close all tabs to make sure they aren't holding anything in memory. tabManager.removeAll() // Now we wipe the system cookie store (for our app). let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage() if let cookies = storage.cookies { for cookie in cookies { storage.deleteCookie(cookie ) } } // And just to be safe, we also wipe the Cookies directory. do { try deleteLibraryFolderContents("Cookies") } catch { return deferMaybe(ClearableErrorType(err: error)) } return succeed() } } // A Clearable designed to clear all of the locally stored data for our app. class EverythingClearable: Clearable { private let clearables: [Clearable] init(profile: Profile, tabmanager: TabManager) { clearables = [ HistoryClearable(profile: profile), CacheClearable(tabManager: tabmanager), CookiesClearable(tabManager: tabmanager), SiteDataClearable(tabManager: tabmanager), PasswordsClearable(profile: profile), ] } func clear() -> Success { let deferred = Success() all(clearables.map({ clearable in clearable.clear() })).upon({ result in deferred.fill(Maybe(success: ())) }) return deferred } }
mpl-2.0
5c03caa504f18d24f9d3570cec7ddcd7
29.365482
113
0.644099
5.078098
false
false
false
false
ahoppen/swift
test/Generics/rdar78233378.swift
6
999
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // CHECK-LABEL: rdar78233378.(file).P1@ // CHECK-LABEL: Requirement signature: <Self where Self : P4, Self == Self.[P1]T1.[P5]T2, Self.[P1]T1 : P2> public protocol P1: P4 where T1.T2 == Self { associatedtype T1: P2 } // CHECK-LABEL: rdar78233378.(file).P2@ // CHECK-LABEL: Requirement signature: <Self where Self : P5, Self.[P5]T2 : P1> public protocol P2: P5 where T2: P1 {} // CHECK-LABEL: rdar78233378.(file).P3@ // CHECK-LABEL: Requirement signature: <Self where Self.[P3]T2 : P4> public protocol P3 { associatedtype T2: P4 } // CHECK-LABEL: rdar78233378.(file).P4@ // CHECK-LABEL: Requirement signature: <Self where Self == Self.[P4]T3.[P3]T2, Self.[P4]T3 : P3> public protocol P4 where T3.T2 == Self { associatedtype T3: P3 } // CHECK-LABEL: rdar78233378.(file).P5@ // CHECK-LABEL: Requirement signature: <Self where Self.[P5]T2 : P4> public protocol P5 { associatedtype T2: P4 }
apache-2.0
3209fe7a500a27dc14c7ec8f1a61d5d2
33.448276
107
0.686687
2.78273
false
false
false
false
iluuu1994/Pathfinder
Pathfinder/AStarAlgorithm.swift
1
4129
// // AStarAlgorithm.swift // Pathfinder // // Created by Ilija Tovilo on 16/08/14. // Copyright (c) 2014 Ilija Tovilo // // 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 /// AStarAlgorithm is a class that implements the A* Algorithm for pathfinding /// http://en.wikipedia.org/wiki/A*_search_algorithm open class AStarAlgorithm: Algorithm { /// Finds the path from point A to B in any Map open class func findPathInMap(_ map: Map, startNode: Node, endNode: Node) -> [Node] { // var openList: [Node] = [startNode] let openList = IndexedArray<Node, Int>(extractIndex: { (node) in return node.fValue }) openList.add(startNode) // Add the neighbours of the start node to the open list to start the iteration process while let currentNode = openList.array.first { currentNode.closed = true openList.removeAtIndex(0) // Check if we reached the end node if currentNode == endNode { return backtracePath(endNode) } // Returns the neighbours of the node let validMoves = map.validMoves(currentNode) // Check each neighbour and add it to the open list for neighbour in validMoves { // If we can't access the tile we have to skip it if !neighbour.accessible { continue } // Calculate the move cost let moveCost = map.moveCostForNode(currentNode, toNode: neighbour) // We don't check the node if it's in the closed list if neighbour.closed && (currentNode.gValue + moveCost) >= neighbour.gValue { continue } if neighbour.opened { // The node was already added to the open list // We need to check if we have to re-parent it neighbour.parent = currentNode neighbour.gValue = currentNode.gValue + moveCost if !neighbour.closed { // Re-add it the the open list so it's sorted openList.removeAtIndex(openList.array.index(of:neighbour)!) openList.add(neighbour) } } else { // Set the parent of the node neighbour.parent = currentNode // Calculate the g value neighbour.gValue = currentNode.gValue + moveCost // Calculate the h value neighbour.hValue = map.hValueForNode(neighbour, endNode: endNode) // Add the new node to the open list neighbour.opened = true openList.add(neighbour) } } } // If there is no route, we just return an empty array return [] } }
mit
e6ca7a3534307ad48b4d2c10030ba09b
42.925532
95
0.584161
5.066258
false
false
false
false
ftxbird/NetEaseMoive
NetEaseMoive/Pods/Kingfisher/Kingfisher/String+MD5.swift
1
8683
// // String+MD5.swift // Kingfisher // // This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift // which is a modified version of CryptoSwift: // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset of CryptoSwift as a (temporary?) alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation extension String { func kf_MD5() -> String { if let data = dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(data) let MD5Data = MD5Calculator.calculate() let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) var MD5String = "" for c in resultEnumerator { MD5String += String(format: "%02x", c) } return MD5String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) let valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T), totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } class HashBase { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(len: Int = 64) -> NSMutableData { let tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.length; var counter = 0; while msgLength % len != (len - 8) { counter++ msgLength++ } let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8))) tmpMessage.appendBytes(bufZeros, length: counter) bufZeros.destroy() bufZeros.dealloc(1) return tmpMessage } } func rotateLeft(v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } class MD5 : HashBase { /** specifies the per-round shift amounts */ private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> NSData { let tmpMessage = prepare() // hash values var hh = h // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.length * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage.appendBytes(Array(lengthBytes.reverse())); // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes, leftMessageBytes))) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0) let range = NSRange(location:0, length: M.count * sizeof(UInt32)) chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range) // Initialize hash value for this chunk: var A:UInt32 = hh[0] var B:UInt32 = hh[1] var C:UInt32 = hh[2] var D:UInt32 = hh[3] var dTemp:UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } let buf: NSMutableData = NSMutableData(); hh.forEach({ (item) -> () in var i:UInt32 = item.littleEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData; } }
mit
42da3fffce11ea9aa05459f33e6f0806
38.257919
213
0.555095
3.861148
false
false
false
false
drewpitchford/Jsonable
Jsonable/Cocoapod/Jsonable.swift
1
2013
// // Jsonable.swift // Jsonable // // Created by Drew Pitchford on 3/31/17. // Copyright © 2017 Drew Pitchford. All rights reserved. // import Foundation /* Jsonable converts your objects into a [String: Any] which can be sent to a server. Jsonable assumes normal Ruby convention in json key naming. Ex. firstName = "first_name" */ public protocol Jsonable {} extension Jsonable { /* Calling this method will return a [String: Any] using your object's property names as the keys and property values as the values. */ public func json() -> [String: Any] { var dict: [String: Any] = [:] let otherSelf = Mirror(reflecting: self) for child in otherSelf.children { guard var key = child.label else { continue } key = insertUnderscores(into: key) if let value = child.value as? Jsonable { dict[key] = value.json() } else if let value = child.value as? OptionalType { if value.containsValue() { dict[key] = parse(value: value) } } else { dict[key] = child.value } } return dict } // MARK: - Helpers func parse(value: OptionalType) -> Any { guard let jsonableValue = value.unwrap() as? Jsonable else { return value.unwrap() } return jsonableValue.json() } func insertUnderscores(into aString: String) -> String { var newString = "" for character in aString.characters { if "A"..."Z" ~= character { newString.append("_") } newString.append(character) } return newString.lowercased() } }
mit
039f4492f0f684a424f8f75e8b0b3a6a
24.15
137
0.492048
5.093671
false
false
false
false
SergeyPetrachkov/VIPERTemplates
VIPER/SiberianTable3.0.xctemplate/UIViewController/___FILEBASENAME___Entities.swift
1
1093
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the SergeyPetrachkov VIPER Xcode Templates so // you can apply VIPER architecture to your iOS projects // import UIKit import SiberianVIPER enum ___VARIABLE_moduleName___ { // MARK: - Use cases enum DataContext { struct ModuleIn { } struct ModuleOut { } struct Request: PaginationRequest { var paginationParams: PaginationParameters init(skip: Int, take: Int) { self.paginationParams = PaginationParameters(skip: skip, take: take) } } struct Response: ModuleResponse { var originalRequest: Request let items: [CollectionModel] } class ViewModel: CollectionViewModel { var batchSize: Int = 20 var items: [CollectionModel] = [] var changeSet: [CollectionChange] = [] var isBusy: Bool = false init(moduleIn: ModuleIn) { } } } }
mit
d9f9b19904083e1909afbe1855d8b5ef
22.255319
76
0.609332
4.337302
false
false
false
false
aiqiuqiu/HGADView-Swift
HGADView/ViewController.swift
1
1289
// // ViewController.swift // HGADView // // Created by nero on 15/12/30. // Copyright © 2015年 nero. All rights reserved. // import UIKit class ViewController: UIViewController { var adView:HGADView<String>? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let adView = HGADView<String>(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 200)) view.addSubview(adView) let images = ["1","2","3"] adView.images = images adView.imageDidClick = { [unowned self] index in print("第\(index)张图片被点击了") } adView.loadImage = { ( imageView:UIImageView,imageName:String) in imageView.image = UIImage(named: imageName) // or use Other Modules } self.adView = adView } override func viewWillAppear(animated: Bool) { super.viewDidAppear(animated) adView?.addTimer() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) adView?.removeTimer() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { } }
artistic-2.0
fe035c2fd06a5f8f15a5bd8fa021ebad
27.222222
120
0.614961
4.290541
false
false
false
false
adrfer/swift
test/NameBinding/Inputs/accessibility_other.swift
7
669
import has_accessibility public let a = 0 internal let b = 0 private let c = 0 extension Foo { public static func a() {} internal static func b() {} private static func c() {} // expected-note {{'c' declared here}} } struct PrivateInit { private init() {} // expected-note {{'init' declared here}} } extension Foo { private func method() {} private typealias TheType = Float } extension OriginallyEmpty { func method() {} typealias TheType = Float } private func privateInBothFiles() {} func privateInPrimaryFile() {} // expected-note {{previously declared here}} private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
apache-2.0
c68b0d5cf8d8287d0f387e6a7e4a69ca
22.068966
80
0.696562
3.982143
false
false
false
false
ZhangHangwei/100_days_Swift
Project_06/Project_6/ViewController.swift
1
838
// // ViewController.swift // Project_6 // // Created by 章航伟 on 23/01/2017. // Copyright © 2017 Harvie. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! fileprivate lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .medium formatter.timeZone = TimeZone.current return formatter }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. refresh() } @IBAction func refresh() { let date = Date() timeLabel.text = dateFormatter.string(from: date) } }
mit
1708d3c47a605919a3375a1c56ca5d5e
18.785714
80
0.599278
4.859649
false
false
false
false
mac-cain13/R.swift
Sources/RswiftCore/Util/Struct+InternalProperties.swift
1
5622
// // Struct+InternalProperties.swift // R.swift // // Created by Mathijs Kadijk on 06-10-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation extension Struct { func addingInternalProperties(forBundleIdentifier bundleIdentifier: String, hostingBundle: String? = nil) -> Struct { let hostingBundleValue: String if let bundleName = hostingBundle, !bundleName.isEmpty { hostingBundleValue = "Bundle(for: R.Class.self).path(forResource: \"\(bundleName)\", ofType: \"bundle\").flatMap(Bundle.init(path:)) ?? Bundle(for: R.Class.self)" } else { hostingBundleValue = "Bundle(for: R.Class.self)" } let internalProperties = [ Let( comments: [], accessModifier: .filePrivate, isStatic: true, name: "hostingBundle", typeDefinition: .inferred(Type._Bundle), value: hostingBundleValue), Let( comments: [], accessModifier: .filePrivate, isStatic: true, name: "applicationLocale", typeDefinition: .inferred(Type._Locale), value: "hostingBundle.preferredLocalizations.first.flatMap { Locale(identifier: $0) } ?? Locale.current") ] let internalClasses = [ Class(accessModifier: .filePrivate, type: Type(module: .host, name: "Class")) ] let internalFunctions = [ Function( availables: [], comments: ["Load string from Info.plist file"], accessModifier: .filePrivate, isStatic: true, name: "infoPlistString", generics: nil, parameters: [ .init(name: "path", type: Type._Array.withGenericArgs([Type._String])), .init(name: "key", type: Type._String) ], doesThrow: false, returnType: Type._String.asOptional(), body: """ var dict = hostingBundle.infoDictionary for step in path { guard let obj = dict?[step] as? [String: Any] else { return nil } dict = obj } return dict?[key] as? String """, os: [] ), Function( availables: [], comments: ["Find first language and bundle for which the table exists"], accessModifier: .filePrivate, isStatic: true, name: "localeBundle", generics: nil, parameters: [ .init(name: "tableName", type: Type._String), .init(name: "preferredLanguages", type: Type._Array.withGenericArgs([Type._String])) ], doesThrow: false, returnType: Type._Tuple.withGenericArgs([Type._Locale, Type._Bundle]).asOptional(), body: """ // Filter preferredLanguages to localizations, use first locale var languages = preferredLanguages .map { Locale(identifier: $0) } .prefix(1) .flatMap { locale -> [String] in if hostingBundle.localizations.contains(locale.identifier) { if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [locale.identifier, language] } else { return [locale.identifier] } } else if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [language] } else { return [] } } // If there's no languages, use development language as backstop if languages.isEmpty { if let developmentLocalization = hostingBundle.developmentLocalization { languages = [developmentLocalization] } } else { // Insert Base as second item (between locale identifier and languageCode) languages.insert("Base", at: 1) // Add development language as backstop if let developmentLocalization = hostingBundle.developmentLocalization { languages.append(developmentLocalization) } } // Find first language for which table exists // Note: key might not exist in chosen language (in that case, key will be shown) for language in languages { if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"), let lbundle = Bundle(url: lproj) { let strings = lbundle.url(forResource: tableName, withExtension: "strings") let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict") if strings != nil || stringsdict != nil { return (Locale(identifier: language), lbundle) } } } // If table is available in main bundle, don't look for localized resources let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil) let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil) if strings != nil || stringsdict != nil { return (applicationLocale, hostingBundle) } // If table is not found for requested languages, key will be shown return nil """, os: [] ) ] var externalStruct = self externalStruct.properties.append(contentsOf: internalProperties) externalStruct.functions.append(contentsOf: internalFunctions) externalStruct.classes.append(contentsOf: internalClasses) return externalStruct } }
mit
ad6d9437fd284bd10192f8f87a6538ce
36.724832
168
0.598648
5.014273
false
false
false
false
ruslanskorb/CoreStore
CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV3.swift
1
731
// // OrganismV3.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/27. // Copyright © 2018 John Rommel Estropia. All rights reserved. // import Foundation import CoreData class OrganismV3: NSManagedObject, OrganismProtocol { @NSManaged var dna: Int64 @NSManaged var hasHead: Bool @NSManaged var hasTail: Bool @NSManaged var numberOfLimbs: Int32 @NSManaged var hasVertebrae: Bool // MARK: OrganismProtocol func mutate() { self.hasHead = arc4random_uniform(2) == 1 self.hasTail = arc4random_uniform(2) == 1 self.numberOfLimbs = Int32(arc4random_uniform(9) / 2 * 2) self.hasVertebrae = arc4random_uniform(2) == 1 } }
mit
0cf25755d5470774f4c2c7d65d54b64a
24.172414
65
0.657534
3.631841
false
false
false
false
xwu/swift
test/expr/unary/keypath/keypath.swift
1
45105
// RUN: %target-swift-frontend -typecheck -parse-as-library %s -verify struct Sub: Hashable { static func ==(_: Sub, _: Sub) -> Bool { return true } func hash(into hasher: inout Hasher) {} } struct OptSub: Hashable { static func ==(_: OptSub, _: OptSub) -> Bool { return true } func hash(into hasher: inout Hasher) {} } struct NonHashableSub {} struct Prop { subscript(sub: Sub) -> A { get { return A() } set { } } subscript(optSub: OptSub) -> A? { get { return A() } set { } } subscript(nonHashableSub: NonHashableSub) -> A { get { return A() } set { } } subscript(a: Sub, b: Sub) -> A { get { return A() } set { } } subscript(a: Sub, b: NonHashableSub) -> A { get { return A() } set { } } var nonMutatingProperty: B { get { fatalError() } nonmutating set { fatalError() } } } struct A: Hashable { init() { fatalError() } var property: Prop var optProperty: Prop? let optLetProperty: Prop? subscript(sub: Sub) -> A { get { return self } set { } } static func ==(_: A, _: A) -> Bool { fatalError() } func hash(into hasher: inout Hasher) { fatalError() } } struct B {} struct C<T> { // expected-note 4 {{'T' declared as parameter to type 'C'}} var value: T subscript() -> T { get { return value } } subscript(sub: Sub) -> T { get { return value } set { } } subscript<U: Hashable>(sub: U) -> U { get { return sub } set { } } subscript<X>(noHashableConstraint sub: X) -> X { get { return sub } set { } } } struct Unavailable { @available(*, unavailable) var unavailableProperty: Int // expected-note@-1 {{'unavailableProperty' has been explicitly marked unavailable here}} @available(*, unavailable) subscript(x: Sub) -> Int { get { } set { } } // expected-note@-1 {{'subscript(_:)' has been explicitly marked unavailable here}} } struct Deprecated { @available(*, deprecated) var deprecatedProperty: Int @available(*, deprecated) subscript(x: Sub) -> Int { get { } set { } } } @available(*, deprecated) func getDeprecatedSub() -> Sub { return Sub() } extension Array where Element == A { var property: Prop { fatalError() } } protocol P { var member: String { get } } extension B : P { var member : String { return "Member Value" } } struct Exactly<T> {} func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {} func testKeyPath(sub: Sub, optSub: OptSub, nonHashableSub: NonHashableSub, x: Int) { var a = \A.property expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var b = \A.[sub] expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self) var c = \A.[sub].property expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var d = \A.optProperty? expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self) var e = \A.optProperty?[sub] expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self) var f = \A.optProperty! expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self) var g = \A.property[optSub]?.optProperty![sub] expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self) var h = \[A].property expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self) var i = \[A].property.nonMutatingProperty expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self) var j = \[A].[x] expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self) var k = \[A: B].[A()] expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self) var l = \C<A>.value expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self) // expected-error@+1{{generic parameter 'T' could not be inferred}} _ = \C.value // expected-error@+1{{}} _ = \(() -> ()).noMember let _: (A) -> Prop = \.property let _: PartialKeyPath<A> = \.property let _: KeyPath<A, Prop> = \.property let _: WritableKeyPath<A, Prop> = \.property let _: ReferenceWritableKeyPath<A, Prop> = \.property //expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, Prop>' to specified type 'ReferenceWritableKeyPath<A, Prop>'}} let _: (A) -> A = \.[sub] let _: PartialKeyPath<A> = \.[sub] let _: KeyPath<A, A> = \.[sub] let _: WritableKeyPath<A, A> = \.[sub] let _: ReferenceWritableKeyPath<A, A> = \.[sub] //expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, A>' to specified type 'ReferenceWritableKeyPath<A, A>'}} let _: (A) -> Prop? = \.optProperty? let _: PartialKeyPath<A> = \.optProperty? let _: KeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, Prop?> = \.optProperty? // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, Prop?> = \.optProperty? let _: (A) -> A? = \.optProperty?[sub] let _: PartialKeyPath<A> = \.optProperty?[sub] let _: KeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: WritableKeyPath<A, A?> = \.optProperty?[sub] // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<A, A?> = \.optProperty?[sub] let _: KeyPath<A, Prop> = \.optProperty! let _: KeyPath<A, Prop> = \.optLetProperty! let _: KeyPath<A, Prop?> = \.property[optSub]?.optProperty! let _: KeyPath<A, A?> = \.property[optSub]?.optProperty![sub] let _: (C<A>) -> A = \.value let _: PartialKeyPath<C<A>> = \.value let _: KeyPath<C<A>, A> = \.value let _: WritableKeyPath<C<A>, A> = \.value let _: ReferenceWritableKeyPath<C<A>, A> = \.value // expected-error@-1 {{cannot convert value of type 'WritableKeyPath<C<A>, A>' to specified type 'ReferenceWritableKeyPath<C<A>, A>'}} let _: (C<A>) -> A = \C.value let _: PartialKeyPath<C<A>> = \C.value let _: KeyPath<C<A>, A> = \C.value let _: WritableKeyPath<C<A>, A> = \C.value // expected-error@+1{{cannot convert}} let _: ReferenceWritableKeyPath<C<A>, A> = \C.value let _: (Prop) -> B = \.nonMutatingProperty let _: PartialKeyPath<Prop> = \.nonMutatingProperty let _: KeyPath<Prop, B> = \.nonMutatingProperty let _: WritableKeyPath<Prop, B> = \.nonMutatingProperty let _: ReferenceWritableKeyPath<Prop, B> = \.nonMutatingProperty var m = [\A.property, \A.[sub], \A.optProperty!] expect(&m, toHaveType: Exactly<[PartialKeyPath<A>]>.self) // \.optProperty returns an optional of Prop and `\.[sub]` returns `A`, all this unifies into `[PartialKeyPath<A>]` var n = [\A.property, \.optProperty, \.[sub], \.optProperty!] expect(&n, toHaveType: Exactly<[PartialKeyPath<A>]>.self) let _: [PartialKeyPath<A>] = [\.property, \.optProperty, \.[sub], \.optProperty!] var o = [\A.property, \C<A>.value] expect(&o, toHaveType: Exactly<[AnyKeyPath]>.self) let _: AnyKeyPath = \A.property let _: AnyKeyPath = \C<A>.value let _: AnyKeyPath = \.property // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}} let _: AnyKeyPath = \C.value // expected-error{{generic parameter 'T' could not be inferred}} let _: AnyKeyPath = \.value // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}} let _ = \Prop.[nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \Prop.[sub, sub] let _ = \Prop.[sub, nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \C<Int>.[] let _ = \C<Int>.[sub] let _ = \C<Int>.[noHashableConstraint: sub] let _ = \C<Int>.[noHashableConstraint: nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}} let _ = \Unavailable.unavailableProperty // expected-error {{'unavailableProperty' is unavailable}} let _ = \Unavailable.[sub] // expected-error {{'subscript(_:)' is unavailable}} let _ = \Deprecated.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated}} let _ = \Deprecated.[sub] // expected-warning {{'subscript(_:)' is deprecated}} let _ = \A.[getDeprecatedSub()] // expected-warning {{'getDeprecatedSub()' is deprecated}} } func testKeyPathInGenericContext<H: Hashable, X>(hashable: H, anything: X) { let _ = \C<Int>.[hashable] let _ = \C<Int>.[noHashableConstraint: hashable] let _ = \C<Int>.[noHashableConstraint: anything] // expected-error{{subscript index of type 'X' in a key path must be Hashable}} } func testDisembodiedStringInterpolation(x: Int) { \(x) // expected-error{{string interpolation can only appear inside a string literal}} \(x, radix: 16) // expected-error{{string interpolation can only appear inside a string literal}} } func testNoComponents() { let _: KeyPath<A, A> = \A // expected-error{{must have at least one component}} let _: KeyPath<C, A> = \C // expected-error{{must have at least one component}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} let _: KeyPath<A, C> = \A // expected-error{{must have at least one component}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} _ = \A // expected-error {{key path must have at least one component}} } struct TupleStruct { var unlabeled: (Int, String) var labeled: (foo: Int, bar: String) } typealias UnlabeledGenericTuple<T, U> = (T, U) typealias LabeledGenericTuple<T, U> = (a: T, b: U) func tupleComponent<T, U>(_: T, _: U) { let _ = \(Int, String).0 let _ = \(Int, String).1 let _ = \TupleStruct.unlabeled.0 let _ = \TupleStruct.unlabeled.1 let _ = \(foo: Int, bar: String).0 let _ = \(foo: Int, bar: String).1 let _ = \(foo: Int, bar: String).foo let _ = \(foo: Int, bar: String).bar let _ = \TupleStruct.labeled.0 let _ = \TupleStruct.labeled.1 let _ = \TupleStruct.labeled.foo let _ = \TupleStruct.labeled.bar let _ = \(T, U).0 let _ = \(T, U).1 let _ = \UnlabeledGenericTuple<T, U>.0 let _ = \UnlabeledGenericTuple<T, U>.1 let _ = \(a: T, b: U).0 let _ = \(a: T, b: U).1 let _ = \(a: T, b: U).a let _ = \(a: T, b: U).b let _ = \LabeledGenericTuple<T, U>.0 let _ = \LabeledGenericTuple<T, U>.1 let _ = \LabeledGenericTuple<T, U>.a let _ = \LabeledGenericTuple<T, U>.b } func tuple_el_0<T, U>() -> KeyPath<(T, U), T> { return \.0 } func tuple_el_1<T, U>() -> KeyPath<(T, U), U> { return \.1 } func tupleGeneric<T, U>(_ v: (T, U)) { _ = (1, "hello")[keyPath: tuple_el_0()] _ = (1, "hello")[keyPath: tuple_el_1()] _ = v[keyPath: tuple_el_0()] _ = v[keyPath: tuple_el_1()] _ = ("tuple", "too", "big")[keyPath: tuple_el_1()] // expected-note@-12 {{}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} // expected-error@-3 {{generic parameter 'U' could not be inferred}} } struct Z { } func testKeyPathSubscript(readonly: Z, writable: inout Z, kp: KeyPath<Z, Int>, wkp: WritableKeyPath<Z, Int>, rkp: ReferenceWritableKeyPath<Z, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}} } struct ZwithSubscript { subscript(keyPath kp: KeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: WritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: ReferenceWritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 } subscript(keyPath kp: PartialKeyPath<ZwithSubscript>) -> Any { return 0 } } struct NotZ {} func testKeyPathSubscript(readonly: ZwithSubscript, writable: inout ZwithSubscript, wrongType: inout NotZ, kp: KeyPath<ZwithSubscript, Int>, wkp: WritableKeyPath<ZwithSubscript, Int>, rkp: ReferenceWritableKeyPath<ZwithSubscript, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} writable[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} readonly[keyPath: wkp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: wkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: rkp] = sink // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: rkp] = sink let pkp: PartialKeyPath = rkp var anySink1 = readonly[keyPath: pkp] expect(&anySink1, toHaveType: Exactly<Any>.self) var anySink2 = writable[keyPath: pkp] expect(&anySink2, toHaveType: Exactly<Any>.self) readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: subscript is get-only}} writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: subscript is get-only}} let akp: AnyKeyPath = pkp var anyqSink1 = readonly[keyPath: akp] expect(&anyqSink1, toHaveType: Exactly<Any?>.self) var anyqSink2 = writable[keyPath: akp] expect(&anyqSink2, toHaveType: Exactly<Any?>.self) // FIXME: silently falls back to keypath application, which seems inconsistent readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} // FIXME: silently falls back to keypath application, which seems inconsistent writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}} _ = wrongType[keyPath: kp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: wkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: rkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: pkp] // expected-error{{cannot be applied}} _ = wrongType[keyPath: akp] } func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type, kp: KeyPath<Z.Type, Int>, wkp: WritableKeyPath<Z.Type, Int>, rkp: ReferenceWritableKeyPath<Z.Type, Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z), kp: KeyPath<(Z,Z), Int>, wkp: WritableKeyPath<(Z,Z), Int>, rkp: ReferenceWritableKeyPath<(Z,Z), Int>) { var sink: Int sink = readonly[keyPath: kp] sink = writable[keyPath: kp] sink = readonly[keyPath: wkp] sink = writable[keyPath: wkp] sink = readonly[keyPath: rkp] sink = writable[keyPath: rkp] readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}} readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}} writable[keyPath: wkp] = sink readonly[keyPath: rkp] = sink writable[keyPath: rkp] = sink } func testKeyPathSubscriptLValue(base: Z, kp: inout KeyPath<Z, Z>) { _ = base[keyPath: kp] } func testKeyPathSubscriptExistentialBase(concreteBase: inout B, existentialBase: inout P, kp: KeyPath<P, String>, wkp: WritableKeyPath<P, String>, rkp: ReferenceWritableKeyPath<P, String>, pkp: PartialKeyPath<P>, s: String) { _ = concreteBase[keyPath: kp] _ = concreteBase[keyPath: wkp] _ = concreteBase[keyPath: rkp] _ = concreteBase[keyPath: pkp] concreteBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}} concreteBase[keyPath: wkp] = s // expected-error {{key path with root type 'P' cannot be applied to a base of type 'B'}} concreteBase[keyPath: rkp] = s concreteBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}} _ = existentialBase[keyPath: kp] _ = existentialBase[keyPath: wkp] _ = existentialBase[keyPath: rkp] _ = existentialBase[keyPath: pkp] existentialBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}} existentialBase[keyPath: wkp] = s existentialBase[keyPath: rkp] = s existentialBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}} } struct AA { subscript(x: Int) -> Int { return x } subscript(labeled x: Int) -> Int { return x } var c: CC? = CC() } class CC { var i = 0 } func testKeyPathOptional() { _ = \AA.c?.i _ = \AA.c!.i // SR-6198 let path: KeyPath<CC,Int>! = \CC.i let cc = CC() _ = cc[keyPath: path] } func testLiteralInAnyContext() { let _: AnyKeyPath = \A.property let _: AnyObject = \A.property let _: Any = \A.property let _: Any? = \A.property } func testMoreGeneralContext<T, U>(_: KeyPath<T, U>, with: T.Type) {} func testLiteralInMoreGeneralContext() { testMoreGeneralContext(\.property, with: A.self) } func testLabeledSubscript() { let _: KeyPath<AA, Int> = \AA.[labeled: 0] let _: KeyPath<AA, Int> = \.[labeled: 0] let k = \AA.[labeled: 0] // TODO: These ought to work without errors. let _ = \AA.[keyPath: k] // expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}} let _ = \AA.[keyPath: \AA.[labeled: 0]] // expected-error {{extraneous argument label 'keyPath:' in call}} // expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}} } func testInvalidKeyPathComponents() { let _ = \.{return 0} // expected-error* {{}} } class X { class var a: Int { return 1 } static var b = 2 } func testStaticKeyPathComponent() { _ = \X.a // expected-error{{cannot refer to static member}} _ = \X.Type.a // expected-error{{cannot refer to static member}} _ = \X.b // expected-error{{cannot refer to static member}} _ = \X.Type.b // expected-error{{cannot refer to static member}} } class Bass: Hashable { static func ==(_: Bass, _: Bass) -> Bool { return false } func hash(into hasher: inout Hasher) {} } class Treble: Bass { } struct BassSubscript { subscript(_: Bass) -> Int { fatalError() } subscript(_: @autoclosure () -> String) -> Int { fatalError() } } func testImplicitConversionInSubscriptIndex() { _ = \BassSubscript.[Treble()] _ = \BassSubscript.["hello"] // expected-error{{must be Hashable}} } // Crash in diagnostics + SR-11438 struct UnambiguousSubscript { subscript(sub: Sub) -> Int { get { } set { } } subscript(y y: Sub) -> Int { get { } set { } } } func useUnambiguousSubscript(_ sub: Sub) { let _: PartialKeyPath<UnambiguousSubscript> = \.[sub] } struct BothUnavailableSubscript { @available(*, unavailable) subscript(sub: Sub) -> Int { get { } set { } } // expected-note {{'subscript(_:)' has been explicitly marked unavailable here}} @available(*, unavailable) subscript(y y: Sub) -> Int { get { } set { } } } func useBothUnavailableSubscript(_ sub: Sub) { let _: PartialKeyPath<BothUnavailableSubscript> = \.[sub] // expected-error@-1 {{'subscript(_:)' is unavailable}} } // SR-6106 func sr6106() { class B {} class A { var b: B? = nil } class C { var a: A? func myFunc() { let _ = \C.a?.b } } } // SR-6744 func sr6744() { struct ABC { let value: Int func value(adding i: Int) -> Int { return value + i } } let abc = ABC(value: 0) func get<T>(for kp: KeyPath<ABC, T>) -> T { return abc[keyPath: kp] } _ = get(for: \.value) } func sr7380() { _ = ""[keyPath: \.count] _ = ""[keyPath: \String.count] let arr1 = [1] _ = arr1[keyPath: \.[0]] _ = arr1[keyPath: \[Int].[0]] let dic1 = [1:"s"] _ = dic1[keyPath: \.[1]] _ = dic1[keyPath: \[Int: String].[1]] var arr2 = [1] arr2[keyPath: \.[0]] = 2 arr2[keyPath: \[Int].[0]] = 2 var dic2 = [1:"s"] dic2[keyPath: \.[1]] = "" dic2[keyPath: \[Int: String].[1]] = "" _ = [""][keyPath: \.[0]] _ = [""][keyPath: \[String].[0]] _ = ["": ""][keyPath: \.["foo"]] _ = ["": ""][keyPath: \[String: String].["foo"]] class A { var a: String = "" } _ = A()[keyPath: \.a] _ = A()[keyPath: \A.a] A()[keyPath: \.a] = "" A()[keyPath: \A.a] = "" } struct VisibilityTesting { private(set) var x: Int fileprivate(set) var y: Int let z: Int // Key path exprs should not get special dispensation to write to lets // in init contexts init() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) // Allow WritableKeyPath for Swift 3/4 only. expect(&zRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) } func inPrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } struct VisibilityTesting2 { func inFilePrivateContext() { var xRef = \VisibilityTesting.x var yRef = \VisibilityTesting.y var zRef = \VisibilityTesting.z // Allow WritableKeyPath for Swift 3/4 only. expect(&xRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&yRef, toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self) expect(&zRef, toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self) } } protocol PP {} class Base : PP { var i: Int = 0 } class Derived : Base {} func testSubtypeKeypathClass(_ keyPath: ReferenceWritableKeyPath<Base, Int>) { testSubtypeKeypathClass(\Derived.i) } func testSubtypeKeypathProtocol(_ keyPath: ReferenceWritableKeyPath<PP, Int>) { testSubtypeKeypathProtocol(\Base.i) // expected-error@-1 {{cannot convert value of type 'ReferenceWritableKeyPath<Base, Int>' to expected argument type 'ReferenceWritableKeyPath<PP, Int>'}} // expected-note@-2 {{arguments to generic parameter 'Root' ('Base' and 'PP') are expected to be equal}} } // rdar://problem/32057712 struct Container { let base: Base? = Base() } var rdar32057712 = \Container.base?.i var identity1 = \Container.self var identity2: WritableKeyPath = \Container.self var identity3: WritableKeyPath<Container, Container> = \Container.self var identity4: WritableKeyPath<Container, Container> = \.self var identity5: KeyPath = \Container.self var identity6: KeyPath<Container, Container> = \Container.self var identity7: KeyPath<Container, Container> = \.self var identity8: PartialKeyPath = \Container.self var identity9: PartialKeyPath<Container> = \Container.self var identity10: PartialKeyPath<Container> = \.self var identity11: AnyKeyPath = \Container.self var identity12: (Container) -> Container = \Container.self var identity13: (Container) -> Container = \.self var interleavedIdentityComponents = \Container.self.base.self?.self.i.self protocol P_With_Static_Members { static var x: Int { get } static var arr: [Int] { get } } func test_keypath_with_static_members(_ p: P_With_Static_Members) { let _ = p[keyPath: \.x] // expected-error@-1 {{key path cannot refer to static member 'x'}} let _: KeyPath<P_With_Static_Members, Int> = \.x // expected-error@-1 {{key path cannot refer to static member 'x'}} let _ = \P_With_Static_Members.arr.count // expected-error@-1 {{key path cannot refer to static member 'arr'}} let _ = p[keyPath: \.arr.count] // expected-error@-1 {{key path cannot refer to static member 'arr'}} struct S { static var foo: String = "Hello" var bar: Bar } struct Bar { static var baz: Int = 42 } func foo(_ s: S) { let _ = \S.Type.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = s[keyPath: \.foo] // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _: KeyPath<S, String> = \.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = \S.foo // expected-error@-1 {{key path cannot refer to static member 'foo'}} let _ = \S.bar.baz // expected-error@-1 {{key path cannot refer to static member 'baz'}} let _ = s[keyPath: \.bar.baz] // expected-error@-1 {{key path cannot refer to static member 'baz'}} } } func test_keypath_with_mutating_getter() { struct S { var foo: Int { mutating get { return 42 } } subscript(_: Int) -> [Int] { mutating get { return [] } } } _ = \S.foo // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} let _: KeyPath<S, Int> = \.foo // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} _ = \S.[0] // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} _ = \S.[0].count // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} func test_via_subscript(_ s: S) { _ = s[keyPath: \.foo] // expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}} _ = s[keyPath: \.[0].count] // expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}} } } func test_keypath_with_method_refs() { struct S { func foo() -> Int { return 42 } static func bar() -> Int { return 0 } } let _: KeyPath<S, Int> = \.foo // expected-error {{key path cannot refer to instance method 'foo()'}} // expected-error@-1 {{key path value type '() -> Int' cannot be converted to contextual type 'Int'}} let _: KeyPath<S, Int> = \.bar // expected-error {{key path cannot refer to static member 'bar()'}} let _ = \S.Type.bar // expected-error {{key path cannot refer to static method 'bar()'}} struct A { func foo() -> B { return B() } static func faz() -> B { return B() } } struct B { var bar: Int = 42 } let _: KeyPath<A, Int> = \.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}} let _: KeyPath<A, Int> = \.faz.bar // expected-error {{key path cannot refer to static member 'faz()'}} let _ = \A.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}} let _ = \A.Type.faz.bar // expected-error {{key path cannot refer to static method 'faz()'}} } // SR-12519: Compiler crash on invalid method reference in key path. protocol Zonk { func wargle() } typealias Blatz = (gloop: String, zoop: Zonk?) func sr12519(fleep: [Blatz]) { fleep.compactMap(\.zoop?.wargle) // expected-error {{key path cannot refer to instance method 'wargle()'}} } // SR-10467 - Argument type 'KeyPath<String, Int>' does not conform to expected type 'Any' func test_keypath_in_any_context() { func foo(_: Any) {} foo(\String.count) // Ok } protocol PWithTypeAlias { typealias Key = WritableKeyPath<Self, Int?> static var fooKey: Key? { get } static var barKey: Key! { get } static var fazKey: Key?? { get } static var bazKey: Key?! { get } } func test_keypath_inference_with_optionals() { final class S : PWithTypeAlias { static var fooKey: Key? { return \.foo } static var barKey: Key! { return \.foo } static var fazKey: Key?? { return \.foo } static var bazKey: Key?! { return \.foo } var foo: Int? = nil } } func sr11562() { struct S1 { subscript(x x: Int) -> Int { x } } _ = \S1.[5] // expected-error {{missing argument label 'x:' in call}} {{12-12=x: }} struct S2 { subscript(x x: Int) -> Int { x } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}} subscript(y y: Int) -> Int { y } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(y:)')}} } _ = \S2.[5] // expected-error {{no exact matches in call to subscript}} struct S3 { subscript(x x: Int, y y: Int) -> Int { x } } _ = \S3.[y: 5, x: 5] // expected-error {{argument 'x' must precede argument 'y'}} struct S4 { subscript(x: (Int, Int)) -> Int { x.0 } } _ = \S4.[1, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{12-12=(}} {{16-16=)}} // expected-error@-1 {{subscript index of type '(Int, Int)' in a key path must be Hashable}} } // SR-12290: Ban keypaths with contextual root and without a leading dot struct SR_12290 { let property: [Int] = [] let kp1: KeyPath<SR_12290, Int> = \property.count // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{38-38=.}} let kp2: KeyPath<SR_12290, Int> = \.property.count // Ok let kp3: KeyPath<SR_12290, Int> = \SR_12290.property.count // Ok func foo1(_: KeyPath<SR_12290, Int> = \property.count) {} // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{42-42=.}} func foo2(_: KeyPath<SR_12290, Int> = \.property.count) {} // Ok func foo3(_: KeyPath<SR_12290, Int> = \SR_12290.property.count) {} // Ok func foo4<T>(_: KeyPath<SR_12290, T>) {} func useFoo4() { foo4(\property.count) // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{11-11=.}} foo4(\.property.count) // Ok foo4(\SR_12290.property.count) // Ok } } func testKeyPathHole() { _ = \.x // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}} _ = \.x.y // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}} let _ : AnyKeyPath = \.x // expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}} let _ : AnyKeyPath = \.x.y // expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}} func f(_ i: Int) {} f(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}} f(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}} func provideValueButNotRoot<T>(_ fn: (T) -> String) {} provideValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideValueButNotRoot(\String.foo) // expected-error {{value of type 'String' has no member 'foo'}} func provideKPValueButNotRoot<T>(_ kp: KeyPath<T, String>) {} // expected-note {{in call to function 'provideKPValueButNotRoot'}} provideKPValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideKPValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} provideKPValueButNotRoot(\String.foo) // expected-error@-1 {{value of type 'String' has no member 'foo'}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} } func testMissingMember() { let _: KeyPath<String, String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}} let _: KeyPath<String, String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}} let _: PartialKeyPath<String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}} let _: PartialKeyPath<String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}} _ = \String.x.y // expected-error {{value of type 'String' has no member 'x'}} } // SR-5688 struct SR5688_A { var b: SR5688_B? } struct SR5688_AA { var b: SR5688_B } struct SR5688_B { var m: Int var c: SR5688_C? } struct SR5688_C { var d: Int } struct SR5688_S { subscript(_ x: Int) -> String? { "" } } struct SR5688_O { struct Nested { var foo = "" } } func SR5688_KP(_ kp: KeyPath<String?, Int>) {} func testMemberAccessOnOptionalKeyPathComponent() { _ = \SR5688_A.b.m // expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'm' of wrapped base type 'SR5688_B'}} // expected-note@-2 {{chain the optional using '?' to access member 'm' only for non-'nil' base values}} {{18-18=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{18-18=!}} _ = \SR5688_A.b.c.d // expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'c' of wrapped base type 'SR5688_B'}} // expected-note@-2 {{chain the optional using '?' to access member 'c' only for non-'nil' base values}} {{18-18=?}} // expected-error@-3 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-4 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{20-20=?}} // expected-note@-5 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{20-20=!}} _ = \SR5688_A.b?.c.d // expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}} _ = \SR5688_AA.b.c.d // expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}} // expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{21-21=!}} \String?.count // expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-11=String}} \Optional<String>.count // expected-error@-1 {{value of optional type 'Optional<String>' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-20=String}} \SR5688_S.[5].count // expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}} // expected-note@-2 {{chain the optional using '?' to access member 'count' only for non-'nil' base values}}{{16-16=?}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{16-16=!}} \SR5688_O.Nested?.foo.count // expected-error@-1 {{value of optional type 'SR5688_O.Nested?' must be unwrapped to refer to member 'foo' of wrapped base type 'SR5688_O.Nested'}} // expected-note@-2 {{use unwrapped type 'SR5688_O.Nested' as key path root}}{{4-20=SR5688_O.Nested}} \(Int, Int)?.0 // expected-error@-1 {{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-2 {{use unwrapped type '(Int, Int)' as key path root}}{{4-15=(Int, Int)}} SR5688_KP(\.count) // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}} // expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{15-15=?.}} // expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{15-15=!.}} let _ : KeyPath<String?, Int> = \.count // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}} // expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{37-37=?.}} // expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{37-37=!.}} let _ : KeyPath<String?, Int> = \.utf8.count // expected-error@-1 {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'utf8' of unwrapped type 'String'}} // expected-note@-2 {{chain the optional using '?.' to access unwrapped type member 'utf8'}} {{37-37=?.}} // expected-note@-3 {{unwrap the optional using '!.' to access unwrapped type member 'utf8'}} {{37-37=!.}} } func testSyntaxErrors() { _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a]; _ = \? ; _ = \! ; _ = \. ; // expected-error{{expected member name following '.'}} _ = \.a ; _ = \[a ; _ = \[a,; _ = \[a:; _ = \[a]; _ = \.a?; _ = \.a!; _ = \A ; _ = \A, ; _ = \A< ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a]; _ = \A? ; _ = \A! ; _ = \A. ; // expected-error{{expected member name following '.'}} _ = \A.a ; _ = \A[a ; _ = \A[a,; _ = \A[a:; _ = \A[a]; _ = \A.a?; _ = \A.a!; } // SR-14644 func sr14644() { _ = \Int.byteSwapped.signum() // expected-error {{invalid component of Swift key path}} _ = \Int.byteSwapped.init() // expected-error {{invalid component of Swift key path}} _ = \Int // expected-error {{key path must have at least one component}} _ = \Int? // expected-error {{key path must have at least one component}} _ = \Int. // expected-error {{invalid component of Swift key path}} // expected-error@-1 {{expected member name following '.'}} } // SR-13364 - keypath missing optional crashes compiler: "Inactive constraints left over?" func sr13364() { let _: KeyPath<String?, Int?> = \.utf8.count // expected-error {{no exact matches in reference to property 'count'}} // expected-note@-1 {{found candidate with type 'Int'}} } // rdar://74711236 - crash due to incorrect member access in key path func rdar74711236() { struct S { var arr: [V] = [] } struct V : Equatable { } enum Type { case store } struct Context { func supported() -> [Type] { return [] } } func test(context: Context?) { var s = S() s.arr = { if let type = context?.store { // expected-error {{value of type 'Context' has no member 'store'}} // `isSupported` should be an invalid declaration to trigger a crash in `map(\.option)` let isSupported = context!.supported().contains(type) return (isSupported ? [type] : []).map(\.option) // expected-error@-1 {{value of type 'Any' has no member 'option'}} // expected-note@-2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } return [] }() } } extension String { var filterOut : (Self) throws -> Bool { { $0.contains("a") } } } func test_kp_as_function_mismatch() { let a : [String] = [ "asd", "bcd", "def" ] let _ : (String) -> Bool = \.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} _ = a.filter(\.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} let _ : (String) -> Bool = \String.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} _ = a.filter(\String.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}} } func test_partial_keypath_inference() { // rdar://problem/34144827 struct S { var i: Int = 0 } enum E { case A(pkp: PartialKeyPath<S>) } _ = E.A(pkp: \.i) // Ok // rdar://problem/36472188 class ThePath { var isWinding:Bool? } func walk<T>(aPath: T, forKey: PartialKeyPath<T>) {} func walkThePath(aPath: ThePath, forKey: PartialKeyPath<ThePath>) {} func test(path: ThePath) { walkThePath(aPath: path, forKey: \.isWinding) // Ok walk(aPath: path, forKey: \.isWinding) // Ok } } // SR-14499 struct SR14499_A { } struct SR14499_B { } func sr14499() { func reproduceA() -> [(SR14499_A, SR14499_B)] { [ (true, .init(), SR14499_B.init()) // expected-error {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } func reproduceB() -> [(SR14499_A, SR14499_B)] { [ (true, SR14499_A.init(), .init()) // expected-error {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } func reproduceC() -> [(SR14499_A, SR14499_B)] { [ (true, .init(), .init()) // expected-error 2 {{cannot infer contextual base in reference to member 'init'}} ] .filter(\.0) // expected-error {{value of type 'Any' has no member '0'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} .prefix(3) .map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}} // expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} } }
apache-2.0
eada44c4f38e7765a04ce9b9a2bfb2ae
37.224576
191
0.642412
3.644554
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift
2
2203
// // UISearchBar+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UISearchBar { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var rx_delegate: DelegateProxy { return proxyForObject(RxSearchBarDelegateProxy.self, self) } /** Reactive wrapper for `text` property. */ public var rx_text: ControlProperty<String> { let source: Observable<String> = Observable.deferred { [weak self] () -> Observable<String> in let text = self?.text ?? "" return (self?.rx_delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) .map { a in return a[1] as? String ?? "" } .startWith(text) } let bindingObserver = UIBindingObserver(UIElement: self) { (searchBar, text: String) in searchBar.text = text } return ControlProperty(values: source, valueSink: bindingObserver) } /** Reactive wrapper for `selectedScopeButtonIndex` property. */ public var rx_selectedScopeButtonIndex: ControlProperty<Int> { let source: Observable<Int> = Observable.deferred { [weak self] () -> Observable<Int> in let index = self?.selectedScopeButtonIndex ?? 0 return (self?.rx_delegate.observe(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) .map { a in return try castOrThrow(Int.self, a[1]) } .startWith(index) } let bindingObserver = UIBindingObserver(UIElement: self) { (searchBar, index: Int) in searchBar.selectedScopeButtonIndex = index } return ControlProperty(values: source, valueSink: bindingObserver) } } #endif
mit
5f50f001e4aa9dbfa669aa415e309d6a
29.164384
148
0.597184
4.993197
false
false
false
false
nikita-leonov/boss-client
BoSS/AppDelegate.swift
1
1069
// // AppDelegate.swift // BoSS // // Created by Nikita Leonov on 2/28/15. // Copyright (c) 2015 Bureau of Street Services. All rights reserved. // import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private let baseURL: NSURL = NSURL(string: "http://10.60.0.74:3000/api/")! var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let locationService: LocationServiceProtocol = LocationService() ServiceLocator.registerService(locationService) let sessionManager = AFHTTPSessionManager(baseURL: baseURL) sessionManager.requestSerializer = AFJSONRequestSerializer() let submissionsService = SubmissionsService(sessionManager: sessionManager) ServiceLocator.registerService(submissionsService as SubmissionsServiceProtocol) ServiceLocator.registerService(CategoriesService() as CategoriesServiceProtocol) return true } }
mit
6e1605229c3056193b33fbb8c78b1c47
32.40625
127
0.743686
5.318408
false
false
false
false
KristopherGBaker/RubiParser
RubiParser/RubiDocument.swift
1
2253
// // RubiDocument.swift // RubiParser // // Created by Kris Baker on 12/19/16. // Copyright © 2016 Empyreal Night, LLC. All rights reserved. // /// Represents a document containing ruby characters. public struct RubiDocument { /// The items - a list of the document elements. public let items: [RubiNode] /// Initializes a RubiDocument with the specified items. /// /// - Parameters: /// - items: The items representing the RubiDocument. /// - Returns: /// The initialized RubiDocument containing the specified items. public init(items: [RubiNode]) { self.items = items } } /// Provides convenience properties for RubiDocument. public extension RubiDocument { /// Returns a string representation of the document using kanji. public var kanjiString: String { return mapItems(items: items).joined(separator: "") } /// Maps the specified items to a string array. /// /// - Parameters: /// - items: The items to map. /// - useKana: Indicates if kana should be used (true) or kanji (false). /// The default is kanji/false. /// - Returns: /// A string array representing the mapped items. private func mapItems(items: [RubiNode], useKana: Bool = false) -> [String] { return items.flatMap { item -> [String] in switch item { case .image: return [] case .ruby(kanji: let kanji, reading: let reading): return useKana ? [reading] : [kanji] case .text(text: let text): return [text] case .word(text: let word): return [word] case .paragraph(children: let children): return mapItems(items: children, useKana: useKana) } } } /// Returns a string representation of the document using hiragana/katakana. public var kanaString: String { return mapItems(items: items, useKana: true).joined(separator: "") } } /// Implements the Equatable protocol for RubiDocument. extension RubiDocument: Equatable { public static func == (lhs: RubiDocument, rhs: RubiDocument) -> Bool { return lhs.items == rhs.items } }
mit
95f9d77f0155bc82e03f348354d26822
30.71831
81
0.60746
4.504
false
false
false
false
loufranco/hello-ios-2-source
CH-04/FlashCards/FlashCards/Models/Game.swift
1
828
// // Game.swift // FlashCards // // // Copyright (c) 2015 Lou Franco and Eitan Mendelowitz. All rights reserved. // import Foundation class Game { private(set) var cards: [Card] private var currentCard = 0 private var numRight = 0 init(cards: [Card]) { self.cards = cards } func recordAnswer(answer: Int) { if self.cards[self.currentCard].correctAnswer == answer { self.numRight++ } self.currentCard++ } func getCurrentCard() -> Card? { if self.currentCard < self.cards.count { return self.cards[self.currentCard] } return nil } func getNumRight() -> Int { return self.numRight } func getNumWrong() -> Int { return self.currentCard - getNumRight() } }
mit
8ea4155b1c77f36dcf3c7b23cfd6192c
19.219512
77
0.565217
4.078818
false
false
false
false
hyperspacemark/Notice
Notice/Observable.swift
1
1535
import Foundation public final class Observable<Value> { // MARK: - Public Properties public var value: Value { didSet { eventQueue.sync { subscriptions.forEach { $0.send(value) } } } } // MARK: - Initialization public init(initial value: Value) { self.value = value } // MARK: - Public Methods @discardableResult public func subscribe(_ options: SubscriptionOptions = [.new], handler: @escaping (Value) -> Void) -> Subscription<Value> { let subscription = Subscription<Value>(send: handler) subscriptions.insert(subscription) if options.contains(.initial) { subscription.send(value) } return subscription } public func unsubscribe(_ subscriber: Subscription<Value>) { subscriptions.remove(subscriber) } // MARK: - Internal Properties var subscriptions = Set<Subscription<Value>>() // MARK: - Private Properties private let eventQueue = DispatchQueue.global(qos: .default) } extension Observable { public typealias Changeset = (old: Value?, new: Value) /// Returns changes of the parent Observable as tuples of old and new values. public func changesets() -> Observable<Changeset> { let observable = Observable<Changeset>(initial: (old: nil, new: value)) subscribe { value in observable.value = (old: observable.value.new, new: value) } return observable } }
mit
c49a10d18cb0540c335be57e10a1514c
23.365079
127
0.616938
4.842271
false
false
false
false
corichmond/turbo-adventure
project16/Extension/ActionViewController.swift
20
2706
// // ActionViewController.swift // Extension // // Created by Hudzilla on 23/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit import MobileCoreServices class ActionViewController: UIViewController { @IBOutlet weak var script: UITextView! var pageTitle = "" var pageURL = "" override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "done") let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillHideNotification, object: nil) notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillChangeFrameNotification, object: nil) if let inputItem = extensionContext!.inputItems.first as? NSExtensionItem { if let itemProvider = inputItem.attachments?.first as? NSItemProvider { itemProvider.loadItemForTypeIdentifier(kUTTypePropertyList as String, options: nil) { [unowned self] (dict, error) in if dict != nil { let itemDictionary = dict as! NSDictionary let javaScriptValues = itemDictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! NSDictionary self.pageTitle = javaScriptValues["title"] as! String self.pageURL = javaScriptValues["URL"] as! String dispatch_async(dispatch_get_main_queue()) { [unowned self] in self.title = self.pageTitle } } } } } } func adjustForKeyboard(notification: NSNotification) { let userInfo = notification.userInfo! let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window) if notification.name == UIKeyboardWillHideNotification { script.contentInset = UIEdgeInsetsZero } else { script.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0) } script.scrollIndicatorInsets = script.contentInset let selectedRange = script.selectedRange script.scrollRangeToVisible(selectedRange) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func done() { let item = NSExtensionItem() let webDictionary = [NSExtensionJavaScriptFinalizeArgumentKey: ["customJavaScript": script.text]] let customJavaScript = NSItemProvider(item: webDictionary, typeIdentifier: kUTTypePropertyList as String) item.attachments = [customJavaScript] extensionContext!.completeRequestReturningItems([item], completionHandler: nil) } }
unlicense
3c922ec8580aaa18bc934c9ce4cf2ce4
33.692308
128
0.758684
4.747368
false
false
false
false
Sadmansamee/quran-ios
Pods/GenericDataSources/Sources/BatchUpdater.swift
1
2665
// // BatchUpdater.swift // GenericDataSource // // Created by Mohamed Afifi on 4/11/16. // Copyright © 2016 mohamede1945. All rights reserved. // import Foundation protocol BatchUpdater: class { func actualPerformBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) } extension UICollectionView : BatchUpdater { func actualPerformBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) { performBatchUpdates(updates, completion: completion) } } extension UITableView : BatchUpdater { func actualPerformBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) { beginUpdates() updates?() endUpdates() completion?(false) } } private class CompletionBlock { let block: (Bool) -> Void init(block: @escaping (Bool) -> Void) { self.block = block } } private struct AssociatedKeys { static var performingBatchUpdates = "performingBatchUpdates" static var completionBlocks = "completionBlocks" } extension GeneralCollectionView where Self : BatchUpdater { fileprivate var performingBatchUpdates: Bool { get { let value = objc_getAssociatedObject(self, &AssociatedKeys.performingBatchUpdates) as? NSNumber return value?.boolValue ?? false } set { objc_setAssociatedObject(self, &AssociatedKeys.performingBatchUpdates, NSNumber(value: newValue as Bool), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var completionBlocks: [CompletionBlock] { get { let value = objc_getAssociatedObject(self, &AssociatedKeys.completionBlocks) as? [CompletionBlock] return value ?? [] } set { objc_setAssociatedObject(self, &AssociatedKeys.completionBlocks, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func internal_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) { guard !performingBatchUpdates else { if let completion = completion { var blocks = completionBlocks blocks.append(CompletionBlock(block: completion)) completionBlocks = blocks } updates?() return } performingBatchUpdates = true actualPerformBatchUpdates(updates) { [weak self] completed in self?.performingBatchUpdates = false completion?(completed) for block in self?.completionBlocks ?? [] { block.block(completed) } self?.completionBlocks = [] } } }
mit
2ce109c60ba6b7a82a56b5360d1fad22
30.714286
153
0.621997
5.213307
false
false
false
false
milseman/swift
test/Frontend/enforce-exclusivity.swift
14
588
// Test command-line flags for enforcement of the law of exclusivity. // RUN: %swift -enforce-exclusivity=checked %s -emit-silgen // RUN: %swift -enforce-exclusivity=unchecked %s -emit-silgen // Staging flags; eventually these will not be accepted. // RUN: %swift -enforce-exclusivity=dynamic-only %s -emit-silgen // RUN: %swift -enforce-exclusivity=none %s -emit-silgen // RUN: not %swift -enforce-exclusivity=other %s -emit-silgen 2>&1 | %FileCheck -check-prefix=EXCLUSIVITY_UNRECOGNIZED %s // EXCLUSIVITY_UNRECOGNIZED: unsupported argument 'other' to option '-enforce-exclusivity='
apache-2.0
6f7d6b1958eb695c7983beba4cccd917
52.454545
121
0.751701
3.607362
false
true
false
false
Hearst-DD/ObjectMapper
Tests/ObjectMapperTests/NestedKeysTests.swift
3
16120
// // NestedKeysTests.swift // ObjectMapper // // Created by Syo Ikeda on 3/10/15. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import XCTest import ObjectMapper class NestedKeysTests: 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 testNestedKeys() { let JSON: [String: Any] = [ "non.nested.key": "string", "nested": [ "int64": NSNumber(value: INT64_MAX), "bool": true, "int": 255, "double": 100.0 as Double, "float": 50.0 as Float, "string": "String!", "nested": [ "int64Array": [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)], "boolArray": [false, true, false], "intArray": [1, 2, 3], "doubleArray": [1.0, 2.0, 3.0], "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], "stringArray": ["123", "ABC"], "int64Dict": ["1": NSNumber(value: INT64_MAX)], "boolDict": ["2": true], "intDict": ["3": 999], "doubleDict": ["4": 999.999], "floatDict": ["5": 123.456 as Float], "stringDict": ["6": "InDict"], "int64Enum": 1000, "intEnum": 255, "doubleEnum": 100.0, "floatEnum": 100.0, "stringEnum": "String B", "nested": [ "object": ["value": 987], "objectArray": [ ["value": 123], ["value": 456] ], "objectDict": ["key": ["value": 999]] ] ] ] ] let mapper = Mapper<NestedKeys>() let value: NestedKeys! = mapper.map(JSONObject: JSON) XCTAssertNotNil(value) let JSONFromValue = mapper.toJSON(value) let valueFromParsedJSON: NestedKeys! = mapper.map(JSON: JSONFromValue) XCTAssertNotNil(valueFromParsedJSON) XCTAssertEqual(value.nonNestedString, valueFromParsedJSON.nonNestedString) XCTAssertEqual(value.int64, valueFromParsedJSON.int64) XCTAssertEqual(value.bool, valueFromParsedJSON.bool) XCTAssertEqual(value.int, valueFromParsedJSON.int) XCTAssertEqual(value.double, valueFromParsedJSON.double) XCTAssertEqual(value.float, valueFromParsedJSON.float) XCTAssertEqual(value.string, valueFromParsedJSON.string) XCTAssertEqual(value.int64Array, valueFromParsedJSON.int64Array) XCTAssertEqual(value.boolArray, valueFromParsedJSON.boolArray) XCTAssertEqual(value.intArray, valueFromParsedJSON.intArray) XCTAssertEqual(value.doubleArray, valueFromParsedJSON.doubleArray) XCTAssertEqual(value.floatArray, valueFromParsedJSON.floatArray) XCTAssertEqual(value.stringArray, valueFromParsedJSON.stringArray) XCTAssertEqual(value.int64Dict, valueFromParsedJSON.int64Dict) XCTAssertEqual(value.boolDict, valueFromParsedJSON.boolDict) XCTAssertEqual(value.intDict, valueFromParsedJSON.intDict) XCTAssertEqual(value.doubleDict, valueFromParsedJSON.doubleDict) XCTAssertEqual(value.floatDict, valueFromParsedJSON.floatDict) XCTAssertEqual(value.stringDict, valueFromParsedJSON.stringDict) XCTAssertEqual(value.int64Enum, valueFromParsedJSON.int64Enum) XCTAssertEqual(value.intEnum, valueFromParsedJSON.intEnum) XCTAssertEqual(value.doubleEnum, valueFromParsedJSON.doubleEnum) XCTAssertEqual(value.floatEnum, valueFromParsedJSON.floatEnum) XCTAssertEqual(value.stringEnum, valueFromParsedJSON.stringEnum) XCTAssertEqual(value.object, valueFromParsedJSON.object) XCTAssertEqual(value.objectArray, valueFromParsedJSON.objectArray) XCTAssertEqual(value.objectDict, valueFromParsedJSON.objectDict) } func testNestedKeysWithDelimiter() { let JSON: [String: Any] = [ "non.nested->key": "string", "com.tristanhimmelman.ObjectMapper.nested": [ "com.tristanhimmelman.ObjectMapper.int64": NSNumber(value: INT64_MAX), "com.tristanhimmelman.ObjectMapper.bool": true, "com.tristanhimmelman.ObjectMapper.int": 255, "com.tristanhimmelman.ObjectMapper.double": 100.0 as Double, "com.tristanhimmelman.ObjectMapper.float": 50.0 as Float, "com.tristanhimmelman.ObjectMapper.string": "String!", "com.tristanhimmelman.ObjectMapper.nested": [ "int64Array": [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)], "boolArray": [false, true, false], "intArray": [1, 2, 3], "doubleArray": [1.0, 2.0, 3.0], "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], "stringArray": ["123", "ABC"], "int64Dict": ["1": NSNumber(value: INT64_MAX)], "boolDict": ["2": true], "intDict": ["3": 999], "doubleDict": ["4": 999.999], "floatDict": ["5": 123.456 as Float], "stringDict": ["6": "InDict"], "int64Enum": 1000, "intEnum": 255, "doubleEnum": 100.0, "floatEnum": 100.0, "stringEnum": "String B", "com.tristanhimmelman.ObjectMapper.nested": [ "object": ["value": 987], "objectArray": [ ["value": 123], ["value": 456] ], "objectDict": ["key": ["value": 999]] ] ] ] ] let mapper = Mapper<DelimiterNestedKeys>() let value: DelimiterNestedKeys! = mapper.map(JSONObject: JSON) XCTAssertNotNil(value) XCTAssertEqual(value.nonNestedString, "string") XCTAssertEqual(value.int64, NSNumber(value: INT64_MAX)) XCTAssertEqual(value.bool, true) XCTAssertEqual(value.int, 255) XCTAssertEqual(value.double, 100.0 as Double) XCTAssertEqual(value.float, 50.0 as Float) XCTAssertEqual(value.string, "String!") let int64Array = [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)] XCTAssertEqual(value.int64Array, int64Array) XCTAssertEqual(value.boolArray, [false, true, false]) XCTAssertEqual(value.intArray, [1, 2, 3]) XCTAssertEqual(value.doubleArray, [1.0, 2.0, 3.0]) XCTAssertEqual(value.floatArray, [1.0 as Float, 2.0 as Float, 3.0 as Float]) XCTAssertEqual(value.stringArray, ["123", "ABC"]) XCTAssertEqual(value.int64Dict, ["1": NSNumber(value: INT64_MAX)]) XCTAssertEqual(value.boolDict, ["2": true]) XCTAssertEqual(value.intDict, ["3": 999]) XCTAssertEqual(value.doubleDict, ["4": 999.999]) XCTAssertEqual(value.floatDict, ["5": 123.456 as Float]) XCTAssertEqual(value.stringDict, ["6": "InDict"]) XCTAssertEqual(value.int64Enum, Int64Enum.b) XCTAssertEqual(value.intEnum, IntEnum.b) // Skip tests due to float issue - #591 // XCTAssertEqual(value.doubleEnum, DoubleEnum.b) // XCTAssertEqual(value.floatEnum, FloatEnum.b) XCTAssertEqual(value.stringEnum, StringEnum.B) XCTAssertEqual(value.object?.value, 987) XCTAssertEqual(value.objectArray.map { $0.value }, [123, 456]) XCTAssertEqual(value.objectDict["key"]?.value, 999) let JSONFromValue = mapper.toJSON(value) let valueFromParsedJSON: DelimiterNestedKeys! = mapper.map(JSON: JSONFromValue) XCTAssertNotNil(valueFromParsedJSON) XCTAssertEqual(value.nonNestedString, valueFromParsedJSON.nonNestedString) XCTAssertEqual(value.int64, valueFromParsedJSON.int64) XCTAssertEqual(value.bool, valueFromParsedJSON.bool) XCTAssertEqual(value.int, valueFromParsedJSON.int) XCTAssertEqual(value.double, valueFromParsedJSON.double) XCTAssertEqual(value.float, valueFromParsedJSON.float) XCTAssertEqual(value.string, valueFromParsedJSON.string) XCTAssertEqual(value.int64Array, valueFromParsedJSON.int64Array) XCTAssertEqual(value.boolArray, valueFromParsedJSON.boolArray) XCTAssertEqual(value.intArray, valueFromParsedJSON.intArray) XCTAssertEqual(value.doubleArray, valueFromParsedJSON.doubleArray) XCTAssertEqual(value.floatArray, valueFromParsedJSON.floatArray) XCTAssertEqual(value.stringArray, valueFromParsedJSON.stringArray) XCTAssertEqual(value.int64Dict, valueFromParsedJSON.int64Dict) XCTAssertEqual(value.boolDict, valueFromParsedJSON.boolDict) XCTAssertEqual(value.intDict, valueFromParsedJSON.intDict) XCTAssertEqual(value.doubleDict, valueFromParsedJSON.doubleDict) XCTAssertEqual(value.floatDict, valueFromParsedJSON.floatDict) XCTAssertEqual(value.stringDict, valueFromParsedJSON.stringDict) XCTAssertEqual(value.int64Enum, valueFromParsedJSON.int64Enum) XCTAssertEqual(value.intEnum, valueFromParsedJSON.intEnum) XCTAssertEqual(value.doubleEnum, valueFromParsedJSON.doubleEnum) XCTAssertEqual(value.floatEnum, valueFromParsedJSON.floatEnum) XCTAssertEqual(value.stringEnum, valueFromParsedJSON.stringEnum) XCTAssertEqual(value.object, valueFromParsedJSON.object) XCTAssertEqual(value.objectArray, valueFromParsedJSON.objectArray) XCTAssertEqual(value.objectDict, valueFromParsedJSON.objectDict) } } class NestedKeys: Mappable { var nonNestedString: String? var int64: NSNumber? var bool: Bool? var int: Int? var double: Double? var float: Float? var string: String? var int64Array: [NSNumber] = [] var boolArray: [Bool] = [] var intArray: [Int] = [] var doubleArray: [Double] = [] var floatArray: [Float] = [] var stringArray: [String] = [] var int64Dict: [String: NSNumber] = [:] var boolDict: [String: Bool] = [:] var intDict: [String: Int] = [:] var doubleDict: [String: Double] = [:] var floatDict: [String: Float] = [:] var stringDict: [String: String] = [:] var int64Enum: Int64Enum? var intEnum: IntEnum? var doubleEnum: DoubleEnum? var floatEnum: FloatEnum? var stringEnum: StringEnum? var object: Object? var objectArray: [Object] = [] var objectDict: [String: Object] = [:] required init?(map: Map){ } func mapping(map: Map) { nonNestedString <- map["non.nested.key", nested: false] int64 <- map["nested.int64"] bool <- map["nested.bool"] int <- map["nested.int"] double <- map["nested.double"] float <- map["nested.float"] string <- map["nested.string"] int64Array <- map["nested.nested.int64Array"] boolArray <- map["nested.nested.boolArray"] intArray <- map["nested.nested.intArray"] doubleArray <- map["nested.nested.doubleArray"] floatArray <- map["nested.nested.floatArray"] stringArray <- map["nested.nested.stringArray"] int64Dict <- map["nested.nested.int64Dict"] boolDict <- map["nested.nested.boolDict"] intDict <- map["nested.nested.intDict"] doubleDict <- map["nested.nested.doubleDict"] floatDict <- map["nested.nested.floatDict"] stringDict <- map["nested.nested.stringDict"] int64Enum <- map["nested.nested.int64Enum"] intEnum <- map["nested.nested.intEnum"] doubleEnum <- map["nested.nested.doubleEnum"] floatEnum <- map["nested.nested.floatEnum"] stringEnum <- map["nested.nested.stringEnum"] object <- map["nested.nested.nested.object"] objectArray <- map["nested.nested.nested.objectArray"] objectDict <- map["nested.nested.nested.objectDict"] } } class DelimiterNestedKeys: NestedKeys { override func mapping(map: Map) { nonNestedString <- map["non.nested->key", nested: false, delimiter: "->"] int64 <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.int64", delimiter: "->"] bool <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.bool", delimiter: "->"] int <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.int", delimiter: "->"] double <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.double", delimiter: "->"] float <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.float", delimiter: "->"] string <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.string", delimiter: "->"] int64Array <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->int64Array", delimiter: "->"] boolArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->boolArray", delimiter: "->"] intArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->intArray", delimiter: "->"] doubleArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->doubleArray", delimiter: "->"] floatArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->floatArray", delimiter: "->"] stringArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->stringArray", delimiter: "->"] int64Dict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->int64Dict", delimiter: "->"] boolDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->boolDict", delimiter: "->"] intDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->intDict", delimiter: "->"] doubleDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->doubleDict", delimiter: "->"] floatDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->floatDict", delimiter: "->"] stringDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->stringDict", delimiter: "->"] int64Enum <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->int64Enum", delimiter: "->"] intEnum <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->intEnum", delimiter: "->"] doubleEnum <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->doubleEnum", delimiter: "->"] floatEnum <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->floatEnum", delimiter: "->"] stringEnum <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->stringEnum", delimiter: "->"] object <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->object", delimiter: "->"] objectArray <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->objectArray", delimiter: "->"] objectDict <- map["com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->com.tristanhimmelman.ObjectMapper.nested->objectDict", delimiter: "->"] } } class Object: Mappable, Equatable { var value: Int = Int.min required init?(map: Map){ } func mapping(map: Map) { value <- map["value"] } } func == (lhs: Object, rhs: Object) -> Bool { return lhs.value == rhs.value } enum Int64Enum: NSNumber { case a = 0 case b = 1000 } enum IntEnum: Int { case a = 0 case b = 255 } enum DoubleEnum: Double { case a = 0.0 case b = 100.0 } enum FloatEnum: Float { case a = 0.0 case b = 100.0 } enum StringEnum: String { case A = "String A" case B = "String B" }
mit
4a83ec3703b6ff496c68c907e71244b6
39.199501
178
0.730955
3.854615
false
false
false
false
mirai418/leaflet-ios
leaflet/FecPoi.swift
1
2133
// // FecPoi.swift // leaflet // // Created by Mirai Akagawa on 4/6/15. // Copyright (c) 2015 parks-and-rec. All rights reserved. // import UIKit import CoreLocation class FecPoi: NSObject { let feetInMeters:Double = 3.28084 var id: Int! var title: String! var content: String! var imageUrl: String! var image: UIImage! var beaconMajor: Int! var latitude: CLLocationDegrees! var longitude: CLLocationDegrees! var visit: Bool! var distance: Double? var coordinate : CLLocationCoordinate2D! init(id: Int, title: String, content: String, imageUrl: String, beaconMajor: Int, latitude: Double, longitude: Double) { super.init() self.id = id self.title = title self.content = content self.imageUrl = imageUrl self.beaconMajor = beaconMajor self.latitude = latitude self.longitude = longitude self.visit = false self.downloadImage() } override var description : String { return "title: \(title)" } func setVisiting(visit: Bool) { self.visit = visit } func setDistance(distanceInMetric: Double) { self.distance = distanceInMetric * feetInMeters NSNotificationCenter.defaultCenter().postNotificationName("setDistanceNotification", object: self) } func getHumanDistance() -> String { if (self.distance == nil) { // return "Unknown distance away." return "A little further." } else if (self.distance < 10) { return "You are here!" } else { // return "\(Int(self.distance!)) feet away." return "A short walk away!" } } func downloadImage() { var httpClient = HTTPClient() if let url = NSURL(string: GlobalConstants.remoteAPIUrl + self.imageUrl) { httpClient.getImageFromUrl(url) { data in dispatch_async(dispatch_get_main_queue()) { self.image = data } } } } }
mit
89876e26d535bbe99eef9abad44917b3
25.012195
124
0.575715
4.471698
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/RainLevelsModel.swift
1
1652
// // RainLevelsModel.swift // NowCastMapView // // Created by Hiroshi Noto on 6/23/16. // Copyright © 2016 Hiroshi Noto. All rights reserved. // import CoreLocation import Foundation import MapKit public protocol RainLevelsProvider { func rainLevels(with request: RainLevelsModel.Request, completionHandler: ((RainLevelsModel.Result) -> Void)?) throws -> RainLevelsModel.Task } public protocol RainLevelsModelDelegate: class { func rainLevelsModel(_ model: RainLevelsModel, task: RainLevelsModel.Task, result: RainLevelsModel.Result) } open class RainLevelsModel: RainLevelsProvider { open private(set) weak var delegate: RainLevelsModelDelegate? public let baseTime: BaseTime open private(set) var tasks = [Task]() private let semaphore = DispatchSemaphore(value: 1) public init(baseTime: BaseTime, delegate: RainLevelsModelDelegate? = nil) { self.baseTime = baseTime self.delegate = delegate } deinit { tasks.forEach { $0.cancel() } } open func rainLevels(with request: Request, completionHandler: ((Result) -> Void)? = nil) throws -> Task { let task = try Task(model: self, request: request, baseTime: baseTime, delegate: delegate, completionHandler: completionHandler) semaphore.wait() tasks.append(task) semaphore.signal() return task } internal func remove(_ task: Task) { semaphore.wait() defer { self.semaphore.signal() } guard let index = tasks.index(of: task) else { return } tasks.remove(at: index) } }
mit
4c5e263031b48c8a173c6d2a354b366e
25.629032
145
0.6596
4.598886
false
false
false
false
acevest/acecode
learn/AcePlay/AcePlay.playground/Pages/AdvancedOperators.xcplaygroundpage/Contents.swift
1
1157
//: [Previous](@previous) import Foundation var str = "Hello, Advanced Operators" //: [Next](@next) // 自定义运算符 // 除了实现标准运算符,在 Swift 中还可以声明和实现自定义运算符 // 要指定 prefix、infix 或者 postfix 前缀 中缀 后缀 struct Vector2D { var x = 0.0 var y = 0.0 } prefix operator +++ infix operator +-: AdditionPrecedence // 此运算符属于 AdditionPrecedence 优先组 extension Vector2D { static func + (left: inout Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x+right.x, y: left.y+right.y) } static func += (left: inout Vector2D, right: Vector2D) { left = left + right } static prefix func +++ (vector: inout Vector2D) -> Vector2D { vector += vector return vector } static func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.x - right.y) } } var va = Vector2D(x: 1.0, y: 2.0) print(+++va) let firstVector = Vector2D(x: 2.0, y: 3.0) let secondVector = Vector2D(x: 3.0, y: 4.0) print(firstVector +- secondVector)
gpl-2.0
95fe5dfca117156c1665b3889642610c
18.830189
71
0.614653
3.011461
false
false
false
false
arvedviehweger/swift
test/Interpreter/enforce_exclusive_access.swift
1
3196
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out -enforce-exclusivity=checked -Onone // // RUN: %target-run %t/a.out // REQUIRES: executable_test // Tests for traps at run time when enforcing exclusive access. import StdlibUnittest import SwiftPrivatePthreadExtras struct X { var i = 7 } /// Calling this function will begin a read access to the variable referred to /// in the first parameter that lasts for the duration of the call. Any /// accesses in the closure will therefore be nested inside the outer read. func readAndPerform<T>(_ _: UnsafePointer<T>, closure: () ->()) { closure() } /// Begin a modify access to the first paraemter and call the closure inside it. func modifyAndPerform<T>(_ _: UnsafeMutablePointer<T>, closure: () ->()) { closure() } var globalX = X() var ExclusiveAccessTestSuite = TestSuite("ExclusiveAccess") ExclusiveAccessTestSuite.test("Read") { let l = globalX // no-trap _blackHole(l) } // It is safe for a read access to overlap with a read. ExclusiveAccessTestSuite.test("ReadInsideRead") { readAndPerform(&globalX) { let l = globalX // no-trap _blackHole(l) } } ExclusiveAccessTestSuite.test("ModifyInsideRead") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .crashOutputMatches("modify/read access conflict detected on address") .code { readAndPerform(&globalX) { expectCrashLater() globalX = X() } } ExclusiveAccessTestSuite.test("ReadInsideModify") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .crashOutputMatches("read/modify access conflict detected on address") .code { modifyAndPerform(&globalX) { expectCrashLater() let l = globalX _blackHole(l) } } ExclusiveAccessTestSuite.test("ModifyInsideModify") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .crashOutputMatches("modify/modify access conflict detected on address") .code { modifyAndPerform(&globalX) { expectCrashLater() globalX.i = 12 } } var globalOtherX = X() // It is safe for two modifications of different variables // to overlap. ExclusiveAccessTestSuite.test("ModifyInsideModifyOfOther") { modifyAndPerform(&globalOtherX) { globalX.i = 12 // no-trap } } // The access durations for these two modifications do not overlap ExclusiveAccessTestSuite.test("ModifyFollowedByModify") { globalX = X() _blackHole(()) globalX = X() // no-trap } ExclusiveAccessTestSuite.test("ClosureCaptureModifyModify") { var x = X() modifyAndPerform(&x) { // FIXME: This should be caught dynamically. x.i = 12 } } // Test for per-thread enforcement. Don't trap when two different threads // have overlapping accesses ExclusiveAccessTestSuite.test("PerThreadEnforcement") { modifyAndPerform(&globalX) { var (_, otherThread) = _stdlib_pthread_create_block(nil, { (_ : Void) -> () in globalX.i = 12 // no-trap return () }, ()) _ = _stdlib_pthread_join(otherThread!, Void.self) } } runAllTests()
apache-2.0
c538398c19891ebcce61a27dc896fc37
24.165354
82
0.698999
4.035354
false
true
false
false
mozilla-mobile/prox
Prox/ProxTests/TimeIntervalTests.swift
1
3110
/* 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 XCTest @testable import Prox class TimeIntervalTests: 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 hoursAsSeconds(hours: Int) -> TimeInterval { return minutesAsSeconds(minutes: hours * 60) } func minutesAsSeconds(minutes: Int) -> TimeInterval { return TimeInterval(minutes * 60) } func testAsHoursAndMinutes() { let startTime = Date() let endTime = startTime.addingTimeInterval(hoursAsSeconds(hours: 2) + minutesAsSeconds(minutes: 22)) let timeDifference = endTime.timeIntervalSince(startTime) let (hours, mins) = timeDifference.asHoursAndMinutes() XCTAssertEqual(hours, 2) XCTAssertEqual(mins, 22) } func testAsHoursAndMinutesString() { let startTime = Date() let endTime = startTime.addingTimeInterval(hoursAsSeconds(hours: 2) + minutesAsSeconds(minutes: 22)) let timeDifference = endTime.timeIntervalSince(startTime) let timeDifferenceString = timeDifference.asHoursAndMinutesString() XCTAssertEqual(timeDifferenceString, "2 hours, 22 minutes") } func testAsHoursAndMinutesStringZeroHours() { let startTime = Date() let endTime = startTime.addingTimeInterval(minutesAsSeconds(minutes: 22)) let timeDifference = endTime.timeIntervalSince(startTime) let timeDifferenceString = timeDifference.asHoursAndMinutesString() XCTAssertEqual(timeDifferenceString, "22 minutes") } func testAsHoursAndMinutesStringZeroMinutes() { let startTime = Date() let endTime = startTime.addingTimeInterval(hoursAsSeconds(hours: 2)) let timeDifference = endTime.timeIntervalSince(startTime) let timeDifferenceString = timeDifference.asHoursAndMinutesString() XCTAssertEqual(timeDifferenceString, "2 hours") } func testAsHoursAndMinutesStringOneHour() { let startTime = Date() let endTime = startTime.addingTimeInterval(hoursAsSeconds(hours: 1)) let timeDifference = endTime.timeIntervalSince(startTime) let timeDifferenceString = timeDifference.asHoursAndMinutesString() XCTAssertEqual(timeDifferenceString, "1 hour") } func testAsHoursAndMinutesStringOneMinute() { let startTime = Date() let endTime = startTime.addingTimeInterval(minutesAsSeconds(minutes: 1)) let timeDifference = endTime.timeIntervalSince(startTime) let timeDifferenceString = timeDifference.asHoursAndMinutesString() XCTAssertEqual(timeDifferenceString, "1 minute") } }
mpl-2.0
4bdf3777aabf2360e2f3331633b29b22
33.94382
111
0.700322
5.37133
false
true
false
false
wowiwj/Yeep
Yeep/Yeep/Views/Buttons/BorderButton.swift
1
963
// // BorderButton.swift // Yeep // // Created by wangju on 16/7/18. // Copyright © 2016年 wangju. All rights reserved. // import UIKit @IBDesignable class BorderButton: UIButton { /* IBDesignable 主要作用:可以显示出来你使用代码写的界面。 使用方法:在Swift里,@IBDesignable关键字写在class前即可。 在OC里,是IB_DESIGNABLE这个关键字,写在@implementation前即可 IBInspectable 主要作用:使view内的变量可视化,并且可以修改后马上看到 */ @IBInspectable var cornerRadius: CGFloat = 6 @IBInspectable var borderColor: UIColor = UIColor.yeepTintColor() @IBInspectable var borderWidth: CGFloat = 1 override func didMoveToSuperview() { super.didMoveToSuperview() layer.cornerRadius = cornerRadius layer.borderColor = borderColor.CGColor layer.borderWidth = borderWidth } }
mit
02ab9bada35957aca7b30ff297c6297f
21.333333
69
0.676617
4.102041
false
false
false
false
Driftt/drift-sdk-ios
Drift/Helpers/DriftDateFormatter.swift
2
1141
// // DriftDateFormatter.swift // Conversations // // Created by Brian McDonald on 16/05/2016. // Copyright © 2016 Drift. All rights reserved. // class DriftDateFormatter: DateFormatter { func createdAtStringFromDate(_ date: Date) -> String{ dateFormat = "HH:mm" timeStyle = .short return string(from: date) } func updatedAtStringFromDate(_ date: Date) -> String{ let now = Date() if Calendar.current.component(.day, from: date) != Calendar.current.component(.day, from: now){ dateStyle = .short }else{ dateFormat = "H:mm a" } return string(from: date) } func headerStringFromDate(_ date: Date) -> String{ let now = Date() if Calendar.current.component(.day, from: date) != Calendar.current.component(.day, from: now){ dateFormat = "MMMM d" }else{ return "Today" } return string(from: date) } func dateFormatForMeetings(date: Date) -> String { dateFormat = "EEEE, MMMM dd, YYYY" return string(from: date) } }
mit
f5aa02dfa5a9637848dbd9cc2af4ba1b
25.511628
103
0.573684
4.191176
false
false
false
false
omardroubi/RankUp
RankUp/SignUp.swift
1
7261
// // SignUp.swift // RankUp // // Created by Omar Droubi on 12/29/16. // Copyright © 2016 Omar Droubi. All rights reserved. // //////////////////////////////////////////// // This class is used in the sign up page // //////////////////////////////////////////// import UIKit import Firebase import FirebaseDatabase class SignUp: UIViewController, UITextFieldDelegate { // Add to Database when done var eventRef = FIRDatabase.database().reference().child("Users") //////////////////////// // Read from Database var eventRefRead: FIRDatabaseReference! var listOfUsers: [(String, String)] = [] ///////////////////////////////////////// var nameGiven: String = "" var idGiven: String = "" var workGiven: String = "" @IBOutlet var displayPicture: UIImageView! //display picture @IBOutlet var name: UITextField! // edit given name by FB @IBOutlet var work: UITextField! // edit given work by FB @IBOutlet var newUsername: UITextField! // new username text @IBOutlet var newPassword: UITextField! // new password text @IBOutlet var newPasswordCheck: UITextField! // check new password text override func viewDidAppear(_ animated: Bool) { //Alert about correct work/email let alert = UIAlertController(title: "Check if Work/School Name is correct", message: "Make sure that your work or school name is written exactly like on Facebook", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBOutlet var tempImageView: UIImageView! // First Method Called override func viewDidLoad() { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) //Depending on your image, it might look better to use UIBlurEffect(style: UIBlurEffectStyle.ExtraLight) or UIBlurEffect(style: UIBlurEffectStyle.Dark). let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = tempImageView.bounds tempImageView.addSubview(blurView) // Edit the placeholders in the textfield (Color + Keyboard Next) let placeholder1 = NSAttributedString(string: "Name", attributes: [NSForegroundColorAttributeName:UIColor.white]) let placeholder2 = NSAttributedString(string: "Work/School", attributes: [NSForegroundColorAttributeName:UIColor.white]) let placeholder3 = NSAttributedString(string: "New Username", attributes: [NSForegroundColorAttributeName:UIColor.white]) let placeholder4 = NSAttributedString(string: "New Password", attributes: [NSForegroundColorAttributeName:UIColor.white]) let placeholder5 = NSAttributedString(string: "Enter Password again", attributes: [NSForegroundColorAttributeName:UIColor.white]) name.attributedPlaceholder = placeholder1 work.attributedPlaceholder = placeholder2 newUsername.attributedPlaceholder = placeholder3 newPassword.attributedPlaceholder = placeholder4 newPasswordCheck.attributedPlaceholder = placeholder5 name.delegate = self name.tag = 0 //Increment accordingly work.delegate = self work.tag = 1 newUsername.delegate = self newUsername.tag = 2 newPassword.delegate = self newPassword.tag = 3 newPasswordCheck.delegate = self newPasswordCheck.tag = 4 name.text = nameGiven work.text = workGiven print("Name Given: " + nameGiven) print("ID Given: " + idGiven) print("Work Given: " + workGiven) // Show Facebook Image displayPicture.downloadedFrom(link: "https://graph.facebook.com/" + self.idGiven + "/picture?type=large") displayPicture.setRounded() // Read DATABASE eventRefRead = FIRDatabase.database().reference() eventRefRead.child("Users").queryOrderedByKey().observe(.childAdded, with: { snapshot in let snapshotValue = snapshot.value as? NSDictionary let username = snapshotValue!["Username"] as! String let password = snapshotValue!["Password"] as! String self.listOfUsers.append((username, password)) }) print(listOfUsers) } // Change picture method @IBAction func changePicture(_ sender: Any) { } // Orange Login Button Pressed (DONE) @IBAction func loginPressed(_ sender: Any) { // Alert about field left empty if name.text! == "" || newPassword.text! == "" || newUsername.text! == "" || work.text! == ""{ let alert = UIAlertController(title: "Some fields are empty", message: "Please fill all required fields", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { var alreadyThere: Bool = false for (user, pass) in listOfUsers { if newUsername.text! == user { alreadyThere = true let alert = UIAlertController(title: "Username already exists", message: "Try another username", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) break } } if alreadyThere == false { let eventRef = self.eventRef.child(self.idGiven) eventRef.setValue(["Name": name.text!, "Password": newPassword.text!, "ID": self.idGiven, "Username": newUsername.text!, "Display Picture": "https://graph.facebook.com/" + self.idGiven + "/picture?type=large", "Work or School": work.text!, "Ratings": "", "Crushes": "", "Average": "5", "isPrivate": "true", "Recommendations": ""]) UserDefaults.standard.set(true, forKey: "LoggedIn") performSegue(withIdentifier: "toHome", sender: self) } } } // To remove keyboard when finished writing override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } // Used for Keyboard Next & Done from a textfield to the other func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Try to find next responder if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField { nextField.becomeFirstResponder() } else { // Not found, so remove keyboard. loginPressed(Any) } // Do not add a line break return true } }
apache-2.0
5798e708c127d3ffb7ad55291627db52
35.666667
346
0.605372
5.357934
false
false
false
false
fangandyuan/FYPlayer
FYPlayer/FYPlayerViewController.swift
1
2407
// // PlayerViewController.swift // FYPlayer // // Created by 方圆 on 2017/8/11. // Copyright © 2017年 fangyuan. All rights reserved. // import UIKit class FYPlayerViewController: UIViewController , FYPlayerViewDelegate { var playUrl : String? var vidoeName : String? var playerView : FYPlayerView? var timer : Timer? var nextBtn : UIButton? var options : FYPlayerOption? var netShowView : FYNetNotiView? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white options = FYPlayerOption() options?.isPlaying = true options?.isBeingActiveState = true options?.isBeingAppearState = true options?.interfaceOrientation = UIDevice.current.orientation let frame = CGRect(x: 0, y:FYNavHeight, width: 0, height: 200); playerView = FYPlayerView(frame: frame,urlStr: playUrl!, options: options!) playerView?.delegate = self as FYPlayerViewDelegate view.addSubview(playerView!) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(FYPlayerViewController.backTap)) } //释放播放器以及所有的子控件 func releasePlayerView() { playerView?.releasePlayer() playerView?.removeFromSuperview() playerView = nil } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } func backTap() {//返回 if self.navigationController != nil { navigationController?.popViewController(animated: true) }else { dismiss(animated: true, completion: nil) } releasePlayerView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var shouldAutorotate: Bool { return false } }
mit
3f5ccbe9d0146e8ad49b935afb1a839b
27.214286
149
0.645992
5.290179
false
false
false
false
blinksh/blink
BlinkFileProvider/FileProviderEnumerator.swift
1
9383
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import BlinkFiles import FileProvider import Combine import SSH class FileProviderEnumerator: NSObject, NSFileProviderEnumerator { let identifier: BlinkItemIdentifier let translator: AnyPublisher<Translator, Error> var cancellableBag: Set<AnyCancellable> = [] var currentAnchor: Int = 0 let log: BlinkLogger init(enumeratedItemIdentifier: NSFileProviderItemIdentifier, domain: NSFileProviderDomain) { // TODO An enumerator may be requested for an open file, in order to enumerate changes to it. if enumeratedItemIdentifier == .rootContainer { self.identifier = BlinkItemIdentifier(domain.pathRelativeToDocumentStorage) } else { self.identifier = BlinkItemIdentifier(enumeratedItemIdentifier) } let path = self.identifier.path self.log = BlinkLogger("enumeratorFor \(path)") self.log.debug("Initialized") self.translator = FileTranslatorCache.translator(for: self.identifier) .flatMap { t -> AnyPublisher<Translator, Error> in path.isEmpty ? .just(t.clone()) : t.cloneWalkTo(path) }.eraseToAnyPublisher() // TODO Schedule an interval enumeration (pull) from the server. super.init() } func invalidate() { // TODO: perform invalidation of server connection if necessary? // Stop the enumeration self.log.debug("Invalidate") cancellableBag = [] } func enumerateItems(for observer: NSFileProviderEnumerationObserver, startingAt page: NSFileProviderPage) { /* - inspect the page to determine whether this is an initial or a follow-up request If this is an enumerator for a directory, the root container or all directories: - perform a server request to fetch directory contents If this is an enumerator for the active set: - perform a server request to update your local database - fetch the active set from your local database - inform the observer about the items returned by the server (possibly multiple times) - inform the observer that you are finished with this page */ self.log.info("Enumeration requested") // We use the local files and the representation of the remotes to construct the view of the system. // It is a simpler way to warm up the local cache without having a persistent representation. var containerTranslator: Translator! translator .flatMap { t -> AnyPublisher<FileAttributes, Error> in containerTranslator = t return t.stat() } .map { containerAttrs -> Translator in // 1. Store the container reference // TODO We may be able to skip this if stat would return '.' if let reference = FileTranslatorCache.reference(identifier: self.identifier) { reference.updateAttributes(remote: containerAttrs) } else { let ref = BlinkItemReference(self.identifier, remote: containerAttrs) FileTranslatorCache.store(reference: ref) } return containerTranslator } .flatMap { // 2. Stat both local and remote files. // For remote, if the file is a link, then stat to know the real attributes Publishers.Zip($0.isDirectory ? $0.directoryFilesAndAttributesResolvingLinks() : AnyPublisher($0.stat().collect()), Local().walkTo(self.identifier.url.path) .flatMap { $0.isDirectory ? $0.directoryFilesAndAttributes() : AnyPublisher($0.stat().collect()) } .catch { _ in AnyPublisher.just([]) }) } .map { (remoteFilesAttributes, localFilesAttributes) -> [BlinkItemReference] in // 3.1 Collect all current file references return remoteFilesAttributes.map { attrs -> BlinkItemReference in // 3.2 Match local and remote files, and upsert accordingly let fileIdentifier = BlinkItemIdentifier(parentItemIdentifier: self.identifier, filename: attrs[.name] as! String) // Find a local file that matches the remote. let localAttrs = localFilesAttributes.first(where: { $0[.name] as! String == fileIdentifier.filename }) if let reference = FileTranslatorCache.reference(identifier: fileIdentifier) { reference.updateAttributes(remote: attrs, local: localAttrs) return reference } else { let ref = BlinkItemReference(fileIdentifier, remote: attrs, local: localAttrs) // Store the reference in the internal DB for later usage. FileTranslatorCache.store(reference: ref) return ref } } } .sink( receiveCompletion: { completion in switch completion { case .failure(let error): self.log.error("\(error)") observer.finishEnumeratingWithError(error) case .finished: observer.finishEnumerating(upTo: nil) } }, receiveValue: { self.log.info("Enumerated \($0.count) items") observer.didEnumerate($0) }).store(in: &cancellableBag) } func enumerateChanges(for observer: NSFileProviderChangeObserver, from anchor: NSFileProviderSyncAnchor) { /* TODO: - query the server for updates since the passed-in sync anchor If this is an enumerator for the active set: - note the changes in your local database - inform the observer about item deletions and updates (modifications + insertions) - inform the observer when you have finished enumerating up to a subsequent sync anchor */ // Schedule changes let anchor = UInt(String(data: anchor.rawValue, encoding: .utf8)!)! self.log.info("Enumerating changes at \(anchor) anchor") guard let ref = FileTranslatorCache.reference(identifier: self.identifier) else { observer.finishEnumeratingWithError("Op not supported") return } if let updatedItems = FileTranslatorCache.updatedItems(container: self.identifier, since: anchor) { // Atm only update changes, no deletion as we don't provide tombstone values. self.log.info("\(updatedItems.count) items updated.") observer.didUpdate(updatedItems) } else if anchor < ref.syncAnchor { observer.didUpdate([ref]) } let newAnchor = ref.syncAnchor let data = "\(newAnchor)".data(using: .utf8) observer.finishEnumeratingChanges(upTo: NSFileProviderSyncAnchor(data!), moreComing: false) } /** Request the current sync anchor. To keep an enumeration updated, the system will typically - request the current sync anchor (1) - enumerate items starting with an initial page - continue enumerating pages, each time from the page returned in the previous enumeration, until finishEnumeratingUpToPage: is called with nextPage set to nil - enumerate changes starting from the sync anchor returned in (1) - continue enumerating changes, each time from the sync anchor returned in the previous enumeration, until finishEnumeratingChangesUpToSyncAnchor: is called with moreComing:NO This method will be called again if you signal that there are more changes with -[NSFileProviderManager signalEnumeratorForContainerItemIdentifier: completionHandler:] and again, the system will enumerate changes until finishEnumeratingChangesUpToSyncAnchor: is called with moreComing:NO. NOTE that the change-based observation methods are marked optional for historical reasons, but are really required. System performance will be severely degraded if they are not implemented. */ func currentSyncAnchor(completionHandler: @escaping (NSFileProviderSyncAnchor?) -> Void) { guard let ref = FileTranslatorCache.reference(identifier: self.identifier) else { completionHandler(nil) return } self.log.info("Requested anchor \(ref.syncAnchor)") let data = "\(ref.syncAnchor)".data(using: .utf8) completionHandler(NSFileProviderSyncAnchor(data!)) } }
gpl-3.0
caa09773ac6b994dd90776d697b58c43
40.702222
123
0.674518
5.031099
false
false
false
false
pitput/SwiftWamp
SwiftWamp/Messages/Auth/AuthenticateSwampMessage.swift
1
738
// // AuthenticateSwampMessage.swift // Pods // // Created by Yossi Abraham on 22/08/2016. // // import Foundation import SwiftyJSON /// [AUTHENTICATE, signature|string, extra|dict] class AuthenticateSwampMessage: SwampMessage { let type: SwampMessageType = .authenticate let signature: String let extra: [String: Any] init(signature: String, extra: [String: Any]) { self.signature = signature self.extra = extra } // MARK: SwampMessage protocol required init(payload: [Any]) { self.signature = payload[0] as! String self.extra = payload[1] as! [String: Any] } func marshal() -> [Any] { return [self.type.rawValue, self.signature, self.extra] } }
mit
f7d438f9ba1fcc8e82be07841523f22c
20.705882
63
0.640921
3.746193
false
false
false
false
lukevanin/OCRAI
CardScanner/DocumentModel.swift
1
12903
// // DocumentModel.swift // CardScanner // // Created by Luke Van In on 2017/03/12. // Copyright © 2017 Luke Van In. All rights reserved. // import UIKit import CoreData protocol DocumentModelDelegate: class { func documentModel(model: DocumentModel, didUpdateWithChanges changes: DocumentModel.Changes) } extension UITableView { func applyChanges(_ changes: DocumentModel.Changes) { assert(Thread.isMainThread) if changes.hasIncrementalChanges { beginUpdates() if let sections = changes.deletedSections, sections.count > 0 { deleteSections(sections, with: .fade) } if let sections = changes.insertedSections, sections.count > 0 { insertSections(sections, with: .fade) } if let indexPaths = changes.deletedRows, indexPaths.count > 0 { deleteRows(at: indexPaths, with: .fade) } if let indexPaths = changes.insertedRows, indexPaths.count > 0 { insertRows(at: indexPaths, with: .fade) } if let indexPaths = changes.updatedRows, indexPaths.count > 0 { deleteRows(at: indexPaths, with: .fade) insertRows(at: indexPaths, with: .fade) } if let moves = changes.movedRows, moves.count > 0 { for (from, to) in moves { moveRow(at: from, to: to) } } endUpdates() } else { reloadData() } } } class DocumentModel { struct Changes { let hasIncrementalChanges: Bool let insertedSections: IndexSet? let deletedSections: IndexSet? let insertedRows: [IndexPath]? let deletedRows: [IndexPath]? let updatedRows: [IndexPath]? let movedRows: [(IndexPath, IndexPath)]? init( hasIncrementalChanges: Bool, insertedSections: IndexSet? = nil, deletedSections: IndexSet? = nil, insertedRows: [IndexPath]? = nil, deletedRows: [IndexPath]? = nil, updatedRows: [IndexPath]? = nil, movedRows: [(IndexPath, IndexPath)]? = nil ) { self.hasIncrementalChanges = hasIncrementalChanges self.insertedSections = insertedSections self.deletedSections = deletedSections self.insertedRows = insertedRows self.deletedRows = deletedRows self.updatedRows = updatedRows self.movedRows = movedRows } } struct Action { fileprivate typealias Action = () -> Void let title: String fileprivate let action: Action fileprivate init(title: String, action: @escaping Action) { self.title = title self.action = action } func execute() { action() } } private class Section { let title: String let actions: [Action] var objects: [NSManagedObject] init(title: String, objects: [NSManagedObject], actions: [Action]) { self.title = title self.objects = objects self.actions = actions } @discardableResult func remove(at: Int) -> NSManagedObject { let output = objects.remove(at: at) return output } func append(_ fragment: NSManagedObject) -> Int { let index = objects.count insert(fragment, at: index) return index } func insert(_ fragment: NSManagedObject, at: Int) { objects.insert(fragment, at: at) } } weak var delegate: DocumentModelDelegate? var isEditing: Bool = false { didSet { guard isEditing != oldValue else { return } var indexPaths = [IndexPath]() for s in 0 ..< sections.count { let section = sections[s] let o = section.objects.count let a = section.actions.count for i in 0 ..< a { let indexPath = IndexPath(row: o + i, section: s) indexPaths.append(indexPath) } } let changes: Changes if isEditing { changes = Changes( hasIncrementalChanges: true, insertedRows: indexPaths ) } else { changes = Changes( hasIncrementalChanges: true, deletedRows: indexPaths ) } notify(with: changes) } } var totalFragments: Int { var count = 0 for i in 0 ..< numberOfSections { count += numberOfRowsInSection(i) } return count } var numberOfSections: Int { return sections.count } private var sections = [Section]() private let document: Document private let coreData: CoreDataStack init(document: Document, coreData: CoreDataStack) { self.document = document self.coreData = coreData fetch() } func fetch() { var deletedSectionIndices = IndexSet() var insertedSectionIndices = IndexSet() var insertedIndexPaths = [IndexPath]() for i in 0 ..< sections.count { deletedSectionIndices.insert(i) } sections = makeSections() for i in 0 ..< sections.count { insertedSectionIndices.insert(i) let section = sections[i] for j in 0 ..< section.objects.count { let indexPath = IndexPath(item: j, section: i) insertedIndexPaths.append(indexPath) } } let changes = Changes( hasIncrementalChanges: true, insertedSections: insertedSectionIndices, deletedSections: deletedSectionIndices, insertedRows: insertedIndexPaths ) notify(with: changes) } private func makeSections() -> [Section] { var sections = [Section]() for fieldType in FieldType.all { sections.append(makeSection(sections.count, type: fieldType)) } sections.append(makeAddressSection(sections.count)) // FIXME: Add images // FIXME: Add dates // return sections.filter { $0.values.count > 0 } return sections } private func makeSection(_ section: Int, type: FieldType) -> Section { let title = String(describing: type.description) let objects = document.fields(ofType: type) let action = Action(title: "Add \(title)") { [weak self, document, coreData] in let context = coreData.mainContext let field = Field(type: type, value: "", ordinality: 0, context: context) field.document = document self?.insert(value: field, in: section) } return Section(title: title, objects: objects, actions: [action]) } private func makeAddressSection(_ section: Int) -> Section { let title = "Address" let objects = document.allPostalAddresses let action = Action(title: "Add \(title)") { [weak self, document, coreData] in let context = coreData.mainContext let field = PostalAddress(address: nil, location: nil, context: context) field.document = document self?.insert(value: field, in: section) } return Section(title: title, objects: objects, actions: [action]) } // MARK: Observer private func notify(with changes: Changes) { delegate?.documentModel(model: self, didUpdateWithChanges: changes) } // MARK: Query func titleForSection(at index: Int) -> String { return sections[index].title } func numberOfRowsInSection(_ index: Int) -> Int { let section = sections[index] let objectCount = section.objects.count let actionCount = isEditing ? section.actions.count : 0 return objectCount + actionCount } func fragment(at indexPath: IndexPath) -> Any { let section = sections[indexPath.section] if indexPath.row < section.objects.count { return section.objects[indexPath.row] } else { return section.actions[indexPath.row - section.objects.count] } } func performAction(at indexPath: IndexPath) { guard let action = fragment(at: indexPath) as? Action else { return } action.execute() } // MARK: Modify func save() { coreData.saveNow() } func clear() { var sectionIndices = IndexSet() var indexPaths = [IndexPath]() var fragments = [NSManagedObject]() for i in 0 ..< sections.count { let section = sections[i] let count = section.objects.count for j in 0 ..< count { let indexPath = IndexPath(row: j, section: i) indexPaths.append(indexPath) let fragment = self.fragment(at: indexPath) if let object = fragment as? NSManagedObject { fragments.append(object) } } sectionIndices.insert(i) } sections.removeAll() let context = coreData.mainContext for fragment in fragments { context.delete(fragment) } save() let changes = Changes( hasIncrementalChanges: true, deletedSections: sectionIndices, deletedRows: indexPaths ) notify(with: changes) } func delete(at indexPaths: [IndexPath]) { guard indexPaths.count > 0 else { return } let context = coreData.mainContext for indexPath in indexPaths { let section = sections[indexPath.section] let fragment = section.remove(at: indexPath.row) context.delete(fragment) } save() let changes = Changes( hasIncrementalChanges: true, deletedRows: indexPaths ) notify(with: changes) } private func insert(value: NSManagedObject, in sectionIndex: Int) { let section = sections[sectionIndex] let index = section.append(value) save() let indexPath = IndexPath(row: index, section: sectionIndex) let changes = Changes( hasIncrementalChanges: true, insertedRows: [indexPath] ) notify(with: changes) } func cleanup() { var indexPaths = [IndexPath]() for s in 0 ..< sections.count { let section = sections[s] var keepObjects = [NSManagedObject]() for v in 0 ..< section.objects.count { let object = section.objects[v] let indexPath = IndexPath(row: v, section: s) var isEmpty = false // FIXME: Create protocol with isEmpty property. Make Field and PostalAddress conformant. if let field = object as? Field { isEmpty = field.value?.isEmpty ?? true } else if let field = object as? PostalAddress { let isStreetEmpty = field.street?.isEmpty ?? true let isCityEmpty = field.city?.isEmpty ?? true let isCodeEmpty = field.postalCode?.isEmpty ?? true let isCountryEmpty = field.country?.isEmpty ?? true isEmpty = isStreetEmpty && isCityEmpty && isCodeEmpty && isCountryEmpty } if isEmpty { indexPaths.append(indexPath) } else { keepObjects.append(object) } } section.objects = keepObjects } let changes = Changes( hasIncrementalChanges: true, deletedRows: indexPaths ) notify(with: changes) } }
mit
91b654ebe3634c7bcd3339df0d24fbf8
28.865741
105
0.520384
5.527849
false
false
false
false
asharijuang/playground-collection
Conditionals.playground/Contents.swift
1
938
//: Playground - noun: a place where people can play import UIKit // Basic condition using if else var umur = 18 if umur >= 17 { print("Kamu sudah beranjak dewasa") }else { print("Saat ini kamu terlalu muda") } // equal var nama = "juang" if nama == "septi" { print("hi \(nama)") }else { print("Saya yakin namamu bukan juang") } // 2 statement if nama == "juang" && umur >= 17 { print("Hi \(nama), kamu sudah beranjak dewasa") }else { print("Maaf saya sedang mencari juang") } // statemen or menggunakan tanda || // statement with boolean var keputusan = true if keputusan { print("Ini yang terbaik buat kamu") } // else if var username = "admin" var pass = "password" if username == "admin" && pass == "" { print("Password anda salah atau password tidak boleh kosong") }else if username == "" && pass == "password" { print("Username tidak boleh kosong") }else { print("Selamat datang") }
mit
473d61990866df025120547b1dfc609e
18.5625
65
0.641791
2.868502
false
false
false
false
SpacyRicochet/NWAAlertController
Example/NWAAlertController/ViewController.swift
1
3295
// // ViewController.swift // NWAAlertController // // Created by Bruno Scheele on 06/27/2015. // Copyright (c) 06/27/2015 Bruno Scheele. All rights reserved. // import UIKit import NWAAlertController class ViewController: UIViewController { @IBOutlet weak var stackView: UIStackView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print("UIStackView layoutMargins: \(stackView.layoutMargins) and layoutMarginsRelativeArrangement: \(stackView.layoutMarginsRelativeArrangement)") // stackView.layoutMargins = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) // stackView.layoutMarginsRelativeArrangement = true // print("UIStackView layoutMargins: \(stackView.layoutMargins) and layoutMarginsRelativeArrangement: \(stackView.layoutMarginsRelativeArrangement)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - User Interaction @IBAction func showUIAlertControllerTapped(sender: AnyObject) { let alertController = UIAlertController(title: "Test", message: "This is what we want to create as a first alert view.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Dismiss this view", style: .Default, handler: nil)) alertController.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func showNWAAlertControllerTapped(sender: AnyObject) { let alertController = NWAAlertController(title: "Test", message: "This is what we want to create as a first alert view.", preferredStyle: .Alert) alertController.addAction(NWAAlertAction(title: "Dismiss this view", style: .Default) { (action) -> Void in print("Dismiss tapped") }) alertController.addAction(NWAAlertAction(title: "Cancel", style: .Default) { (action) -> Void in print("Cancel tapped") }) self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func showNWAWithColorsTapped(sender: AnyObject) { let alertController = NWAAlertController(title: "Test", message: "This is what we want to create as a first alert view.", preferredStyle: .Alert) alertController.overlayBackgroundColor = UIColor.redColor().colorWithAlphaComponent(0.4) alertController.alertBackgroundColor = UIColor.yellowColor() alertController.destructiveBackgroundColor = UIColor.greenColor() alertController.destructiveTitleColor = UIColor.cyanColor() alertController.addAction(NWAAlertAction(title: "Destructive!", style: .Destructive, handler: nil)) alertController.addAction(NWAAlertAction(title: "Red background", style: .Cancel, handler: nil)) alertController.addAction(NWAAlertAction(title: "Yellow alert", style: .Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
79eae9a96da22f66b54275904b81ab1c
44.763889
156
0.696813
5.156495
false
false
false
false
crossroadlabs/ExpressCommandLine
swift-express/Core/Steps/CarthageInstallLibs.swift
1
3685
//===--- CarthageInstallLibs.swift -------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line 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. // //Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===-------------------------------------------------------------===// import Foundation import Regex // Install carthage dependencies. //Input: // workingFolder //Output: // None struct CarthageInstallLibs : RunSubtaskStep { let dependsOn = [Step]() let platform = "Mac" let updateCommand: String let force:Bool let fetchOnly: Bool init(updateCommand: String = "bootstrap", force: Bool = true, fetchOnly: Bool = false) { self.updateCommand = updateCommand self.force = force self.fetchOnly = fetchOnly } func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] { guard let workingFolder = params["workingFolder"] as? String else { throw SwiftExpressError.BadOptions(message: "CarthageInstallLibs: No workingFolder option.") } if !force && FileManager.isDirectoryExists(workingFolder.addPathComponent("Carthage").addPathComponent("Build")) { //All ok. We already have build dependencies return [String:Any]() } var args = [updateCommand, "--platform", platform] if fetchOnly { args.insert("--no-build", atIndex: 1) } let result = try executeSubtaskAndWait(SubTask(task: "/usr/local/bin/carthage", arguments: args, workingDirectory: workingFolder, environment: nil, useAppOutput: true)) if result != 0 { throw SwiftExpressError.SubtaskError(message: "CarthageInstallLibs: bootstrap failed. Exit code \(result)") } return [String:Any]() } func cleanup(params: [String : Any], output: StepResponse) throws { let workingFolder = params["workingFolder"]! as! String let plRe = platform.r! let cartBuildFolder = workingFolder.addPathComponent("Carthage").addPathComponent("Build") do { let plfms = try FileManager.listDirectory(cartBuildFolder) for plf in plfms { if plRe.matches(plf) { continue } try FileManager.removeItem(cartBuildFolder.addPathComponent(plf)) } } catch { print("CarthageInstallLibs: Some error on cleanup \(error)") } } func revert(params:[String: Any], output: [String: Any]?, error: SwiftExpressError?) { if let workingFolder = params["workingFolder"] { do { let cartPath = (workingFolder as! String).addPathComponent("Carthage") if FileManager.isDirectoryExists(cartPath) { try FileManager.removeItem(cartPath) } } catch { print("Can't revert CarthageInstallLibs: \(error)") } } } }
gpl-3.0
4bdecbb966b7b6bf3f3daa125695aa20
37.395833
176
0.614654
4.973009
false
false
false
false
thelukester92/swift-engine
swift-engine/Engine/Classes/LGTileMap.swift
1
1008
// // LGTileMap.swift // swift-engine // // Created by Luke Godfrey on 6/21/14. // Copyright (c) 2014 Luke Godfrey. See LICENSE. // public class LGTileMap { /// The width of the map in tiles. public var width: Int /// The height of the map in tiles. public var height: Int /// The width of a single tile in pixels. public var tileWidth: Int /// The height of a single tile in pixels. public var tileHeight: Int public var layers = [LGTileLayer]() public var spriteSheet: LGSpriteSheet! public init(width: Int, height: Int, tileWidth: Int, tileHeight: Int) { self.width = width self.height = height self.tileWidth = tileWidth self.tileHeight = tileHeight } public convenience init(spriteSheet: LGSpriteSheet, width: Int, height: Int, tileWidth: Int, tileHeight: Int) { self.init(width: width, height: height, tileWidth: tileWidth, tileHeight: tileHeight) self.spriteSheet = spriteSheet } public func add(layer: LGTileLayer) { layers.append(layer) } }
mit
f71e6cc910fec75c4904c4cbd3b50076
21.909091
110
0.699405
3.230769
false
false
false
false
taqun/TodoEver
TodoEver/Classes/Operation/TDEUpdateNoteOperation.swift
1
1503
// // TDEUpdateNoteOperation.swift // TodoEver // // Created by taqun on 2015/06/02. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit class TDEUpdateNoteOperation: TDEConcurrentOperation { private var guid: EDAMGuid private var edamNoteToUpdate: EDAMNote! init(guid: EDAMGuid) { self.guid = guid super.init() } /* * Public Method */ override func start() { super.start() let semaphore = dispatch_semaphore_create(0) let noteStore = ENSession.sharedSession().primaryNoteStore() let note = TDEModelManager.sharedInstance.getNoteByGuid(self.guid) edamNoteToUpdate = note.generateEDAMNote() noteStore.updateNote(edamNoteToUpdate, success: { (edamNote) -> Void in self.updateNote(edamNote) dispatch_semaphore_signal(semaphore) }) { (error) -> Void in println(error) dispatch_semaphore_signal(semaphore) } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) self.complete() } /* * Private Method */ func updateNote(edamNote: EDAMNote) { let note = TDEModelManager.sharedInstance.getNoteByGuid(self.guid) note.usn = edamNote.updateSequenceNum note.content = self.edamNoteToUpdate.content } }
mit
2b4596dc149354aec0e646f585e14ac6
22.825397
79
0.577615
4.56231
false
false
false
false
KYawn/myiOS
Login/Login/ViewController.swift
1
1803
// // ViewController.swift // Login // // Created by K.Yawn Xoan on 3/15/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var phoneNum: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var result: UILabel! @IBOutlet weak var textField: UITextView! @IBAction func loginBtnClicked(sender: UIButton) { var req = NSMutableURLRequest(URL: NSURL(string: "http://www.azfs.com.cn/Login/ioscheck.php")!) req.HTTPMethod = "POST" req.HTTPBody = NSString(string: "username=\(phoneNum.text)&password=\(password.text)").dataUsingEncoding(NSUTF8StringEncoding) NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue()) { (resq:NSURLResponse!, data:NSData!, error:NSError!) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in if let d = data { var result = NSString(data: d, encoding: NSUTF8StringEncoding) if (result == "success"){ UIAlertView(title: "Success!", message: "Login Successed!", delegate: self, cancelButtonTitle: "Close").show() }else{ UIAlertView(title: "Failed!", message: "Login Failed!", delegate: self, cancelButtonTitle: "Close").show() } } }) } } 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. } }
apache-2.0
a13ed5349dc654b6e6e4a12f0d9ce844
33.673077
144
0.597892
4.795213
false
false
false
false
sachinvas/Swifter
Source/Extensions/UI/UITextFieldExtensions.swift
2
1800
// // UITextFieldExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import UIKit // MARK: - Properties public extension UITextField { /// SwifterSwift: Check if text field is empty. public var isEmpty: Bool { if let text = self.text { return text.characters.isEmpty } return true } /// SwifterSwift: Return text with no spaces or new lines in beginning and end. public var trimmedText: String? { return text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } @IBInspectable /// SwifterSwift: Left view tint color. public var leftViewTintColor: UIColor? { get { guard let iconView = self.leftView as? UIImageView else { return nil } return iconView.tintColor } set { guard let iconView = self.leftView as? UIImageView else { return } iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = newValue } } @IBInspectable /// SwifterSwift: Right view tint color. public var rightViewTintColor: UIColor? { get { guard let iconView = self.rightView as? UIImageView else { return nil } return iconView.tintColor } set { guard let iconView = self.rightView as? UIImageView else { return } iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate) iconView.tintColor = newValue } } } // MARK: - Methods public extension UITextField { /// SwifterSwift: Set placeholder text color. /// /// - Parameter color: placeholder text color. public func setPlaceHolderTextColor(_ color: UIColor) { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: color]) } }
mit
929ed55c47680b2727e2b1ee946ae37e
22.671053
158
0.710395
3.962555
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Models/Artist.swift
2
632
import Foundation import SwiftyJSON final class Artist: NSObject, JSONAbleType { let id: String dynamic var name: String let sortableID: String? var blurb: String? init(id: String, name: String, sortableID: String?) { self.id = id self.name = name self.sortableID = sortableID } static func fromJSON(_ json: [String: Any]) -> Artist { let json = JSON(json) let id = json["id"].stringValue let name = json["name"].stringValue let sortableID = json["sortable_id"].string return Artist(id: id, name:name, sortableID:sortableID) } }
mit
3c404dc56fe6de035f29c54e728a1b9e
22.407407
63
0.618671
4.051282
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKScripting/util/NKArchive/NKArchive.swift
1
5868
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * Portions Copyright (c) 2015 lazyapps. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public class NKArchive { var path: String var _cdirs: [String: NKAR_CentralDirectory] init(path: String, _cdirs: [String: NKAR_CentralDirectory]) { self.path = path self._cdirs = _cdirs } static func createFromPath(path: String) -> (NKArchive, NSData)? { guard let data = NSFileManager.defaultManager().contentsAtPath(path) else { return nil } let bytes = unsafeBitCast(data.bytes, UnsafePointer<UInt8>.self) let len = data.length guard let _endrec = NKAR_EndRecord.findEndRecordInBytes(bytes, length: len) else { return nil } guard let _cdirs = NKAR_CentralDirectory.findCentralDirectoriesInBytes(bytes, length: len, withEndRecord: _endrec) else { return nil } return (NKArchive(path: path, _cdirs: _cdirs), data) } } public extension NKArchive { private func getDirectory_(filename: String) -> NKAR_CentralDirectory? { let cdir = _cdirs[filename] if (cdir != nil) { return cdir } if !filename.hasPrefix("*") { return nil } let filename = (filename as NSString).substringFromIndex(1) let depth = (filename as NSString).pathComponents.count guard let item = self.files.filter({(item: String) -> Bool in return item.lowercaseString.hasSuffix(filename.lowercaseString) && ((item as NSString).pathComponents.count == depth) }).first else { return nil } return self._cdirs[item] } func dataForFile(filename: String) -> NSData? { guard let _cdir = self.getDirectory_(filename) else { return nil } guard let file: NSFileHandle = NSFileHandle(forReadingAtPath: self.path) else { return nil } file.seekToFileOffset(UInt64(_cdir.dataOffset)) let data = file.readDataOfLength(Int(_cdir.compressedSize)) file.closeFile() let bytes = unsafeBitCast(data.bytes, UnsafePointer<UInt8>.self) return NKAR_Uncompressor.uncompressWithFileBytes(_cdir, fromBytes: bytes) } func dataForFileWithArchiveData(filename: String, data: NSData) -> NSData? { guard let _cdir = self.getDirectory_(filename) else { return nil } return NKAR_Uncompressor.uncompressWithArchiveData(_cdir, data: data) } func exists(filename: String) -> Bool { if (self.getDirectory_(filename) != nil) {return true} else { return false } } var files: [String] { return Array(self._cdirs.keys) } func containsFile(file: String) -> Bool { return self.getDirectory_(file) != nil } func containsFolder(module: String) -> Bool { var folder = module if !folder.hasSuffix("/") { folder += "/" } return self.getDirectory_(folder) != nil } func stat(filename: String) -> Dictionary<String, AnyObject> { var storageItem = Dictionary<String, NSObject>() guard let cdir = self.getDirectory_(filename) ?? self.getDirectory_(filename + "/") else { return storageItem } storageItem["birthtime"] = NSDate(timeIntervalSince1970: Double(cdir.lastmodUnixTimestamp)) storageItem["size"] = NSNumber(unsignedInt: cdir.uncompressedSize) storageItem["mtime"] = storageItem["birthtime"] storageItem["path"] = (self.path as NSString).stringByAppendingPathComponent(filename) storageItem["filetype"] = cdir.fileName.hasSuffix("/") ? "Directory" : "File" return storageItem } func getDirectory(foldername: String) -> [String] { var foldername = foldername; if (foldername.characters.last != "/") { foldername = foldername + "/"; } let depth = (foldername as NSString).pathComponents.count + 1 let items = self.files.filter({(item: String) -> Bool in return item.lowercaseString.hasPrefix(foldername.lowercaseString) && ((item as NSString).pathComponents.count == depth) && (item.characters.last == "/") }) return items.map({(item: String) -> String in return (item as NSString).lastPathComponent }) } } public extension NKArchive { subscript(file: String) -> NSData? { return dataForFile(file) } subscript(file: String, withArchiveData data: NSData) -> NSData? { return dataForFileWithArchiveData(file, data: data) } }
apache-2.0
f138e5577299724d990b590da1b0bfda
28.054455
122
0.575835
5.002558
false
false
false
false
jariz/Noti
Noti/StatusMenuController.swift
1
3147
// // StatusMenuController.swift // Noti // // Created by Jari on 23/06/16. // Copyright © 2016 Jari Zwarts. All rights reserved. // import Foundation import Cocoa import ImageIO class StatusMenuController: NSObject, NSUserNotificationCenterDelegate { let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) @IBOutlet weak var menu: NSMenu! @IBOutlet weak var menuItem: NSMenuItem! var appDelegate: AppDelegate?; override func awakeFromNib() { print("StatusMenuController alive") appDelegate = NSApplication.shared.delegate as? AppDelegate if let button = statusItem.button { button.image = NSImage(named: NSImage.Name(rawValue: "StatusBarButtonImageFail")) statusItem.menu = menu; button.appearsDisabled = true } menuItem.isEnabled = true NotificationCenter.default.addObserver(self, selector: #selector(StatusMenuController.stateChange(_:)), name:NSNotification.Name(rawValue: "StateChange"), object: nil) } @objc func stateChange(_ notification: Notification) { if let info = notification.object as? [String: AnyObject] { if let title = info["title"] as? String { menuItem.title = title } if let disabled = info["disabled"] as? Bool { statusItem.button?.image = NSImage(named: NSImage.Name(rawValue: disabled ? "StatusBarButtonImageFail" : "StatusBarButtonImage")) statusItem.button?.appearsDisabled = disabled } if let image = info["image"] as? NSImage { let destSize = NSMakeSize(CGFloat(20), CGFloat(20)), newImage = NSImage(size: destSize) newImage.lockFocus() image.draw(in: NSMakeRect(0, 0, destSize.width, destSize.height), from: NSMakeRect(0, 0, image.size.width, image.size.height), operation: NSCompositingOperation.sourceOver, fraction: CGFloat(1)) newImage.unlockFocus() newImage.size = destSize let finalImage = NSImage(data: newImage.tiffRepresentation!)! menuItem.image = finalImage } else { menuItem.image = nil } } } @IBAction func reauthorize(_ sender: AnyObject?) { let alert = NSAlert() alert.messageText = "Are you sure?" alert.informativeText = "This will remove all asocciated PushBullet account information from Noti." alert.addButton(withTitle: "Yes") alert.addButton(withTitle: "No") if(alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn) { //delete token & restart push manager appDelegate!.userDefaults.removeObject(forKey: "token") appDelegate!.loadPushManager() } } @IBAction func preferences(_ sender: AnyObject?) { appDelegate!.displayPreferencesWindow() } @IBAction func quit(_ sender: AnyObject?) { NSApplication.shared.terminate(self) } }
mit
6ed8db630d2ce4f7786bcce2c5e33be5
38.325
210
0.625238
5.140523
false
false
false
false
PabloAlejandro/Transitions
TransitionsTests/GenericTransitionTests.swift
1
2681
// // GenericTransition.swift // TransitionTests // // Created by Pau on 24/02/2017. // Copyright © 2017 pau-ios-developer. All rights reserved. // import XCTest @testable import Transitions class GenericTransitionTests: XCTestCase { weak var transition: GenericTransition? 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 testViewController() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let viewController: UIViewController = UIViewController() let properties = TransitionProperties(duration: 0.5, modalPresentationStyle: .overFullScreen) let configuration = TransitionConfiguration.noninteractive(transitionProperties: properties) autoreleasepool { let strongTransition = GenericTransition(withViewController: viewController, configuration: configuration) transition = strongTransition XCTAssertNotNil(transition, "transition must be retained") } XCTAssertNil(transition, "transition must be released") } func testWeakViewController() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. weak var viewController: UIViewController? var strongTransition: GenericTransition! autoreleasepool { let strongVC = UIViewController() viewController = strongVC XCTAssertNotNil(viewController, "viewController must be retained") let properties = TransitionProperties(duration: 0.5, modalPresentationStyle: .overFullScreen) let configuration = TransitionConfiguration.noninteractive(transitionProperties: properties) strongTransition = GenericTransition(withViewController: viewController!, configuration: configuration) } XCTAssertNil(viewController, "viewController must be released") XCTAssertNotNil(strongTransition, "strongTransition must be retained") } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
771cb3362ae3c9ad93f4ecc9313efd25
37.285714
118
0.676119
5.851528
false
true
false
false
iCodeForever/ifanr
ifanr/ifanr/Models/MindStoreModel/MindStoreModel.swift
1
5734
// // MindStoreModel.swift // ifanr // // Created by sys on 16/7/9. // Copyright © 2016年 ifanrOrg. All rights reserved. // import Foundation struct CreatedByModel { var avatar_url: String! var company: String! var email: String! var id: String! var lime_home_url: String! var nickname: String! var position: String! var wechat_screenname: String! } struct RelatedImageModel { var link: String! var resource_uri: String! var title: String! } struct MindStoreModel: Initable { var id: Int64! var comment_count: String! var comment_order: String! var created_at: String! var is_auto_refresh: String! var is_producer: String! var link: String! var priority: String! var producer_participated: String! var resource_uri: String! var share_count: String! var tagline: String! var title: String! var vote_count: NSNumber! var vote_user_count: NSNumber! var voted: Int64! var createdByModel: CreatedByModel! = CreatedByModel() var relatedImageModelArr: [RelatedImageModel] = Array() init(dict: NSDictionary) { self.id = dict["id"] as? Int64 ?? 0 self.comment_count = dict["comment_count"] as? String ?? "" self.comment_order = dict["comment_order"] as? String ?? "" self.created_at = dict["created_at"] as? String ?? "" self.is_auto_refresh = dict["is_auto_refresh"] as? String ?? "" self.is_producer = dict["is_producer"] as? String ?? "" self.link = dict["link"] as? String ?? "" self.priority = dict["priority"] as? String ?? "" self.producer_participated = dict["producer_participated"] as? String ?? "" self.resource_uri = dict["resource_uri"] as? String ?? "" self.share_count = dict["share_count"] as? String ?? "" self.tagline = dict["tagline"] as? String ?? "" self.title = dict["title"] as? String ?? "" self.vote_count = dict["vote_count"] as? NSNumber ?? 0 self.vote_user_count = dict["vote_user_count"] as? NSNumber ?? 0 self.voted = dict["voted"] as? Int64 ?? 0 if let createByDic = dict["created_by"] as? NSDictionary { self.createdByModel.avatar_url = createByDic["avatar_url"] as? String ?? "" self.createdByModel.company = createByDic["company"] as? String ?? "" self.createdByModel.email = createByDic["email"] as? String ?? "" self.createdByModel.id = createByDic["id"] as? String ?? "" self.createdByModel.lime_home_url = createByDic["lime_home_url"] as? String ?? "" self.createdByModel.nickname = createByDic["nickname"] as? String ?? "" self.createdByModel.position = createByDic["position"] as? String ?? "" self.createdByModel.wechat_screenname = createByDic["wechat_screenname"] as? String ?? "" } if let tmp = dict["related_image"] { for item in (tmp as? NSArray)! { if let itemDic: NSDictionary = item as? NSDictionary { var model: RelatedImageModel = RelatedImageModel() model.link = itemDic["link"] as! String model.title = itemDic["title"] as! String model.resource_uri = itemDic["resource_uri"] as! String self.relatedImageModelArr.append(model) } } } // var model: RelatedImageModel = RelatedImageModel() // model.link = "http://media.ifanrusercontent.com/media/user_files/lime/fc/0f/fc0f1fa3b6eb1b3f8e6c2e2666415e1acaea6387-137691a83047904eca6b05d23d91cda63702b847.jpg" // self.relatedImageModelArr.append(model) // var model1: RelatedImageModel = RelatedImageModel() // model1.link = "http://media.ifanrusercontent.com/media/user_files/lime/fc/0f/fc0f1fa3b6eb1b3f8e6c2e2666415e1acaea6387-137691a83047904eca6b05d23d91cda63702b847.jpg" // self.relatedImageModelArr.append(model1) } } /* { comment_count: 0, comment_order: 0, created_at: 1467943090, created_by: { avatar_url: "http://media.ifanrusercontent.com/media/user_files/lime/avatar/rBACFFWY2lTQ5UnvAAAUiTklo1Y344_200x200_3.jpg", company: "骞垮憡", email: "[email protected]", id: 21144821, lime_home_url: "/lime/user/home/21144821/", nickname: "John", position: "AE", userprofile: { weibo_uid: "-40" }, wechat_screenname: null }, id: 12287, is_auto_refresh: 0, is_producer: false, link: "https://itunes.apple.com/cn/app/microsoft-sprightly-instantly/id1114875964?mt=8&amp;utm_source=mindstore.io", priority: 1, producer_participated: false, related_image: [ { link: "http://media.ifanrusercontent.com/media/user_files/lime/fc/0f/fc0f1fa3b6eb1b3f8e6c2e2666415e1acaea6387-137691a83047904eca6b05d23d91cda63702b847.jpg", resource_uri: "", title: "" }, { link: "http://media.ifanrusercontent.com/media/user_files/lime/1e/71/1e71f8cc20f68bdd1f3ec2a2b4b5042ec4d5e078-f8bb11291d7a63e4c4c2ec6d9e65737c0a1cbf92.jpg", resource_uri: "", title: "" } ], related_link: [ ], resource_uri: "/api/v1.2/mind/12287/", share_count: 0, tagline: "涓轰釜浜烘垨灏忓晢瀹跺畾鍒惰彍鍗曘€佷紭鎯犲埜浠ュ強鐢靛瓙鍗$墖鐨勭簿缇庢帓鐗堣蒋浠躲€�", tags: [ ], title: "Microsoft Sprightly #iOS ", vote_count: 27, vote_user_count: 15, voted: false }, */
mit
d78c2a50d16742ab06ae895b0e9e4874
37.333333
173
0.610293
3.324484
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Classes/Mpn/MpnManager.swift
2
2545
// // MpnManager.swift // byuSuite // // Created by Eric Romrell on 4/26/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let OBSERVER_KEY = "ByuMpn" class MpnManager: NSObject, ByuCredentialManagerObserver { var device: Device @objc init(token: String) { device = Device(token: token) //This line tells the compiler that we are done initializing. This will allow us to pass self and use self.<function> in this method super.init() //Register as an observer. This will let us know when login/logouts will occur ByuCredentialManager.addObserver(forKey: OBSERVER_KEY, observer: self) //Check to see if we missed the loginSucceeded request (due to latency of receiving our token). If so, manually call login succeeded if let personSummary = ByuCredentialManager.cachedPersonSummary { self.loginSucceeded(personSummary: personSummary) } } deinit { ByuCredentialManager.removeObserver(forKey: OBSERVER_KEY) } //MARK: ByuCredentialManagerObserver callbacks func loginSucceeded(personSummary: PersonSummary?) { if let personSummary = personSummary { self.device.personId = personSummary.personId self.saveDevice() } else { print("MPN Person Summary Error") } } func loginFailed(error: ByuError?) { print("MPN Login Error") } func willLogout() { //We need to unregister now while we still have the token (rather than in the logoutSucceeded method) if let id = device.databaseId { MpnClient.unregisterDevice(databaseId: id, callback: { (device, error) in if let device = device { print("MPN DELETE \(device)") self.device = device self.device.saveDataToUserDefaults() } else { print("MPN DELETE error") } }) } } func logoutSucceeded() { //Do nothing. Just needed for non-optional swift protocol } private func saveDevice() { //Check to see if we should be inserting or updating (or do nothing if nothing has changed) if device.databaseId == nil { MpnClient.createDevice(device, callback: { (device, error) in if let device = device { print("MPN POST \(device)") self.device = device self.device.saveDataToUserDefaults() } else { print("MPN POST error") } }) } else if device.hasChanged() { MpnClient.updateDevice(device, callback: { (device, error) in if let device = device { print("MPN PUT \(device)") self.device = device self.device.saveDataToUserDefaults() } else { print("MPN PUT error") } }) } } }
apache-2.0
eaddf7cd2e2b0f355a2d89b3ee5c4791
26.956044
134
0.693789
3.655172
false
false
false
false
cburrows/swift-protobuf
Tests/SwiftProtobufTests/Test_Any.swift
1
40713
// Tests/SwiftProtobufTests/Test_Any.swift - Verify well-known Any type // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Any is tricky. Some of the more interesting cases: /// * Transcoding protobuf to/from JSON with or without the schema being known /// * Any fields that contain well-known or user-defined types /// * Any fields that contain Any fields /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf class Test_Any: XCTestCase { func test_Any() throws { var content = ProtobufUnittest_TestAllTypes() content.optionalInt32 = 7 var m = ProtobufUnittest_TestAny() m.int32Value = 12 m.anyValue = try Google_Protobuf_Any(message: content) // The Any holding an object can be JSON serialized XCTAssertNotNil(try m.jsonString()) let encoded = try m.serializedBytes() XCTAssertEqual(encoded, [8, 12, 18, 56, 10, 50, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 112, 114, 111, 116, 111, 98, 117, 102, 95, 117, 110, 105, 116, 116, 101, 115, 116, 46, 84, 101, 115, 116, 65, 108, 108, 84, 121, 112, 101, 115, 18, 2, 8, 7]) let decoded = try ProtobufUnittest_TestAny(serializedBytes: encoded) XCTAssertEqual(decoded.anyValue.typeURL, "type.googleapis.com/protobuf_unittest.TestAllTypes") XCTAssertEqual(decoded.anyValue.value, Data([8, 7])) XCTAssertEqual(decoded.int32Value, 12) XCTAssertNotNil(decoded.anyValue) let any = decoded.anyValue do { let extracted = try ProtobufUnittest_TestAllTypes(unpackingAny: any) XCTAssertEqual(extracted.optionalInt32, 7) } catch { XCTFail("Failed to unpack \(any)") } XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(unpackingAny: any)) let recoded = try decoded.serializedBytes() XCTAssertEqual(encoded, recoded) } /// The typeURL prefix should be ignored for purposes of determining the actual type. /// The prefix is only used for dynamically loading type data from a remote server /// (There are currently no such servers, and no plans to build any.) /// /// This test verifies that we can decode an Any with a different prefix func test_Any_different_prefix() throws { let encoded = Data([8, 12, 18, 40, 10, 34, 88, 47, 89, 47, 112, 114, 111, 116, 111, 98, 117, 102, 95, 117, 110, 105, 116, 116, 101, 115, 116, 46, 84, 101, 115, 116, 65, 108, 108, 84, 121, 112, 101, 115, 18, 2, 8, 7]) let decoded: ProtobufUnittest_TestAny do { decoded = try ProtobufUnittest_TestAny(serializedData: encoded) } catch { XCTFail("Failed to decode \(encoded): \(error)") return } XCTAssertEqual(decoded.anyValue.typeURL, "X/Y/protobuf_unittest.TestAllTypes") XCTAssertEqual(decoded.anyValue.value, Data([8, 7])) XCTAssertEqual(decoded.int32Value, 12) XCTAssertNotNil(decoded.anyValue) let any = decoded.anyValue do { let extracted = try ProtobufUnittest_TestAllTypes(unpackingAny: any) XCTAssertEqual(extracted.optionalInt32, 7) } catch { XCTFail("Failed to unpack \(any)") } XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(unpackingAny: any)) let recoded = try decoded.serializedData() XCTAssertEqual(encoded, recoded) } /// The typeURL prefix should be ignored for purposes of determining the actual type. /// The prefix is only used for dynamically loading type data from a remote server /// (There are currently no such servers, and no plans to build any.) /// /// This test verifies that we can decode an Any with an empty prefix func test_Any_noprefix() throws { let encoded = Data([8, 12, 18, 37, 10, 31, 47, 112, 114, 111, 116, 111, 98, 117, 102, 95, 117, 110, 105, 116, 116, 101, 115, 116, 46, 84, 101, 115, 116, 65, 108, 108, 84, 121, 112, 101, 115, 18, 2, 8, 7]) let decoded: ProtobufUnittest_TestAny do { decoded = try ProtobufUnittest_TestAny(serializedData: encoded) } catch { XCTFail("Failed to decode \(encoded): \(error)") return } XCTAssertEqual(decoded.anyValue.typeURL, "/protobuf_unittest.TestAllTypes") XCTAssertEqual(decoded.anyValue.value, Data([8, 7])) XCTAssertEqual(decoded.int32Value, 12) XCTAssertNotNil(decoded.anyValue) let any = decoded.anyValue do { let extracted = try ProtobufUnittest_TestAllTypes(unpackingAny: any) XCTAssertEqual(extracted.optionalInt32, 7) } catch { XCTFail("Failed to unpack \(any)") } XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(unpackingAny: any)) let recoded = try decoded.serializedData() XCTAssertEqual(encoded, recoded) } /// Though Google discourages this, we should be able to match and decode an Any /// if the typeURL holds just the type name: func test_Any_shortesttype() throws { let encoded = Data([8, 12, 18, 36, 10, 30, 112, 114, 111, 116, 111, 98, 117, 102, 95, 117, 110, 105, 116, 116, 101, 115, 116, 46, 84, 101, 115, 116, 65, 108, 108, 84, 121, 112, 101, 115, 18, 2, 8, 7]) let decoded: ProtobufUnittest_TestAny do { decoded = try ProtobufUnittest_TestAny(serializedData: encoded) } catch { XCTFail("Failed to decode \(encoded): \(error)") return } XCTAssertEqual(decoded.anyValue.typeURL, "protobuf_unittest.TestAllTypes") XCTAssertEqual(decoded.anyValue.value, Data([8, 7])) XCTAssertEqual(decoded.int32Value, 12) XCTAssertNotNil(decoded.anyValue) let any = decoded.anyValue do { let extracted = try ProtobufUnittest_TestAllTypes(unpackingAny: any) XCTAssertEqual(extracted.optionalInt32, 7) } catch { XCTFail("Failed to unpack \(any)") } XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(unpackingAny: any)) let recoded = try decoded.serializedData() XCTAssertEqual(encoded, recoded) } func test_Any_UserMessage() throws { Google_Protobuf_Any.register(messageType: ProtobufUnittest_TestAllTypes.self) var content = ProtobufUnittest_TestAllTypes() content.optionalInt32 = 7 var m = ProtobufUnittest_TestAny() m.int32Value = 12 m.anyValue = try Google_Protobuf_Any(message: content) let encoded = try m.jsonString() XCTAssertEqual(encoded, "{\"int32Value\":12,\"anyValue\":{\"@type\":\"type.googleapis.com/protobuf_unittest.TestAllTypes\",\"optionalInt32\":7}}") do { let decoded = try ProtobufUnittest_TestAny(jsonString: encoded) XCTAssertNotNil(decoded.anyValue) XCTAssertEqual(Data([8, 7]), decoded.anyValue.value) XCTAssertEqual(decoded.int32Value, 12) XCTAssertNotNil(decoded.anyValue) let any = decoded.anyValue do { let extracted = try ProtobufUnittest_TestAllTypes(unpackingAny: any) XCTAssertEqual(extracted.optionalInt32, 7) XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(unpackingAny: any)) } catch { XCTFail("Failed to unpack \(any)") } let recoded = try decoded.jsonString() XCTAssertEqual(encoded, recoded) XCTAssertEqual([8, 12, 18, 56, 10, 50, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 112, 114, 111, 116, 111, 98, 117, 102, 95, 117, 110, 105, 116, 116, 101, 115, 116, 46, 84, 101, 115, 116, 65, 108, 108, 84, 121, 112, 101, 115, 18, 2, 8, 7], try decoded.serializedBytes()) } catch { XCTFail("Failed to decode \(encoded)") } } func test_Any_UnknownUserMessage_JSON() throws { Google_Protobuf_Any.register(messageType: ProtobufUnittest_TestAllTypes.self) let start = "{\"int32Value\":12,\"anyValue\":{\"@type\":\"type.googleapis.com/UNKNOWN\",\"optionalInt32\":7}}" let decoded = try ProtobufUnittest_TestAny(jsonString: start) // JSON-to-JSON transcoding succeeds let recoded = try decoded.jsonString() XCTAssertEqual(recoded, start) let anyValue = decoded.anyValue XCTAssertNotNil(anyValue) XCTAssertEqual(anyValue.typeURL, "type.googleapis.com/UNKNOWN") XCTAssertEqual(anyValue.value, Data()) XCTAssertEqual(anyValue.textFormatString(), "type_url: \"type.googleapis.com/UNKNOWN\"\n#json: \"{\\\"optionalInt32\\\":7}\"\n") // Verify: JSON-to-protobuf transcoding should fail here // since the Any does not have type information XCTAssertThrowsError(try decoded.serializedBytes()) } func test_Any_UnknownUserMessage_protobuf() throws { Google_Protobuf_Any.register(messageType: ProtobufUnittest_TestAllTypes.self) let start = Data([8, 12, 18, 33, 10, 27, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 85, 78, 75, 78, 79, 87, 78, 18, 2, 8, 7]) let decoded = try ProtobufUnittest_TestAny(serializedData: start) // Protobuf-to-protobuf transcoding succeeds let recoded = try decoded.serializedData() XCTAssertEqual(recoded, start) let anyValue = decoded.anyValue XCTAssertNotNil(anyValue) XCTAssertEqual(anyValue.typeURL, "type.googleapis.com/UNKNOWN") XCTAssertEqual(anyValue.value, Data([8, 7])) XCTAssertEqual(anyValue.textFormatString(), "type_url: \"type.googleapis.com/UNKNOWN\"\nvalue: \"\\b\\007\"\n") // Protobuf-to-JSON transcoding fails XCTAssertThrowsError(try decoded.jsonString()) } func test_Any_Any() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Any\",\"value\":{\"@type\":\"type.googleapis.com/google.protobuf.Int32Value\",\"value\":1}}}" let decoded: ProtobufTestMessages_Proto3_TestAllTypesProto3 do { decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) } catch { XCTFail("Failed to decode \(start)") return } XCTAssertNotNil(decoded.optionalAny) let outerAny = decoded.optionalAny do { let innerAny = try Google_Protobuf_Any(unpackingAny: outerAny) do { let value = try Google_Protobuf_Int32Value(unpackingAny: innerAny) XCTAssertEqual(value.value, 1) } catch { XCTFail("Failed to decode innerAny") return } } catch { XCTFail("Failed to unpack outerAny \(outerAny): \(error)") return } let protobuf: Data do { protobuf = try decoded.serializedData() } catch { XCTFail("Failed to serialize \(decoded)") return } XCTAssertEqual(protobuf, Data([138, 19, 95, 10, 39, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 65, 110, 121, 18, 52, 10, 46, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117, 101, 18, 2, 8, 1])) let redecoded: ProtobufTestMessages_Proto3_TestAllTypesProto3 do { redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) } catch { XCTFail("Failed to decode \(protobuf)") return } let json: String do { json = try redecoded.jsonString() } catch { XCTFail("Failed to recode \(redecoded)") return } XCTAssertEqual(json, start) do { let recoded = try decoded.jsonString() XCTAssertEqual(recoded, start) } catch { XCTFail("Failed to recode \(start)") } } func test_Any_recursive() throws { func nestedAny(_ i: Int) throws -> Google_Protobuf_Any { guard i > 0 else { return Google_Protobuf_Any() } return try Google_Protobuf_Any(message: nestedAny(i - 1)) } let any = try nestedAny(5) let encoded = try any.serializedBytes() XCTAssertEqual(encoded.count, 214) } func test_Any_Duration_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Duration\",\"value\":\"99.001s\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_Duration(unpackingAny: anyField) XCTAssertEqual(unpacked.seconds, 99) XCTAssertEqual(unpacked.nanos, 1000000) } catch { XCTFail("Failed to unpack \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_Duration_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Duration\",\"value\":\"99.001s\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 54, 10, 44, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 68, 117, 114, 97, 116, 105, 111, 110, 18, 6, 8, 99, 16, 192, 132, 61])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Failed to redecode \(protobuf): \(e)") } } catch let e { XCTFail("Failed to decode \(start): \(e)") } } func test_Any_FieldMask_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.FieldMask\",\"value\":\"foo,bar.bazQuux\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_FieldMask(unpackingAny: anyField) XCTAssertEqual(unpacked.paths, ["foo", "bar.baz_quux"]) } catch { XCTFail("Failed to unpack anyField \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_FieldMask_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.FieldMask\",\"value\":\"foo,bar.bazQuux\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 68, 10, 45, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 70, 105, 101, 108, 100, 77, 97, 115, 107, 18, 19, 10, 3, 102, 111, 111, 10, 12, 98, 97, 114, 46, 98, 97, 122, 95, 113, 117, 117, 120])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Failed to redecode \(protobuf): \(e)") } } catch let e { XCTFail("Failed to decode \(start): \(e)") } } func test_Any_Int32Value_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Int32Value\",\"value\":1}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_Int32Value(unpackingAny: anyField) XCTAssertEqual(unpacked.value, 1) } catch { XCTFail("failed to unpack \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_Int32Value_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Int32Value\",\"value\":1}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 52, 10, 46, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 73, 110, 116, 51, 50, 86, 97, 108, 117, 101, 18, 2, 8, 1])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Failed to redecode \(protobuf): \(e)") } } catch let e { XCTFail("Failed to decode \(start): \(e)") } } // TODO: Test remaining XxxValue types func test_Any_Struct_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Struct\",\"value\":{\"foo\":1}}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_Struct(unpackingAny: anyField) XCTAssertEqual(unpacked.fields["foo"], Google_Protobuf_Value(numberValue:1)) } catch { XCTFail("Failed to unpack \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_Struct_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Struct\",\"value\":{\"foo\":1.0}}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 64, 10, 42, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 83, 116, 114, 117, 99, 116, 18, 18, 10, 16, 10, 3, 102, 111, 111, 18, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Redecode failed for \(protobuf): \(e)") } } catch let e { XCTFail("Redecode failed for \(start): \(e)") } } func test_Any_Timestamp_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Timestamp\",\"value\":\"1970-01-01T00:00:01Z\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_Timestamp(unpackingAny: anyField) XCTAssertEqual(unpacked.seconds, 1) XCTAssertEqual(unpacked.nanos, 0) } catch { XCTFail("Failed to unpack \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_Timestamp_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Timestamp\",\"value\":\"1970-01-01T00:00:01.000000001Z\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 53, 10, 45, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 84, 105, 109, 101, 115, 116, 97, 109, 112, 18, 4, 8, 1, 16, 1])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Decode failed for \(start): \(e)") } } catch let e { XCTFail("Decode failed for \(start): \(e)") } } func test_Any_ListValue_JSON_roundtrip() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.ListValue\",\"value\":[\"foo\",1]}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_ListValue(unpackingAny: anyField) XCTAssertEqual(unpacked.values, [Google_Protobuf_Value(stringValue: "foo"), Google_Protobuf_Value(numberValue: 1)]) } catch { XCTFail("Failed to unpack \(anyField)") } let encoded = try decoded.jsonString() XCTAssertEqual(encoded, start) } catch { XCTFail("Failed to decode \(start)") } } func test_Any_ListValue_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.ListValue\",\"value\":[1.0,\"abc\"]}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 67, 10, 45, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 76, 105, 115, 116, 86, 97, 108, 117, 101, 18, 18, 10, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63, 10, 5, 26, 3, 97, 98, 99])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Redecode failed for \(protobuf): \(e)") } } catch let e { XCTFail("Decode failed for \(start): \(e)") } } func test_Any_Value_struct_JSON_roundtrip() throws { // Value holding a JSON Struct let start1 = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":{\"foo\":1}}}" do { let decoded1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start1) XCTAssertNotNil(decoded1.optionalAny) let anyField = decoded1.optionalAny XCTAssertThrowsError(try Google_Protobuf_Struct(unpackingAny: anyField)) do { let unpacked = try Google_Protobuf_Value(unpackingAny: anyField) XCTAssertEqual(unpacked.structValue.fields["foo"], Google_Protobuf_Value(numberValue:1)) } catch { XCTFail("failed to unpack \(anyField)") } let encoded1 = try decoded1.jsonString() XCTAssertEqual(encoded1, start1) } catch { XCTFail("Failed to decode \(start1)") } } func test_Any_Value_struct_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":{\"foo\":1.0}}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 65, 10, 41, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 86, 97, 108, 117, 101, 18, 20, 42, 18, 10, 16, 10, 3, 102, 111, 111, 18, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch let e { XCTFail("Decode failed for \(protobuf): \(e)") } } catch let e { XCTFail("Decode failed for \(start): \(e)") } } func test_Any_Value_int_JSON_roundtrip() throws { // Value holding an Int let start2 = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":1}}" do { let decoded2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start2) XCTAssertNotNil(decoded2.optionalAny) let anyField = decoded2.optionalAny XCTAssertThrowsError(try Google_Protobuf_Struct(unpackingAny: anyField)) do { let unpacked = try Google_Protobuf_Value(unpackingAny: anyField) XCTAssertEqual(unpacked.numberValue, 1) } catch { XCTFail("Failed to unpack \(anyField)") } let encoded2 = try decoded2.jsonString() XCTAssertEqual(encoded2, start2) } catch let e { XCTFail("Failed to decode \(start2): \(e)") } } func test_Any_Value_int_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":1.0}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 54, 10, 41, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 86, 97, 108, 117, 101, 18, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch { XCTFail("Redecode failed for \(protobuf)") } } catch { XCTFail("Decode failed for \(start)") } } func test_Any_Value_string_JSON_roundtrip() throws { // Value holding a String let start3 = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":\"abc\"}}" do { let decoded3 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start3) let anyField = decoded3.optionalAny XCTAssertThrowsError(try Google_Protobuf_Struct(unpackingAny: anyField)) do { let unpacked = try Google_Protobuf_Value(unpackingAny: anyField) XCTAssertEqual(unpacked.stringValue, "abc") } catch { XCTFail("Failed to unpack \(anyField)") } let encoded3 = try decoded3.jsonString() XCTAssertEqual(encoded3, start3) } catch { XCTFail("Failed to decode \(start3)") } } func test_Any_Value_string_transcode() throws { let start = "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Value\",\"value\":\"abc\"}}" do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 50, 10, 41, 116, 121, 112, 101, 46, 103, 111, 111, 103, 108, 101, 97, 112, 105, 115, 46, 99, 111, 109, 47, 103, 111, 111, 103, 108, 101, 46, 112, 114, 111, 116, 111, 98, 117, 102, 46, 86, 97, 108, 117, 101, 18, 5, 26, 3, 97, 98, 99])) do { let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let json = try redecoded.jsonString() XCTAssertEqual(json, start) } catch { XCTFail("Redecode failed for \(protobuf)") } } catch { XCTFail("Decode failed for \(start)") } } func test_Any_OddTypeURL_FromValue() throws { var msg = ProtobufTestMessages_Proto3_TestAllTypesProto3() msg.optionalAny.value = Data([0x1a, 0x03, 0x61, 0x62, 0x63]) msg.optionalAny.typeURL = "Odd\nType\" prefix/google.protobuf.Value" let newJSON = try msg.jsonString() XCTAssertEqual(newJSON, "{\"optionalAny\":{\"@type\":\"Odd\\nType\\\" prefix/google.protobuf.Value\",\"value\":\"abc\"}}") } func test_Any_OddTypeURL_FromMessage() throws { let valueMsg = Google_Protobuf_Value.with { $0.stringValue = "abc" } var msg = ProtobufTestMessages_Proto3_TestAllTypesProto3() msg.optionalAny = try Google_Protobuf_Any(message: valueMsg, typePrefix: "Odd\nPrefix\"") let newJSON = try msg.jsonString() XCTAssertEqual(newJSON, "{\"optionalAny\":{\"@type\":\"Odd\\nPrefix\\\"/google.protobuf.Value\",\"value\":\"abc\"}}") } func test_Any_JSON_Extensions() throws { var content = ProtobufUnittest_TestAllExtensions() content.ProtobufUnittest_optionalInt32Extension = 17 var msg = ProtobufUnittest_TestAny() msg.anyValue = try Google_Protobuf_Any(message: content) let json = try msg.jsonString() XCTAssertEqual(json, "{\"anyValue\":{\"@type\":\"type.googleapis.com/protobuf_unittest.TestAllExtensions\",\"[protobuf_unittest.optional_int32_extension]\":17}}") // Decode the outer message without any extension knowledge let decoded = try ProtobufUnittest_TestAny(jsonString: json) // Decoding the inner content fails without extension info XCTAssertThrowsError(try ProtobufUnittest_TestAllExtensions(unpackingAny: decoded.anyValue)) // Succeeds if you do provide extension info let decodedContent = try ProtobufUnittest_TestAllExtensions(unpackingAny: decoded.anyValue, extensions: ProtobufUnittest_Unittest_Extensions) XCTAssertEqual(content, decodedContent) // Transcoding should fail without extension info XCTAssertThrowsError(try decoded.serializedData()) // Decode the outer message with extension information let decodedWithExtensions = try ProtobufUnittest_TestAny(jsonString: json, extensions: ProtobufUnittest_Unittest_Extensions) // Still fails; the Any doesn't record extensions that were in effect when the outer Any was decoded XCTAssertThrowsError(try ProtobufUnittest_TestAllExtensions(unpackingAny: decodedWithExtensions.anyValue)) let decodedWithExtensionsContent = try ProtobufUnittest_TestAllExtensions(unpackingAny: decodedWithExtensions.anyValue, extensions: ProtobufUnittest_Unittest_Extensions) XCTAssertEqual(content, decodedWithExtensionsContent) XCTAssertTrue(Google_Protobuf_Any.register(messageType: ProtobufUnittest_TestAllExtensions.self)) // Throws because the extensions can't be implicitly transcoded XCTAssertThrowsError(try decodedWithExtensions.serializedData()) } func test_Any_WKT_UnknownFields() throws { let testcases = [ // unknown field before value "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Duration\",\"fred\":1,\"value\":\"99.001s\"}}", // unknown field after value "{\"optionalAny\":{\"@type\":\"type.googleapis.com/google.protobuf.Duration\",\"value\":\"99.001s\",\"fred\":1}}", ] for json in testcases { for ignoreUnknown in [false, true] { var options = JSONDecodingOptions() options.ignoreUnknownFields = ignoreUnknown // This may appear a little odd, since Any lazy parses, this will // always succeed because the Any isn't decoded until requested. let decoded = try! ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json, options: options) XCTAssertNotNil(decoded.optionalAny) let anyField = decoded.optionalAny do { let unpacked = try Google_Protobuf_Duration(unpackingAny: anyField) XCTAssertTrue(ignoreUnknown) // Should have throw if not ignoring unknowns. XCTAssertEqual(unpacked.seconds, 99) XCTAssertEqual(unpacked.nanos, 1000000) } catch { XCTAssertTrue(!ignoreUnknown) } // The extra field should still be there. let encoded = try decoded.jsonString() XCTAssertEqual(encoded, json) } } } func test_Any_empty() throws { let start = "{\"optionalAny\":{}}" let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) let protobuf = try decoded.serializedData() XCTAssertEqual(protobuf, Data([138, 19, 0])) let redecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: protobuf) let retext = redecoded.textFormatString() XCTAssertEqual(retext, "optional_any {\n}\n") let reredecoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(textFormatString: retext) let rejson = try reredecoded.jsonString() XCTAssertEqual(rejson, start) } func test_Any_nestedList() throws { var start = "{\"optionalAny\":{\"x\":" for _ in 0...10000 { start.append("[") } XCTAssertThrowsError( // This should fail because the deeply-nested array is not closed // It should not crash from exhausting stack space try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) ) for _ in 0...10000 { start.append("]") } start.append("}}") // This should succeed because the deeply-nested array is properly closed // It should not crash from exhausting stack space and should // not fail due to recursion limits (because when skipping, those are // only applied to objects). _ = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: start) } func test_IsA() { var msg = Google_Protobuf_Any() msg.typeURL = "type.googleapis.com/protobuf_unittest.TestAllTypes" XCTAssertTrue(msg.isA(ProtobufUnittest_TestAllTypes.self)) XCTAssertFalse(msg.isA(Google_Protobuf_Empty.self)) msg.typeURL = "random.site.org/protobuf_unittest.TestAllTypes" XCTAssertTrue(msg.isA(ProtobufUnittest_TestAllTypes.self)) XCTAssertFalse(msg.isA(Google_Protobuf_Empty.self)) msg.typeURL = "/protobuf_unittest.TestAllTypes" XCTAssertTrue(msg.isA(ProtobufUnittest_TestAllTypes.self)) XCTAssertFalse(msg.isA(Google_Protobuf_Empty.self)) msg.typeURL = "protobuf_unittest.TestAllTypes" XCTAssertTrue(msg.isA(ProtobufUnittest_TestAllTypes.self)) XCTAssertFalse(msg.isA(Google_Protobuf_Empty.self)) msg.typeURL = "" XCTAssertFalse(msg.isA(ProtobufUnittest_TestAllTypes.self)) XCTAssertFalse(msg.isA(Google_Protobuf_Empty.self)) } func test_Any_Registry() { // Registering the same type multiple times is ok. XCTAssertTrue(Google_Protobuf_Any.register(messageType: ProtobufUnittestImport_ImportMessage.self)) XCTAssertTrue(Google_Protobuf_Any.register(messageType: ProtobufUnittestImport_ImportMessage.self)) // Registering a different type with the same messageName will fail. XCTAssertFalse(Google_Protobuf_Any.register(messageType: ConflictingImportMessage.self)) // Sanity check that the .proto files weren't changed, and they do have the same name. XCTAssertEqual(ConflictingImportMessage.protoMessageName, ProtobufUnittestImport_ImportMessage.protoMessageName) // Lookup XCTAssertTrue(Google_Protobuf_Any.messageType(forMessageName: ProtobufUnittestImport_ImportMessage.protoMessageName) == ProtobufUnittestImport_ImportMessage.self) XCTAssertNil(Google_Protobuf_Any.messageType(forMessageName: ProtobufUnittest_TestMap.protoMessageName)) // All the WKTs should be registered. let wkts: [Message.Type] = [ Google_Protobuf_Any.self, Google_Protobuf_BoolValue.self, Google_Protobuf_BytesValue.self, Google_Protobuf_DoubleValue.self, Google_Protobuf_Duration.self, Google_Protobuf_Empty.self, Google_Protobuf_FieldMask.self, Google_Protobuf_FloatValue.self, Google_Protobuf_Int32Value.self, Google_Protobuf_Int64Value.self, Google_Protobuf_ListValue.self, Google_Protobuf_StringValue.self, Google_Protobuf_Struct.self, Google_Protobuf_Timestamp.self, Google_Protobuf_UInt32Value.self, Google_Protobuf_UInt64Value.self, Google_Protobuf_Value.self, ] for t in wkts { XCTAssertTrue(Google_Protobuf_Any.messageType(forMessageName: t.protoMessageName) == t, "Looking up \(t.protoMessageName)") } } } // Dummy message class to test registration conflicts, this is basically the // generated code from ProtobufUnittest_TestEmptyMessage. struct ConflictingImportMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = "protobuf_unittest_import.ImportMessage" var unknownFields = SwiftProtobuf.UnknownStorage() init() {} mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static let _protobuf_nameMap: SwiftProtobuf._NameMap = SwiftProtobuf._NameMap() static func ==(lhs: ConflictingImportMessage, rhs: ConflictingImportMessage) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } #if swift(>=5.5) && canImport(_Concurrency) extension ConflictingImportMessage: @unchecked Sendable {} #endif // swift(>=5.5) && canImport(_Concurrency)
apache-2.0
55337275ae221dd8d6c0dc837837605e
46.561916
493
0.61683
4.504647
false
true
false
false
codestergit/swift
test/IRGen/enum_resilience.swift
3
12396
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s import resilient_enum import resilient_struct // CHECK: %swift.type = type { [[INT:i32|i64]] } // CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }> // CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }> // Public fixed layout struct contains a public resilient struct, // cannot use spare bits // CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }> // Public resilient struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }> // Internal fixed layout struct contains a public resilient struct, // can use spare bits // CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }> // Public fixed layout struct contains a fixed layout struct, // can use spare bits // CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }> public class Class {} public struct Reference { public var n: Class } @_fixed_layout public enum Either { case Left(Reference) case Right(Reference) } public enum ResilientEither { case Left(Reference) case Right(Reference) } enum InternalEither { case Left(Reference) case Right(Reference) } @_fixed_layout public struct ReferenceFast { public var n: Class } @_fixed_layout public enum EitherFast { case Left(ReferenceFast) case Right(ReferenceFast) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnum010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithResilientEnum(_ m: Medium) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return m } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnum010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture) public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum16IndirectApproachOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return ia } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF public func constructResilientEnumNoPayload() -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 0, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Paper } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayload010resilient_A06MediumO0G7_struct4SizeVF public func constructResilientEnumPayload(_ s: Size) -> Medium { // CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa() // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* %0, %swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8*** // CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1 // CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 25 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %0, i32 -2, %swift.type* [[METADATA2]]) // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4 // CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* %1, %swift.type* [[METADATA]]) // CHECK-NEXT: ret void return Medium.Postcard(s) } // CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestSi0c1_A06MediumOF(%swift.opaque* noalias nocapture) // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa() // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 6 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* [[ENUM_STORAGE]], %swift.opaque* %0, %swift.type* [[METADATA]]) // CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 23 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* [[ENUM_STORAGE]], %swift.type* [[METADATA]]) // CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [ // CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]] // CHECK: i32 0, label %[[PAPER_CASE:.*]] // CHECK: i32 1, label %[[CANVAS_CASE:.*]] // CHECK: ] // CHECK: ; <label>:[[PAPER_CASE]] // CHECK: br label %[[END:.*]] // CHECK: ; <label>:[[CANVAS_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[PAMPHLET_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[DEFAULT_CASE]] // CHECK: br label %[[END]] // CHECK: ; <label>:[[END]] // CHECK: ret public func resilientSwitchTest(_ m: Medium) -> Int { switch m { case .Paper: return 1 case .Canvas: return 2 case .Pamphlet(let m): return resilientSwitchTest(m) default: return 3 } } public func reabstraction<T>(_ f: (Medium) -> T) {} // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyySi0c1_A06MediumOcF(i8*, %swift.refcounted*) public func resilientEnumPartialApply(_ f: (Medium) -> Int) { // CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject // CHECK: call swiftcc void @_T015enum_resilience13reabstractionyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN) reabstraction(f) // CHECK: ret void } // CHECK-LABEL: define internal swiftcc void @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself) // Enums with resilient payloads from a different resilience domain // require runtime metadata instantiation, just like generics. public enum EnumWithResilientPayload { case OneSize(Size) case TwoSizes(Size, Size) } // Make sure we call a function to access metadata of enums with // resilient layout. // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T015enum_resilience20getResilientEnumTypeypXpyF() // CHECK: [[METADATA:%.*]] = call %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa() // CHECK-NEXT: ret %swift.type* [[METADATA]] public func getResilientEnumType() -> Any.Type { return EnumWithResilientPayload.self } // Public metadata accessor for our resilient enum // CHECK-LABEL: define{{( protected)?}} %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa() // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @_T015enum_resilience24EnumWithResilientPayloadOMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*)) // CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ] // CHECK-NEXT: ret %swift.type* [[RESULT]] // Methods inside extensions of resilient enums fish out type parameters // from metadata -- make sure we can do that extension ResilientMultiPayloadGenericEnum { // CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T014resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself) // CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type** // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 3 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] public func getTypeParameter() -> T.Type { return T.self } } // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
apache-2.0
d4e33c96d8ec1e4d688da40da428d670
45.954545
275
0.663924
3.432844
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Display dimensions/DisplayDimensionsViewController.swift
1
3708
// Copyright 2021 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class DisplayDimensionsViewController: UIViewController { // MARK: Storyboard views /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { loadMobileMapPackage() } } @IBOutlet var settingsBarButtonItem: UIBarButtonItem! // MARK: Properties /// The dimension layer. Will be `nil` until the mmpk has finished loading. var dimensionLayer: AGSDimensionLayer! // MARK: Methods /// Initiates loading of the mobile map package. func loadMobileMapPackage() { // The mobile map package used by this sample. let mobileMapPackage = AGSMobileMapPackage(fileURL: Bundle.main.url(forResource: "Edinburgh_Pylon_Dimensions", withExtension: "mmpk")!) mobileMapPackage.load { [weak self] error in guard let self = self else { return } let result: Result<AGSMap, Error> if let map = mobileMapPackage.maps.first { result = .success(map) } else if let error = error { result = .failure(error) } else { fatalError("MMPK doesn't contain a map.") } self.mobileMapPackageDidLoad(with: result) } } /// Called in response to the mobile map package load operation completing. /// - Parameter result: The result of the load operation. func mobileMapPackageDidLoad(with result: Result<AGSMap, Error>) { switch result { case .success(let map): // Set a minScale to maintain dimension readability. map.minScale = 4e4 mapView.map = map // Get the dimension layer. if let layer = map.operationalLayers.first(where: { $0 is AGSDimensionLayer }) as? AGSDimensionLayer { dimensionLayer = layer settingsBarButtonItem.isEnabled = true } case .failure(let error): presentAlert(error: error) } } // MARK: UIViewController @IBSegueAction func makeSettingsViewController(_ coder: NSCoder) -> DisplayDimensionsSettingsViewController? { let settingsViewController = DisplayDimensionsSettingsViewController( coder: coder, dimensionLayer: dimensionLayer ) settingsViewController?.modalPresentationStyle = .popover settingsViewController?.presentationController?.delegate = self return settingsViewController } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["DisplayDimensionsViewController", "DisplayDimensionsSettingsViewController"] } } extension DisplayDimensionsViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
apache-2.0
52af28fb7466fca816a5a6071663ea77
37.625
163
0.665049
5.366136
false
false
false
false
hilenium/HISwiftExtensions
Example/Tests/NSDateTests.swift
1
5875
////// ////// NSDateTests.swift ////// HISwiftExtensions ////// ////// Created by Matthew on 27/12/2015. ////// Copyright © 2015 CocoaPods. All rights reserved. ////// //// //import Quick //import Nimble //import HISwiftExtensions // //class NSDateExtensionsSpec: QuickSpec { // // override func spec() { // describe("nsdate extensions") { // // it("comparable true") { // // let date1 = NSDate() // let date2 = date1 // // expect(date1 == date2).to(equal(true)) // } // // it("comparable false") { // // let date1 = NSDate() // let date2 = Calendar.current.date(byAdding: .day, value: -1, toDate: NSDate()) // // expect(date1 == date2).to(equal(false)) // } // // it("add seconds") { // // let date1 = NSDate() // let date2 = Calendar.current.date(byAdding: .day, value: 1, toDate: NSDate()) // let date3 = date1.addSeconds(86400) // // expect(date2).to(equal(date3)) // } // // it("time ago - 1 second ago") { // // let date2 = Calendar.current.date(byAdding: .second, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 second ago")) // } // // it("time ago - 1 second ago (not numeric)") { // // let date2 = Calendar.current.date(byAdding: .second, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("Just now")) // } // // it("time ago - 1 minute ago") { // // let date2 = Calendar.current.date(byAdding: .minute, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 minute ago")) // } // // it("time ago - 1 minute ago (not numeric)") { // // let date2 = Calendar.current.date(byAdding: .minute, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("A minute ago")) // } // // it("time ago - X minutes ago") { // // let date2 = Calendar.current.date(byAdding: .minute, value: -5, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("5 minutes ago")) // } // // it("time ago - 1 hour ago") { // // let date2 = Calendar.current.date(byAdding: .hour, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 hour ago")) // } // // it("time ago - 1 hour ago (not numeric)") { // // let date2 = Calendar.current.date(byAdding: .hour, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("An hour ago")) // } // // it("time ago - 1 day ago") { // // let date2 = Calendar.current.date(byAdding: .day, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 day ago")) // } // // it("time ago - 1 day ago (not numeric)") { // // let date2 = Calendar.current.date(byAdding: .day, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("Yesterday")) // } // // it("time ago - 2 days ago") { // // let date2 = Calendar.current.date(byAdding: .day, value: -2, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("2 days ago")) // } // // it("time ago - 1 week ago (not numeric)") { // // let date2 = Calendar.current.date(byAdding: .day, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("Last week")) // } // // it("time ago - 1 week ago") { // // let date2 = Calendar.current.date(byAdding: .day, value: -2, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 week ago")) // } // // it("time ago - 1 month ago (numeric)") { // // let date2 = Calendar.current.date(byAdding: .month, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 month ago")) // } // // it("time ago - 1 month ago (non-numeric)") { // // let date2 = Calendar.current.date(byAdding: .month, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("Last month")) // } // // it("time ago - 1 month ago (numeric)") { // // let date2 = NSCalendar.current.date(byAdding: .year, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo()).to(equal("1 year ago")) // } // // it("time ago - 1 year ago (non-numeric)") { // // let date2 = NSCalendar.current.date(byAdding: .year, value: -1, toDate: NSDate()) // // expect(date2?.timeAgo(false)).to(equal("Last year")) // } // } // } //}
mit
19278b2de2abd4ac7b68fa3f6387f36a
36.653846
99
0.40875
3.947581
false
false
false
false
thomasvl/swift-protobuf
Sources/SwiftProtobufCore/BinaryEncodingSizeVisitor.swift
3
20558
// Sources/SwiftProtobuf/BinaryEncodingSizeVisitor.swift - Binary size calculation support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Visitor used during binary encoding that precalcuates the size of a /// serialized message. /// // ----------------------------------------------------------------------------- import Foundation /// Visitor that calculates the binary-encoded size of a message so that a /// properly sized `Data` or `UInt8` array can be pre-allocated before /// serialization. internal struct BinaryEncodingSizeVisitor: Visitor { /// Accumulates the required size of the message during traversal. var serializedSize: Int = 0 init() {} mutating func visitUnknown(bytes: Data) throws { serializedSize += bytes.count } mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize + MemoryLayout<Float>.size } mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize + MemoryLayout<Double>.size } mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws { try visitSingularInt64Field(value: Int64(value), fieldNumber: fieldNumber) } mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize + Varint.encodedSize(of: value) } mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws { try visitSingularUInt64Field(value: UInt64(value), fieldNumber: fieldNumber) } mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize + Varint.encodedSize(of: value) } mutating func visitSingularSInt32Field(value: Int32, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value)) } mutating func visitSingularSInt64Field(value: Int64, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize + Varint.encodedSize(of: ZigZag.encoded(value)) } mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize + MemoryLayout<UInt32>.size } mutating func visitSingularFixed64Field(value: UInt64, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize + MemoryLayout<UInt64>.size } mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize + MemoryLayout<Int32>.size } mutating func visitSingularSFixed64Field(value: Int64, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize + MemoryLayout<Int64>.size } mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize + 1 } mutating func visitSingularStringField(value: String, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let count = value.utf8.count serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count } mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let count = value.count serializedSize += tagSize + Varint.encodedSize(of: Int64(count)) + count } // The default impls for visitRepeated*Field would work, but by implementing // these directly, the calculation for the tag overhead can be optimized and // the fixed width fields can be simple multiplication. mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize * value.count + MemoryLayout<Float>.size * value.count } mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize * value.count + MemoryLayout<Double>.size * value.count } mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: ZigZag.encoded($1)) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: ZigZag.encoded($1)) } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize * value.count + MemoryLayout<UInt32>.size * value.count } mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize * value.count + MemoryLayout<UInt64>.size * value.count } mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed32).encodedSize serializedSize += tagSize * value.count + MemoryLayout<Int32>.size * value.count } mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .fixed64).encodedSize serializedSize += tagSize * value.count + MemoryLayout<Int64>.size * value.count } mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize * value.count + 1 * value.count } mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { let count = $1.utf8.count return $0 + Varint.encodedSize(of: Int64(count)) + count } serializedSize += tagSize * value.count + dataSize } mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { let count = $1.count return $0 + Varint.encodedSize(of: Int64(count)) + count } serializedSize += tagSize * value.count + dataSize } // Packed field handling. mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<Float>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<Double>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: ZigZag.encoded($1)) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: ZigZag.encoded($1)) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: $1) } serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<UInt32>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<UInt64>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<Int32>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count * MemoryLayout<Int64>.size serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let dataSize = value.count serializedSize += tagSize + Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize let dataSize = Varint.encodedSize(of: Int32(truncatingIfNeeded: value.rawValue)) serializedSize += dataSize } mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += value.count * tagSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: Int32(truncatingIfNeeded: $1.rawValue)) } serializedSize += dataSize } mutating func visitPackedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .varint).encodedSize serializedSize += tagSize let dataSize = value.reduce(0) { $0 + Varint.encodedSize(of: Int32(truncatingIfNeeded: $1.rawValue)) } serializedSize += Varint.encodedSize(of: Int64(dataSize)) + dataSize } mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize let messageSize = try value.serializedDataSize() serializedSize += tagSize + Varint.encodedSize(of: UInt64(messageSize)) + messageSize } mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize serializedSize += value.count * tagSize let dataSize = try value.reduce(0) { let messageSize = try $1.serializedDataSize() return $0 + Varint.encodedSize(of: UInt64(messageSize)) + messageSize } serializedSize += dataSize } mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws { // The wire format doesn't matter here because the encoded size of the // integer won't change based on the low three bits. let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .startGroup).encodedSize serializedSize += 2 * tagSize try value.traverse(visitor: &self) } mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws { assert(!value.isEmpty) let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .startGroup).encodedSize serializedSize += 2 * value.count * tagSize for v in value { try v.traverse(visitor: &self) } } mutating func visitMapField<KeyType, ValueType: MapValueType>( fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: _ProtobufMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize for (k,v) in value { var sizer = BinaryEncodingSizeVisitor() try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer) try ValueType.visitSingular(value: v, fieldNumber: 2, with: &sizer) let entrySize = sizer.serializedSize serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize } serializedSize += value.count * tagSize } mutating func visitMapField<KeyType, ValueType>( fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: _ProtobufEnumMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws where ValueType.RawValue == Int { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize for (k,v) in value { var sizer = BinaryEncodingSizeVisitor() try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer) try sizer.visitSingularEnumField(value: v, fieldNumber: 2) let entrySize = sizer.serializedSize serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize } serializedSize += value.count * tagSize } mutating func visitMapField<KeyType, ValueType>( fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: _ProtobufMessageMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws { let tagSize = FieldTag(fieldNumber: fieldNumber, wireFormat: .lengthDelimited).encodedSize for (k,v) in value { var sizer = BinaryEncodingSizeVisitor() try KeyType.visitSingular(value: k, fieldNumber: 1, with: &sizer) try sizer.visitSingularMessageField(value: v, fieldNumber: 2) let entrySize = sizer.serializedSize serializedSize += Varint.encodedSize(of: Int64(entrySize)) + entrySize } serializedSize += value.count * tagSize } mutating func visitExtensionFieldsAsMessageSet( fields: ExtensionFieldValueSet, start: Int, end: Int ) throws { var sizer = BinaryEncodingMessageSetSizeVisitor() try fields.traverse(visitor: &sizer, start: start, end: end) serializedSize += sizer.serializedSize } } extension BinaryEncodingSizeVisitor { // Helper Visitor to compute the sizes when writing out the extensions as MessageSets. internal struct BinaryEncodingMessageSetSizeVisitor: SelectiveVisitor { var serializedSize: Int = 0 init() {} mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws { var groupSize = WireFormat.MessageSet.itemTagsEncodedSize groupSize += Varint.encodedSize(of: Int32(fieldNumber)) let messageSize = try value.serializedDataSize() groupSize += Varint.encodedSize(of: UInt64(messageSize)) + messageSize serializedSize += groupSize } // SelectiveVisitor handles the rest. } }
apache-2.0
961bca38ef2d47ffd63370b51f493761
42.463002
94
0.706538
4.724891
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/Common/Services/CategoriesProvider/CategoriesProviderImpl.swift
1
2292
import Foundation final class CategoriesProviderImpl: CategoriesProvider { // MARK: - CategoriesProvider func topCategory() -> Category { return Category( title: "categories.selectCategory".localized, id: "-1", subcategories: self.allCategories() ) } func categoryForId(_ categoryId: CategoryId) -> Category { let allCategories = self.allCategoryDictionaries() return categoryForId(categoryId, inCategories: allCategories)! } // MARK: - Private private func allCategories() -> [Category] { let allCategories = self.allCategoryDictionaries() return allCategories.map { category(categoryDictionary: $0) } } private func allCategoryDictionaries() -> [[String: AnyObject]] { let path = Bundle.main.path(forResource: "Categories", ofType: "plist") return NSArray(contentsOfFile: path!) as! [[String: AnyObject]] } private func categoryForId(_ categoryId: String, inCategories categoryDictionaries: [[String: AnyObject]]) -> Category? { for categoryDictionary in categoryDictionaries { if let id = categoryDictionary["id"] as? CategoryId, id == categoryId { return category(categoryDictionary: categoryDictionary) } if let subCategoryDictionaries = categoryDictionary["subcategories"] as? [[String: AnyObject]] { if let result = categoryForId(categoryId, inCategories: subCategoryDictionaries) { return result } } } return nil } private func category(categoryDictionary: [String: AnyObject]) -> Category { return Category( title: categoryDictionary["title"] as! String, id: categoryDictionary["id"] as! CategoryId, subcategories: subcategories(categoryDictionaries: categoryDictionary["subcategories"] as? [[String: AnyObject]]) ) } private func subcategories(categoryDictionaries: [[String: AnyObject]]?) -> [Category]? { if let categoryDictionaries = categoryDictionaries { return categoryDictionaries.map { category(categoryDictionary: $0) } } return nil } }
mit
851eb11ce25f3ccbf8acf6dbfe56f047
38.517241
125
0.629581
5.590244
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/Pods/ObjectMapper/Sources/Operators.swift
25
10306
// // Operators.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // 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. /** * This file defines a new operator which is used to create a mapping between an object and a JSON key value. * There is an overloaded operator definition for each type of object that is supported in ObjectMapper. * This provides a way to add custom logic to handle specific types of objects */ /// Operator used for defining mappings to and from JSON infix operator <- /// Operator used to define mappings to JSON infix operator >>> // MARK:- Objects with Basic types /// Object of Basic type public func <- <T>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.basicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } public func >>> <T>(left: T, right: Map) { if right.mappingType == .toJSON { ToJSON.basicType(left, map: right) } } /// Optional object of basic type public func <- <T>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalBasicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } public func >>> <T>(left: T?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalBasicType(left, map: right) } } /// Implicitly unwrapped optional object of basic type public func <- <T>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalBasicType(&left, object: right.value()) case .toJSON: left >>> right default: () } } // MARK:- Mappable Objects - <T: BaseMappable> /// Object conforming to Mappable public func <- <T: BaseMappable>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON: FromJSON.object(&left, map: right) case .toJSON: left >>> right } } public func >>> <T: BaseMappable>(left: T, right: Map) { if right.mappingType == .toJSON { ToJSON.object(left, map: right) } } /// Optional Mappable objects public func <- <T: BaseMappable>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObject(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: T?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObject(left, map: right) } } /// Implicitly unwrapped optional Mappable objects public func <- <T: BaseMappable>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObject(&left, map: right) case .toJSON: left >>> right default: () } } // MARK:- Dictionary of Mappable objects - Dictionary<String, T: BaseMappable> /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectDictionary(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectDictionary(left, map: right) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionary(&left, map: right) case .toJSON: left >>> right default: () } } /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectDictionaryOfArrays(left, map: right) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Dictionary<String, [T]>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectDictionaryOfArrays(left, map: right) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: BaseMappable>(left: inout Dictionary<String, [T]>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) case .toJSON: left >>> right default: () } } // MARK:- Array of Mappable objects - Array<T: BaseMappable> /// Array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectArray(left, map: right) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } // MARK:- Array of Array of Mappable objects - Array<Array<T: BaseMappable>> /// Array of Array Mappable objects public func <- <T: BaseMappable>(left: inout Array<Array<T>>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.twoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<Array<T>>, right: Map) { if right.mappingType == .toJSON { ToJSON.twoDimensionalObjectArray(left, map: right) } } /// Optional array of Mappable objects public func <- <T: BaseMappable>(left:inout Array<Array<T>>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Array<Array<T>>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalTwoDimensionalObjectArray(left, map: right) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: BaseMappable>(left: inout Array<Array<T>>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) case .toJSON: left >>> right default: () } } // MARK:- Set of Mappable objects - Set<T: BaseMappable> /// Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.objectSet(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Set<T>, right: Map) { if right.mappingType == .toJSON { ToJSON.objectSet(left, map: right) } } /// Optional Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectSet(&left, map: right) case .toJSON: left >>> right default: () } } public func >>> <T: BaseMappable>(left: Set<T>?, right: Map) { if right.mappingType == .toJSON { ToJSON.optionalObjectSet(left, map: right) } } /// Implicitly unwrapped Optional Set of Mappable objects public func <- <T: BaseMappable>(left: inout Set<T>!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: FromJSON.optionalObjectSet(&left, map: right) case .toJSON: left >>> right default: () } }
apache-2.0
3e60157cbb8982f7031b02b92169be3d
26.33687
108
0.704929
3.599721
false
false
false
false
cfraz89/RxSwift
Tests/Microoptimizations/PerformanceTools.swift
1
6227
// // PerformanceTools.swift // Tests // // Created by Krunoslav Zaher on 9/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if os(Linux) import Dispatch #endif fileprivate var mallocFunctions: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = [] fileprivate var allocCalls: Int64 = 0 fileprivate var bytesAllocated: Int64 = 0 func call0(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? { OSAtomicIncrement64Barrier(&allocCalls) OSAtomicAdd64Barrier(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[0](p, size) } func call1(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? { OSAtomicIncrement64Barrier(&allocCalls) OSAtomicAdd64Barrier(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[1](p, size) } func call2(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? { OSAtomicIncrement64Barrier(&allocCalls) OSAtomicAdd64Barrier(Int64(size), &bytesAllocated) #if ALLOC_HOOK allocation() #endif return mallocFunctions[2](p, size) } var proxies: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = [call0, call1, call2] func getMemoryInfo() -> (bytes: Int64, allocations: Int64) { return (bytesAllocated, allocCalls) } fileprivate var registeredMallocHooks = false func registerMallocHooks() { if registeredMallocHooks { return } registeredMallocHooks = true var _zones: UnsafeMutablePointer<vm_address_t>? var count: UInt32 = 0 // malloc_zone_print(nil, 1) let res = malloc_get_all_zones(mach_task_self_, nil, &_zones, &count) assert(res == 0) _zones?.withMemoryRebound(to: UnsafeMutablePointer<malloc_zone_t>.self, capacity: Int(count), { zones in assert(Int(count) <= proxies.count) for i in 0 ..< Int(count) { let zoneArray = zones.advanced(by: i) let name = malloc_get_zone_name(zoneArray.pointee) var zone = zoneArray.pointee.pointee //print(String.fromCString(name)) assert(name != nil) mallocFunctions.append(zone.malloc) zone.malloc = proxies[i] let protectSize = vm_size_t(MemoryLayout<malloc_zone_t>.size) * vm_size_t(count) if true { zoneArray.withMemoryRebound(to: vm_address_t.self, capacity: Int(protectSize), { addressPointer in let res = vm_protect(mach_task_self_, addressPointer.pointee, protectSize, 0, PROT_READ | PROT_WRITE) assert(res == 0) }) } zoneArray.pointee.pointee = zone if true { let res = vm_protect(mach_task_self_, _zones!.pointee, protectSize, 0, PROT_READ) assert(res == 0) } } }) } // MARK: Benchmark tools let NumberOfIterations = 10000 final class A { let _0 = 0 let _1 = 0 let _2 = 0 let _3 = 0 let _4 = 0 let _5 = 0 let _6 = 0 } final class B { var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29] } let numberOfObjects = 1000000 let aliveAtTheEnd = numberOfObjects / 10 fileprivate var objects: [AnyObject] = [] func fragmentMemory() { objects = [AnyObject](repeating: A(), count: aliveAtTheEnd) for _ in 0 ..< numberOfObjects { objects[Int(arc4random_uniform(UInt32(aliveAtTheEnd)))] = arc4random_uniform(2) == 0 ? A() : B() } } func approxValuePerIteration(_ total: Int) -> UInt64 { return UInt64(round(Double(total) / Double(NumberOfIterations))) } func approxValuePerIteration(_ total: UInt64) -> UInt64 { return UInt64(round(Double(total) / Double(NumberOfIterations))) } func measureTime(_ work: () -> ()) -> UInt64 { var timebaseInfo: mach_timebase_info = mach_timebase_info() let res = mach_timebase_info(&timebaseInfo) assert(res == 0) let start = mach_absolute_time() for _ in 0 ..< NumberOfIterations { work() } let timeInNano = (mach_absolute_time() - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom) return approxValuePerIteration(timeInNano) / 1000 } func measureMemoryUsage(work: () -> ()) -> (bytesAllocated: UInt64, allocations: UInt64) { let (bytes, allocations) = getMemoryInfo() for _ in 0 ..< NumberOfIterations { work() } let (bytesAfter, allocationsAfter) = getMemoryInfo() return (approxValuePerIteration(bytesAfter - bytes), approxValuePerIteration(allocationsAfter - allocations)) } fileprivate var fragmentedMemory = false func compareTwoImplementations(benchmarkTime: Bool, benchmarkMemory: Bool, first: () -> (), second: () -> ()) { if !fragmentedMemory { print("Fragmenting memory ...") fragmentMemory() print("Benchmarking ...") fragmentedMemory = true } // first warm up to keep it fair let time1: UInt64 let time2: UInt64 if benchmarkTime { first() second() time1 = measureTime(first) time2 = measureTime(second) } else { time1 = 0 time2 = 0 } let memory1: (bytesAllocated: UInt64, allocations: UInt64) let memory2: (bytesAllocated: UInt64, allocations: UInt64) if benchmarkMemory { registerMallocHooks() first() second() memory1 = measureMemoryUsage(work: first) memory2 = measureMemoryUsage(work: second) } else { memory1 = (0, 0) memory2 = (0, 0) } // this is good enough print(String(format: "#1 implementation %8d bytes %4d allocations %5d useconds", arguments: [ memory1.bytesAllocated, memory1.allocations, time1 ])) print(String(format: "#2 implementation %8d bytes %4d allocations %5d useconds", arguments: [ memory2.bytesAllocated, memory2.allocations, time2 ])) }
mit
c2606a4957acf4499c53b14c2a3ec3c4
27.171946
129
0.629296
3.867081
false
false
false
false
cao903775389/MRCBaseLibrary
MRCBaseLibrary/Classes/MRCExtension/UIButtonExtensions.swift
1
1026
// // UIButtonExtensions.swift // Pods // // Created by 逢阳曹 on 2017/5/27. // // import Foundation extension UIButton { //创建UIButton public class func createButton(_ title: String?, font: UIFont?, image: UIImage?, selectedImage: UIImage?, titleColor: UIColor?, disableTitleColor: UIColor? = UIColor(rgba: "#cccccc"), highlightedTitleColor: UIColor? = UIColor(rgba: "#FD4E4E")) -> UIButton { let button = UIButton(type: UIButtonType.custom) button.setTitle(title, for: UIControlState()) button.setTitleColor(disableTitleColor, for: UIControlState.disabled) button.setTitleColor(highlightedTitleColor, for: UIControlState.highlighted) button.setImage(image, for: UIControlState()) button.setTitleColor(titleColor, for: UIControlState()) button.setImage(selectedImage, for: UIControlState.highlighted) button.titleLabel?.font = font button.titleLabel?.textAlignment = NSTextAlignment.right; return button } }
mit
c20533a4aa531cf474641f4647f97acc
36.62963
261
0.69685
4.597285
false
false
false
false
bugitapp/bugit
bugit/PriorityTypeModel.swift
1
894
// // PriorityTypeModel.swift // bugit // // Created by Bipin Pattan on 12/3/16. // Copyright © 2016 BugIt App. All rights reserved. // import UIKit class PriorityTypeModel: NSObject { var id: Int? var name: String? var iconUrl: String? var typeDescription: String? init(dict: Dictionary<String, Any>) { if let idValue = dict["id"] as! String? { id = Int(idValue) } if let nameValue = dict["name"] as! String? { name = nameValue } if let urlValue = dict["iconUrl"] as! String? { iconUrl = urlValue } if let descValue = dict["description"] as! String? { typeDescription = descValue } } override var description: String { return "PriorityTypeModel: id: \(id) name: \(name) iconUrl: \(iconUrl) typeDesc: \(typeDescription)" } }
apache-2.0
a8e943e649a8dcd65ff4420dd4f319c5
24.514286
108
0.571109
3.986607
false
false
false
false
maxadamski/swift-corelibs-foundation
Foundation/NSPropertyList.swift
6
5349
// 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 // import CoreFoundation public struct NSPropertyListMutabilityOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } static let Immutable = NSPropertyListMutabilityOptions(rawValue: 0) static let MutableContainers = NSPropertyListMutabilityOptions(rawValue: 1) static let MutableContainersAndLeaves = NSPropertyListMutabilityOptions(rawValue: 2) } public enum NSPropertyListFormat : UInt { case OpenStepFormat = 1 case XMLFormat_v1_0 = 100 case BinaryFormat_v1_0 = 200 } #if os(OSX) || os(iOS) let kCFPropertyListOpenStepFormat = CFPropertyListFormat.OpenStepFormat let kCFPropertyListXMLFormat_v1_0 = CFPropertyListFormat.XMLFormat_v1_0 let kCFPropertyListBinaryFormat_v1_0 = CFPropertyListFormat.BinaryFormat_v1_0 #endif public typealias NSPropertyListReadOptions = NSPropertyListMutabilityOptions public typealias NSPropertyListWriteOptions = Int public class NSPropertyListSerialization : NSObject { public class func propertyList(plist: AnyObject, isValidForFormat format: NSPropertyListFormat) -> Bool { #if os(OSX) || os(iOS) let fmt = CFPropertyListFormat(rawValue: CFIndex(format.rawValue))! #else let fmt = CFPropertyListFormat(format.rawValue) #endif return CFPropertyListIsValid(unsafeBitCast(plist, CFPropertyList.self), fmt) } public class func dataWithPropertyList(plist: AnyObject, format: NSPropertyListFormat, options opt: NSPropertyListWriteOptions) throws -> NSData { var error: Unmanaged<CFError>? = nil let result = withUnsafeMutablePointer(&error) { (outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> CFData? in #if os(OSX) || os(iOS) let fmt = CFPropertyListFormat(rawValue: CFIndex(format.rawValue))! #else let fmt = CFPropertyListFormat(format.rawValue) #endif let options = CFOptionFlags(opt) return CFPropertyListCreateData(kCFAllocatorSystemDefault, plist, fmt, options, outErr) } if let res = result { return res._nsObject } else { throw error!.takeRetainedValue()._nsObject } } /// - Experiment: Note that the return type of this function is different than on Darwin Foundation (Any instead of AnyObject). This is likely to change once we have a more complete story for bridging in place. public class func propertyListWithData(data: NSData, options opt: NSPropertyListReadOptions, format: UnsafeMutablePointer<NSPropertyListFormat>) throws -> Any { var fmt = kCFPropertyListBinaryFormat_v1_0 var error: Unmanaged<CFError>? = nil let decoded = withUnsafeMutablePointers(&fmt, &error) { (outFmt: UnsafeMutablePointer<CFPropertyListFormat>, outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> NSObject? in return unsafeBitCast(CFPropertyListCreateWithData(kCFAllocatorSystemDefault, unsafeBitCast(data, CFDataRef.self), CFOptionFlags(CFIndex(opt.rawValue)), outFmt, outErr), NSObject.self) } if format != nil { #if os(OSX) || os(iOS) format.memory = NSPropertyListFormat(rawValue: UInt(fmt.rawValue))! #else format.memory = NSPropertyListFormat(rawValue: UInt(fmt))! #endif } if let err = error { throw err.takeUnretainedValue()._nsObject } else { return _expensivePropertyListConversion(decoded!) } } } // Until we have proper bridging support, we will have to recursively convert NS/CFTypes to Swift types when we return them to callers. Otherwise, they may expect to treat them as Swift types and it will fail. Obviously this will cause a problem if they treat them as NS types, but we'll live with that for now. internal func _expensivePropertyListConversion(input : AnyObject) -> Any { if let dict = input as? NSDictionary { var result : [String : Any] = [:] dict.enumerateKeysAndObjectsUsingBlock { key, value, _ in guard let k = key as? NSString else { fatalError("Non-string key in a property list") } result[k._swiftObject] = _expensivePropertyListConversion(value) } return result } else if let array = input as? NSArray { var result : [Any] = [] array.enumerateObjectsUsingBlock { value, _, _ in result.append(_expensivePropertyListConversion(value)) } return result } else if let str = input as? NSString { return str._swiftObject } else if let date = input as? NSDate { return date } else if let data = input as? NSData { return data } else if let number = input as? NSNumber { return number } else if input === kCFBooleanTrue { return true } else if input === kCFBooleanFalse { return false } else { fatalError("Attempt to convert a non-plist type \(input)") } }
apache-2.0
25cc5df34e62bc9c6a219dd2633de1b3
42.137097
311
0.692092
4.876026
false
false
false
false
dreamsxin/swift
validation-test/stdlib/OpenCLSDKOverlay.swift
3
9511
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=macosx // Translated from standard OpenCL hello.c program // Abstract: A simple "Hello World" compute example showing basic usage of OpenCL which // calculates the mathematical square (X[i] = pow(X[i],2)) for a buffer of // floating point values. // // // Version: <1.0> // // Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") // in consideration of your agreement to the following terms, and your use, // installation, modification or redistribution of this Apple software // constitutes acceptance of these terms. If you do not agree with these // terms, please do not use, install, modify or redistribute this Apple // software. // // In consideration of your agreement to abide by the following terms, and // subject to these terms, Apple grants you a personal, non - exclusive // license, under Apple's copyrights in this original Apple software (the // "Apple Software"), to use, reproduce, modify and redistribute the Apple // Software, with or without modifications, in source and / or binary forms // provided that if you redistribute the Apple Software in its entirety and // without modifications, you must retain this notice and the following text // and disclaimers in all such redistributions of the Apple Software. Neither // the name, trademarks, service marks or logos of Apple Inc. may be used to // endorse or promote products derived from the Apple Software without specific // prior written permission from Apple. Except as expressly stated in this // notice, no other rights or licenses, express or implied, are granted by // Apple herein, including but not limited to any patent rights that may be // infringed by your derivative works or by other works in which the Apple // Software may be incorporated. // // The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO // WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED // WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION // ALONE OR IN COMBINATION WITH YOUR PRODUCTS. // // IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION // AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER // UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR // OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (C) 2008 Apple Inc. All Rights Reserved. // import OpenCL import StdlibUnittest import Foundation import Darwin let KernelSource = "\n" + "__kernel void square( \n" + " __global float* input, \n" + " __global float* output, \n" + " const unsigned int count) \n" + "{ \n" + " int i = get_global_id(0); \n" + " if (i < count) \n" + " output[i] = input[i] * input[i]; \n" + "} \n" + "\n" let DATA_SIZE = 1024 var tests = TestSuite("MiscSDKOverlay") tests.test("clSetKernelArgsListAPPLE") { var err: cl_int // error code returned from api calls var data = [Float](repeating: 0, count: DATA_SIZE) // original data set given to device var results = [Float](repeating: 0, count: DATA_SIZE) // results returned from device var correct: Int // number of correct results returned var global: size_t // global domain size for our calculation var local: size_t = 0 // local domain size for our calculation var device_id: cl_device_id? = nil // compute device id var context: cl_context? // compute context var commands: cl_command_queue? // compute command queue var program: cl_program? // compute program var kernel: cl_kernel? // compute kernel // Fill our data set with random float values // var count = DATA_SIZE for i in 0..<count { data[i] = 0.0 } // Connect to a compute device // err = clGetDeviceIDs(nil, cl_device_type(CL_DEVICE_TYPE_ALL), 1, &device_id, nil) if (err != CL_SUCCESS) { print("Error: Failed to create a device group!") exit(EXIT_FAILURE) } // Create a compute context // context = clCreateContext(nil, 1, &device_id, nil, nil, &err) if (context == nil) { print("Error: Failed to create a compute context!") exit(EXIT_FAILURE) } // Create a command commands // commands = clCreateCommandQueue(context, device_id, 0, &err) if (commands == nil) { print("Error: Failed to create a command commands!") exit(EXIT_FAILURE) } // Create the compute program from the source buffer // program = KernelSource.withCString { (p: UnsafePointer<CChar>) -> cl_program in var s: UnsafePointer? = p return withUnsafeMutablePointer(&s) { return clCreateProgramWithSource(context, 1, $0, nil, &err) } } if (program == nil) { print("Error: Failed to create compute program!") exit(EXIT_FAILURE) } // Build the program executable // err = clBuildProgram(program, 0, nil, nil, nil, nil) if (err != CL_SUCCESS) { var len: Int = 0 var buffer = [CChar](repeating: 0, count: 2048) print("Error: Failed to build program executable!") clGetProgramBuildInfo( program, device_id, cl_program_build_info(CL_PROGRAM_BUILD_LOG), 2048, &buffer, &len) print("\(String(cString: buffer))") exit(1) } // Create the compute kernel in the program we wish to run // kernel = clCreateKernel(program, "square", &err) if (kernel == nil || err != cl_int(CL_SUCCESS)) { print("Error: Failed to create compute kernel!") exit(1) } // Create the input and output arrays in device memory for our calculation // guard var input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), sizeof(Float.self) * count, nil, nil), var output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), sizeof(Float.self) * count, nil, nil) else { print("Error: Failed to allocate device memory!") exit(1) } // Write our data set into the input array in device memory // err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, data, 0, nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to write to source array!") exit(1) } // Set the arguments to our compute kernel // err = 0 err = withUnsafePointers(&input, &output, &count) { inputPtr, outputPtr, countPtr in clSetKernelArgsListAPPLE( kernel!, 3, 0, sizeof(cl_mem.self), inputPtr, 1, sizeof(cl_mem.self), outputPtr, 2, sizeofValue(count), countPtr) } if (err != CL_SUCCESS) { print("Error: Failed to set kernel arguments! \(err)") exit(1) } // Get the maximum work group size for executing the kernel on the device // err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), sizeofValue(local), &local, nil) if (err != CL_SUCCESS) { print("Error: Failed to retrieve kernel work group info! \(err)") exit(1) } // Execute the kernel over the entire range of our 1d input data set // using the maximum number of work group items for this device // global = count err = clEnqueueNDRangeKernel(commands, kernel, 1, nil, &global, &local, 0, nil, nil) if (err != 0) { print("Error: Failed to execute kernel!") exit(EXIT_FAILURE) } // Wait for the command commands to get serviced before reading back results // clFinish(commands) // Read back the results from the device to verify the output // err = clEnqueueReadBuffer(commands, output, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, &results, cl_uint(0), nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to read output array! \(err)") exit(1) } // Validate our results // correct = 0 for i in 0..<count { if (results[i] == data[i] * data[i]) { correct += 1 } } // Print a brief summary detailing the results // print("Computed '\(correct)/\(count)' correct values!") // Shutdown and cleanup // clReleaseMemObject(input) clReleaseMemObject(output) clReleaseProgram(program) clReleaseKernel(kernel) clReleaseCommandQueue(commands) clReleaseContext(context) } runAllTests()
apache-2.0
00cc76fca632590f3be13906ce640602
35.301527
138
0.612238
4.173322
false
false
false
false
gminky019/Content-Media-App
Content Media App/Content Media App/ConnectToAWS.swift
1
26092
// // ConnectToAWS.swift // Content Media App // // Created by Garrett Minky on 3/31/16. // Copyright © 2016 Garrett Minky. All rights reserved. // /* Description: This is the main class that connects to the AWS S3 instance to download the main page. This class opens up a function that passes a complex dictionary to the integration layer that contains all the data needed for the content classes to populate the main page. It utilizes multithreaded asyncrounous functions to laod the content from aws extremely fast. It uses the _s3MainBucket as the global o get the data from a bucket. */ import Foundation public class ConnectToAWS{ // These globals are used to store the various content and data coming from aws let _transferManager: AWSS3TransferManager var _completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock? var _prefix: String let _s3: AWSS3 var _keys: [AWSS3Object] var _MainKeyDict: [String: AWSS3Object] var _HeroURLDict: [String: [NSURL]] var _urlsTemp : [NSURL] var _urlKey : [String: String] var _globalCountVar : Int var _globFlag: Bool = false var _downLoaded: [String: Bool] var _realDown: [String] let _s3MainBucket: String = "contentmediaapp" //let _baseURL : String init() { self._transferManager = AWSS3TransferManager.defaultS3TransferManager() //self._baseURL = self._prefix = "" self._s3 = AWSS3.defaultS3() self._keys = [AWSS3Object]() self._urlsTemp = [NSURL]() self._MainKeyDict = [String: AWSS3Object]() self._HeroURLDict = [String: [NSURL]]() self._urlKey = [String: String]() self._globalCountVar = 0 self._downLoaded = [String: Bool]() self._realDown = [String]() } /* This method is the method the middle ware will call to get the main page content. It uses a completion handler to handle the multithreaded aspect and returns a dictionary of the data passed back from AWS */ func getMain(completion: (main: [String: [NSURL]])->()){ self.getKeys("Hero") {(keys: [AWSS3Object]) in self._keys = keys //parse string for key self.setMainKeyDict(keys) let sortKeys: [AWSS3Object] = self.parseKeys("Main", allKey: keys) //set download req let req : [AWSS3TransferManagerDownloadRequest] = self.setReq(sortKeys) // self.testGet() //initiate download // let queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) var urls: [NSURL] = [NSURL]() self.downLoadMain(req) {( mainDict: [String: [NSURL]]) in (completion(main: mainDict)) } self._urlsTemp = urls } } /* This is the mid level completion handler function that handles the processing to download all the main content for the page. It is essentially an abstraction layer method that uses all the Requests and then calls a download method for each one. What also makes this important is this method uses groups for the threads to be notified when all the threada are complete. This will return the dictionary needed filled with the local url's for the downloaded content. */ func downLoadMain(reqs : [AWSS3TransferManagerDownloadRequest], complete: (mainDict: [String: [NSURL]])-> ()) { self._globalCountVar = 0 let firstGroup = dispatch_group_create() // let sem : dispatch_semaphore_t = dispatch_semaphore_create(0) let queue:dispatch_queue_t = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT) for r in reqs // dispatch_apply(reqs.count, queue) { // i in // dispatch_async(queue, {() -> Void in dispatch_group_enter(firstGroup) // let index = Int(i) //let r:AWSS3TransferManagerDownloadRequest = reqs[index] let DictKey: String = self.findMainURLKey(r.key!) self._downLoaded[r.downloadingFileURL.path!] = false; self.downLoadV2(r, group: firstGroup) { (url: NSURL) in //dispatch_group_leave(firstGroup) var temp: [NSURL] if(!self._HeroURLDict.keys.contains(DictKey).boolValue) { temp = [NSURL]() } else { temp = self._HeroURLDict[DictKey]! } temp.append(url) self._HeroURLDict[DictKey] = temp self._urlsTemp.append(url) } } dispatch_group_notify(firstGroup, dispatch_get_main_queue()){ complete(mainDict: self._HeroURLDict) } } /* This is the vErsion 2 of the download function that will actually download the aws content. This method will complete the completion handler on a data success or error and pass back the downloaded local url for the file content. */ func downLoadV2(downReq: AWSS3TransferManagerDownloadRequest, group: dispatch_group_t, completionDown: (url: NSURL) ->()) { let transferManager = AWSS3TransferManager.defaultS3TransferManager() var downLoadPath: NSURL? // dispatch_group_enter(group) print(String(self._globalCountVar)) print("Adding Dispatch Low Level \n") transferManager.download(downReq).continueWithBlock({(task) -> AnyObject! in if let error = task.error{ if error.domain == AWSS3TransferManagerErrorDomain as String && AWSS3TransferManagerErrorType(rawValue: error.code) == AWSS3TransferManagerErrorType.Paused{ // dispatch_group_leave(group) print ("DownLoad Paused") }else{ dispatch_group_leave(group) print("FAILED ON " + downReq.key! + "\n") print("DownLoad Failed: [\(error)]" + "\n\n") } } else if let exception = task.exception { //dispatch_group_leave(group) print("download failed: [\(exception)]") } else{ // dispatch_group_leave(group) dispatch_async(dispatch_get_main_queue(), {() -> Void in print("SUCCESS ON " + downReq.key! + "\n\n") downLoadPath = downReq.downloadingFileURL dispatch_group_leave(group) completionDown(url: downLoadPath!) }) } // dispatch_group_leave(group) return nil }) } /* This method is a helper function that finds the main url based off of the key given. It is used by the middle integration layer to complete the custom objects. */ func findMainURLKey(key: String) -> String { var dicKey: String = "" let keyVal = key.lowercaseString if(keyVal.lowercaseString.rangeOfString("hero") != nil) { if(keyVal.lowercaseString.rangeOfString("main") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { dicKey = "mainsub" } else { dicKey = "main" } } else if (keyVal.lowercaseString.rangeOfString("read/hero") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { dicKey = "readsub" } else { dicKey = "read" } } else if(keyVal.lowercaseString.rangeOfString("read/sub") != nil) { dicKey = "readsub" } else if(keyVal.lowercaseString.rangeOfString("learn/hero") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { dicKey = "learnsub" } else { dicKey = "learn" } } else if(keyVal.lowercaseString.rangeOfString("learn/sub") != nil) { dicKey = "learnsub" } else if(keyVal.lowercaseString.rangeOfString("shop/hero") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { dicKey = "shopsub" } else { dicKey = "shop" } } else if(keyVal.lowercaseString.rangeOfString("shop/sub") != nil) { dicKey = "shopsub" } else if(keyVal.lowercaseString.rangeOfString("watch/hero") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { dicKey = "watchsub" } else { dicKey = "watch" } } else if(keyVal.lowercaseString.rangeOfString("watch/sub") != nil) { dicKey = "watchsub" } else { } } return dicKey } /* This method is a helper used when the downloaders need to put content into the dictionary that is passed back to the integration layer. This will take the s3 object and then create the key in the dictionary and how to find it. */ func setMainKeyDict(allKey: [AWSS3Object]) { for key in allKey { let keyVal: String = key.key!.lowercaseString if(keyVal.lowercaseString.rangeOfString("hero") != nil) { if(keyVal.lowercaseString.rangeOfString("main") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { self._MainKeyDict["mainsub"] = key } else { self._MainKeyDict["main"] = key } } else if (keyVal.lowercaseString.rangeOfString("read") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { self._MainKeyDict["readsub"] = key } else { self._MainKeyDict["read"] = key } } else if(keyVal.lowercaseString.rangeOfString("learn") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { self._MainKeyDict["learnsub"] = key } else { self._MainKeyDict["learn"] = key } } else if(keyVal.lowercaseString.rangeOfString("shop") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { self._MainKeyDict["shopsub"] = key } else { self._MainKeyDict["shop"] = key } } else if(keyVal.lowercaseString.rangeOfString("watch") != nil) { if(keyVal.lowercaseString.rangeOfString("sub") != nil) { self._MainKeyDict["watchsub"] = key } else { self._MainKeyDict["watch"] = key } } else { } } } } /* This method parses the keys found from the AWS calls and finds what type of content they are; and if that is necessary for the download calls. This will return the new array of s3 objects that are valid for downloading. */ func parseKeys(type: String, allKey: [AWSS3Object]) -> [AWSS3Object] { var parsedKeys: [AWSS3Object] = [AWSS3Object]() switch type { case "Main": for k in allKey { let val: String = k.key!.lowercaseString if(val.lowercaseString.rangeOfString("hero") != nil) { parsedKeys.append(k) } } default: print("Did not find type") } return parsedKeys } /* This method takes the AWSS3Objects and goes throuhgh each one and sets the downloadrequest objects needed for downloading. The download requests include the file download path as well. It will return an array of the download requests. */ func setReq(s3Obj: [AWSS3Object]) -> [AWSS3TransferManagerDownloadRequest] { var reqList: [AWSS3TransferManagerDownloadRequest] = [AWSS3TransferManagerDownloadRequest]() for s3 in s3Obj{ let tempDir = NSURL(fileURLWithPath: NSTemporaryDirectory()) let downloadURL = NSTemporaryDirectory().stringByAppendingString(s3.key!) let tempURL = NSURL(fileURLWithPath: downloadURL) let url: NSURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true).URLByAppendingPathComponent(s3.key!) var str: String = s3.key! if(s3.key!.lowercaseString.rangeOfString("/") != nil) { str = s3.key!.stringByReplacingOccurrencesOfString("/", withString: "+") } let downFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(str) let downFilePath = downFileURL.path! self._urlKey[downFileURL.path!] = s3.key if NSFileManager.defaultManager().fileExistsAtPath(tempURL.path!){ //reqList.append(nil) print("Error getting download request file path exists") } else { let downReq = AWSS3TransferManagerDownloadRequest() downReq.bucket = "contentmediaapp" downReq.key = s3.key downReq.downloadingFileURL = downFileURL reqList.append(downReq) } //downloadURL = nil // rempurl = nil } return reqList } /* This method gets all keys from the aws s3 bucket set. Getting all the keys from this bucket is necessary to download as this is only main page content. This method will return an array of the newly minted AWSS3Objects with the proper keys used for downloading. */ func getKeys(prefix: String, completionKey: (keys: [AWSS3Object]) -> ()){ let listObjectsRequest = AWSS3ListObjectsRequest() listObjectsRequest.bucket = "contentmediaapp" //listObjectsRequest.delimiter = "/" // listObjectsRequest.prefix = prefix //listObjectsRequest. self._s3.listObjects(listObjectsRequest).continueWithSuccessBlock({(task) -> AnyObject! in if let error = task.error{ print("List objects Failed: [\(error)]") } if let exception = task.exception { print("list objects failed: [\(exception)]") } if let listOutput = task.result as? AWSS3ListObjectsOutput { if let contents = listOutput.contents as [AWSS3Object]? { completionKey(keys: contents) } } return nil }) } /* This method is a helper function that propery creates the thumbnail objects and formats the dictionary so the front end/integration layer understands what type of data is held. It will return a subhero object which is all of the subheros. */ func getSubHero(type: String) -> SubHero { self._prefix = type + "/Hero/" //get listings let subListings = getListObj() //setdownReq let subReq = setDownloadReq(subListings) var main: ThumbNail? for req in subReq{ let url = downLoad(req) main = ThumbNail(title: req.key!, description: type + " Main Hero", key: req.key!, picture: UIImage(contentsOfFile: url.path!)!) } self._prefix = type + "/SubHero/" //get listings let subSubListings = getListObj() //setdownReq let subSubReq = setDownloadReq(subSubListings) var subList: [ThumbNail] = [ThumbNail]() for subr in subSubReq{ let urlS = downLoad(subr) subList.append( ThumbNail(title: subr.key!, description: type + " Main Hero", key: subr.key!, picture: UIImage(contentsOfFile: urlS.path!)!)) } return SubHero(cType: type, hero: main!, subHero: subList) } /* This is another get main page conent function like above. This method has been depreciated but still is functional as it will return a flat array of the content instead of a proper formatted dictionary */ func GetMainPage() -> MainPageContent{ var content: MainPageContent? var mainHero: [ThumbNail] = [ThumbNail]() var subHeros: [SubHero] = [SubHero]() //Get Main Hero Content //set prefix self._prefix = "Hero/" //get listing let mainHerolistings: [AWSS3Object] = getListObj() //set downreq let mainHeroDownReq: [AWSS3TransferManagerDownloadRequest] = setDownloadReq(mainHerolistings) //download listings for req in mainHeroDownReq { //create objects let url = downLoad(req) mainHero.append(ThumbNail(title: req.key!, description: "Tester", key: req.key!, picture: UIImage(contentsOfFile: url.path!)!)) } //GetSub Hero Content From each content type let start: Int = 0 //for loop while start < 3 { var type: String = "" //set prefix for content if(start == 0 ){ type = "Read" subHeros.append(getSubHero(type)) } else if (start == 1) { type = "Learn" subHeros.append(getSubHero(type)) } else { type = "Watch" subHeros.append(getSubHero(type)) } //create objects } content = MainPageContent(heros: mainHero, sub: [Content](), contSub: subHeros) //return main page return content! } /* This is a depreciated download function as it does not handle multiple object calls. This method can be used to download a single object. */ func downLoad(downReq: AWSS3TransferManagerDownloadRequest) -> NSURL { let transferManager = AWSS3TransferManager.defaultS3TransferManager() var downLoadPath: NSURL? transferManager.download(downReq).continueWithBlock({(task) -> AnyObject! in if let error = task.error{ if error.domain == AWSS3TransferManagerErrorDomain as String && AWSS3TransferManagerErrorType(rawValue: error.code) == AWSS3TransferManagerErrorType.Paused{ print ("DownLoad Paused") }else{ print("DownLoad Failed: [\(error)]") } } else if let exception = task.exception { print("download failed: [\(exception)]") } else{ dispatch_async(dispatch_get_main_queue(), {() -> Void in downLoadPath = downReq.downloadingFileURL }) } return downLoadPath }) return downLoadPath! } /* This is a depreciated downloadrequiremtns function. This method did not handle complex objects. It is still functional it just will only do a flat AWS class. */ func setDownloadReq(s3Obj: [AWSS3Object]) -> [AWSS3TransferManagerDownloadRequest] { var reqList: [AWSS3TransferManagerDownloadRequest] = [AWSS3TransferManagerDownloadRequest]() for s3 in s3Obj{ let downFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("download").URLByAppendingPathComponent(s3.key!) let downFilePath = downFileURL.path! if NSFileManager.defaultManager().fileExistsAtPath(downFilePath){ //reqList.append(nil) print("Error getting download request file path exists") } else { let downReq = AWSS3TransferManagerDownloadRequest() downReq.bucket = "contentmediaapp" downReq.key = s3.key downReq.downloadingFileURL = downFileURL reqList.append(downReq) } } return reqList } /* func getKeys(){ let listObjectsRequest = AWSS3ListObjectsRequest() listObjectsRequest.bucket = "contentmediaapp" listObjectsRequest.delimiter = "/" listObjectsRequest.prefix = self._prefix self._s3.listObjects(listObjectsRequest).continueWithBlock({(task) -> AnyObject! in if let error = task.error{ print("List objects Failed: [\(error)]") } if let exception = task.exception { print("list objects failed: [\(exception)]") } if let listOutput = task.result as? AWSS3ListObjectsOutput { if let contents = listOutput.contents! as? [AWSS3Object] { } } return nil }) }*/ /* This method is a get keys method call for the AWS S3 database. It will return all keys with a certain prefix. */ func getListObj() -> [AWSS3Object] { let listObjectsRequest = AWSS3ListObjectsRequest() listObjectsRequest.bucket = "contentmediaapp" listObjectsRequest.delimiter = "/" listObjectsRequest.prefix = self._prefix self._s3.listObjects(listObjectsRequest).continueWithBlock({(task) -> AnyObject! in if let error = task.error{ print("List objects Failed: [\(error)]") } if let exception = task.exception { print("list objects failed: [\(exception)]") } if let listOutput = task.result as? AWSS3ListObjectsOutput { if let contents = listOutput.contents! as? [AWSS3Object] { return contents } } return nil }) return [AWSS3Object]() } /* This is a testing method. We used this method to test getting a single picture from the AWS Instance. */ func testGet() { let downloadURL = NSTemporaryDirectory().stringByAppendingString("ronswanson.jpg") let tempURL = NSURL(fileURLWithPath: downloadURL) let downloadReq: AWSS3TransferManagerDownloadRequest = AWSS3TransferManagerDownloadRequest() downloadReq.bucket = "contentmediaapp" downloadReq.key = "ronswanson.jpg" downloadReq.downloadingFileURL = tempURL var selectedImage: UIImage? let task = self._transferManager.download(downloadReq) task.continueWithBlock { (task: AWSTask) -> AnyObject! in print(task.error) if task.error != nil { print("GAHH") } else { dispatch_async(dispatch_get_main_queue() , { selectedImage = UIImage(contentsOfFile: downloadURL)! }) if((task.result) != nil){ var down:AnyObject? = task.result } } return nil } } /* A helpr method that returns the class member dictionary to a class that calls it. */ func getUrlKeyDict() -> [String: String] { return self._urlKey } }
apache-2.0
8c9597d8f6b0e6c97e34f49c0098476e
32.709302
338
0.514315
5.43223
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/RecentlySaved/RecentlySavedViewModel.swift
1
8851
// 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 Storage struct RecentlySavedCellViewModel { let site: Site var heroImage: UIImage? var favIconImage: UIImage? } class RecentlySavedViewModel { struct UX { static let cellWidth: CGFloat = 150 static let cellHeight: CGFloat = 110 static let generalSpacing: CGFloat = 8 static let iPadGeneralSpacing: CGFloat = 8 } // MARK: - Properties var isZeroSearch: Bool var theme: Theme private let profile: Profile private var recentlySavedDataAdaptor: RecentlySavedDataAdaptor private var recentItems = [RecentlySavedItem]() private var wallpaperManager: WallpaperManager private var siteImageHelper: SiteImageHelperProtocol var headerButtonAction: ((UIButton) -> Void)? weak var delegate: HomepageDataModelDelegate? init(profile: Profile, isZeroSearch: Bool = false, theme: Theme, wallpaperManager: WallpaperManager) { self.profile = profile self.isZeroSearch = isZeroSearch self.theme = theme self.siteImageHelper = SiteImageHelper(profile: profile) let adaptor = RecentlySavedDataAdaptorImplementation(readingList: profile.readingList, bookmarksHandler: profile.places) self.recentlySavedDataAdaptor = adaptor self.wallpaperManager = wallpaperManager adaptor.delegate = self } } // MARK: HomeViewModelProtocol extension RecentlySavedViewModel: HomepageViewModelProtocol, FeatureFlaggable { var sectionType: HomepageSectionType { return .recentlySaved } var headerViewModel: LabelButtonHeaderViewModel { var textColor: UIColor? if wallpaperManager.featureAvailable { textColor = wallpaperManager.currentWallpaper.textColor } return LabelButtonHeaderViewModel( title: HomepageSectionType.recentlySaved.title, titleA11yIdentifier: AccessibilityIdentifiers.FirefoxHomepage.SectionTitles.recentlySaved, isButtonHidden: false, buttonTitle: .RecentlySavedShowAllText, buttonAction: headerButtonAction, buttonA11yIdentifier: AccessibilityIdentifiers.FirefoxHomepage.MoreButtons.recentlySaved, textColor: textColor) } func section(for traitCollection: UITraitCollection) -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize( widthDimension: .absolute(UX.cellWidth), heightDimension: .estimated(UX.cellHeight) ) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize( widthDimension: .absolute(UX.cellWidth), heightDimension: .estimated(UX.cellHeight) ) let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(34)) let header = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize, elementKind: UICollectionView.elementKindSectionHeader, alignment: .top) section.boundarySupplementaryItems = [header] let leadingInset = HomepageViewModel.UX.leadingInset(traitCollection: traitCollection) section.contentInsets = NSDirectionalEdgeInsets( top: 0, leading: leadingInset, bottom: HomepageViewModel.UX.spacingBetweenSections, trailing: 0) let isIPad = UIDevice.current.userInterfaceIdiom == .pad section.interGroupSpacing = isIPad ? UX.iPadGeneralSpacing: UX.generalSpacing section.orthogonalScrollingBehavior = .continuous return section } func numberOfItemsInSection() -> Int { return recentItems.count } var isEnabled: Bool { return featureFlags.isFeatureEnabled(.recentlySaved, checking: .buildAndUser) } var hasData: Bool { return !recentItems.isEmpty } func refreshData(for traitCollection: UITraitCollection, isPortrait: Bool = UIWindow.isPortrait, device: UIUserInterfaceIdiom = UIDevice.current.userInterfaceIdiom) {} func setTheme(theme: Theme) { self.theme = theme } } // MARK: FxHomeSectionHandler extension RecentlySavedViewModel: HomepageSectionHandler { func configure(_ cell: UICollectionViewCell, at indexPath: IndexPath) -> UICollectionViewCell { guard let recentlySavedCell = cell as? RecentlySavedCell else { return UICollectionViewCell() } if let item = recentItems[safe: indexPath.row] { let site = Site(url: item.url, title: item.title, bookmarked: true) let id = Int(arc4random()) cell.tag = id var heroImage: UIImage? var favicon: UIImage? let viewModel = RecentlySavedCellViewModel(site: site, heroImage: heroImage, favIconImage: favicon) siteImageHelper.fetchImageFor(site: site, imageType: .heroImage, shouldFallback: true) { image in guard cell.tag == id else { return } heroImage = image let viewModel = RecentlySavedCellViewModel(site: site, heroImage: heroImage, favIconImage: favicon) recentlySavedCell.configure(viewModel: viewModel, theme: self.theme) } siteImageHelper.fetchImageFor(site: site, imageType: .favicon, shouldFallback: true) { image in guard cell.tag == id else { return } favicon = image let viewModel = RecentlySavedCellViewModel(site: site, heroImage: heroImage, favIconImage: favicon) recentlySavedCell.configure(viewModel: viewModel, theme: self.theme) } recentlySavedCell.configure(viewModel: viewModel, theme: theme) } return recentlySavedCell } func didSelectItem(at indexPath: IndexPath, homePanelDelegate: HomePanelDelegate?, libraryPanelDelegate: LibraryPanelDelegate?) { if let item = recentItems[safe: indexPath.row] as? RecentlySavedBookmark { guard let url = URIFixup.getURL(item.url) else { return } homePanelDelegate?.homePanel(didSelectURL: url, visitType: .bookmark, isGoogleTopSite: false) TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .recentlySavedBookmarkItemAction, extras: TelemetryWrapper.getOriginExtras(isZeroSearch: isZeroSearch)) } else if let item = recentItems[safe: indexPath.row] as? ReadingListItem, let url = URL(string: item.url), let encodedUrl = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) { let visitType = VisitType.bookmark libraryPanelDelegate?.libraryPanel(didSelectURL: encodedUrl, visitType: visitType) TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .recentlySavedReadingListAction, extras: TelemetryWrapper.getOriginExtras(isZeroSearch: isZeroSearch)) } } } extension RecentlySavedViewModel: RecentlySavedDelegate { func didLoadNewData() { ensureMainThread { self.recentItems = self.recentlySavedDataAdaptor.getRecentlySavedData() guard self.isEnabled else { return } self.delegate?.reloadView() } } }
mpl-2.0
03d62de250ca49d1fea958025df7903f
40.167442
120
0.600836
6.09573
false
false
false
false