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
einsteinx2/iSub
Carthage/Checkouts/Nuke/Tests/PerformanceTests.swift
1
4020
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Nuke import XCTest class ManagerPerformanceTests: XCTestCase { func testDefaultManager() { let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { Nuke.loadImage(with: url, into: view) } } } func testWithoutMemoryCache() { let loader = Loader(loader: DataLoader(), decoder: DataDecoder(), cache: nil) let manager = Manager(loader: Deduplicator(loader: loader)) let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { manager.loadImage(with: url, into: view) } } } func testWithoutDeduplicator() { let loader = Loader(loader: DataLoader(), decoder: DataDecoder(), cache: nil) let manager = Manager(loader: loader) let view = ImageView() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(5000))")! } measure { for url in urls { manager.loadImage(with: url, into: view) } } } } class CachePerformanceTests: XCTestCase { func testCacheWrite() { let cache = Cache() let image = Image() let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(500))")! } measure { for url in urls { let request = Request(url: url) cache[request] = image } } } func testCacheHit() { let cache = Cache() for i in 0..<200 { cache[Request(url: URL(string: "http://test.com/\(i))")!)] = Image() } var hits = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } measure { for url in urls { let request = Request(url: url) if cache[request] != nil { hits += 1 } } } print("hits: \(hits)") } func testCacheMiss() { let cache = Cache() var misses = 0 let urls = (0..<10_000).map { _ in return URL(string: "http://test.com/\(rnd(200))")! } measure { for url in urls { let request = Request(url: url) if cache[request] == nil { misses += 1 } } } print("misses: \(misses)") } } class DeduplicatorPerformanceTests: XCTestCase { func testDeduplicatorHits() { let deduplicator = Deduplicator(loader: MockImageLoader()) let request = Request(url: URL(string: "http://test.com/\(arc4random())")!) measure { let cts = CancellationTokenSource() for _ in (0..<10_000) { _ = deduplicator.loadImage(with: request, token:cts.token) } } } func testDeduplicatorMisses() { let deduplicator = Deduplicator(loader: MockImageLoader()) let requests = (0..<10_000) .map { _ in return URL(string: "http://test.com/\(arc4random())")! } .map { return Request(url: $0) } measure { let cts = CancellationTokenSource() for request in requests { _ = deduplicator.loadImage(with: request, token:cts.token) } } } } class MockImageLoader: Loading { func loadImage(with request: Request, token: CancellationToken?) -> Promise<Image> { return Promise() { fulfill, reject in return } } }
gpl-3.0
d45946229bd804520af3085a3ce2a576
26.534247
96
0.484328
4.481605
false
true
false
false
rodrigoruiz/SwiftUtilities
SwiftUtilities/Lite/NewStructures/Result.swift
1
4389
// // Result.swift // SwiftUtilities // // Created by Rodrigo Ruiz on 4/25/17. // Copyright © 2017 Rodrigo Ruiz. All rights reserved. // public enum Result<S, F> { case success(S) case failure(F) public func getSuccess() -> S? { if case let .success(s) = self { return s } return nil } public func getFailure() -> F? { if case let .failure(f) = self { return f } return nil } public func isSuccess() -> Bool { if case .success(_) = self { return true } return false } public func isFailure() -> Bool { return !isSuccess() } public func flatMap<S2>(_ transform: (S) -> Result<S2, F>) -> Result<S2, F> { switch self { case let .success(s): return transform(s) case let .failure(f): return .failure(f) } } public func map<S2>(_ transform: (S) -> S2) -> Result<S2, F> { return flatMap({ .success(transform($0)) }) } public func flatMapFailure<F2>(_ transform: (F) -> Result<S, F2>) -> Result<S, F2> { switch self { case let .success(s): return .success(s) case let .failure(f): return transform(f) } } public func mapFailure<F2>(_ transform: @escaping (F) -> F2) -> Result<S, F2> { return flatMapFailure({ .failure(transform($0)) }) } public func mapToValue<V>(_ successTransform: (S) -> V, _ failureTransform: (F) -> V) -> V { switch self { case let .success(s): return successTransform(s) case let .failure(f): return failureTransform(f) } } public func mapToVoid() -> Result<Void, F> { return map({ _ in }) } public func mapFailureToVoid() -> Result<S, Void> { return mapFailure({ _ in }) } } public func getSuccess<S, F>(_ result: Result<S, F>) -> S? { return result.getSuccess() } public func getFailure<S, F>(_ result: Result<S, F>) -> F? { return result.getFailure() } public func isSuccess<S, F>(_ result: Result<S, F>) -> Bool { return result.isSuccess() } public func isFailure<S, F>(_ result: Result<S, F>) -> Bool { return result.isFailure() } public func flatMap<S, F, S2>(_ transform: @escaping (S) -> Result<S2, F>) -> (Result<S, F>) -> Result<S2, F> { return { $0.flatMap(transform) } } public func map<S, F, S2>(_ transform: @escaping (S) -> S2) -> (Result<S, F>) -> Result<S2, F> { return { $0.map(transform) } } func flatMapFailure<S, F, F2>(_ transform: @escaping (F) -> Result<S, F2>) -> (Result<S, F>) -> Result<S, F2> { return { $0.flatMapFailure(transform) } } public func mapFailure<S, F, F2>(_ transform: @escaping (F) -> F2) -> (Result<S, F>) -> Result<S, F2> { return { $0.mapFailure(transform) } } public func mapToValue<S, F, V>( _ successTransform: @escaping (S) -> V, _ failureTransform: @escaping (F) -> V ) -> (Result<S, F>) -> V { return { $0.mapToValue(successTransform, failureTransform) } } public func mapToVoid<S, F>(_ result: Result<S, F>) -> Result<Void, F> { return result.mapToVoid() } public func mapFailureToVoid<S, F>(_ result: Result<S, F>) -> Result<S, Void> { return result.mapFailureToVoid() } public func reduceResults<S, F, S2>(_ initialResultValue: S2, _ nextPartialResultValue: @escaping (S2, S) -> S2) -> ([Result<S, F>]) -> Result<S2, F> { return { results in return results.reduce(Result<S2, F>.success(initialResultValue), { result, next in switch (result, next) { case let (.success(r), .success(n)): return .success(nextPartialResultValue(r, n)) case let (.failure(error), _): return .failure(error) case let (_, .failure(error)): return .failure(error) default: fatalError() } }) } } public func == <S: Equatable, F: Equatable>(lhs: Result<S, F>, rhs: Result<S, F>) -> Bool { switch (lhs, rhs) { case let (.success(left), .success(right)): return left == right case let (.failure(left), .failure(right)): return left == right default: return false } }
mit
257e598fced316acee9f4248ccbd3785
26.425
151
0.540109
3.527331
false
false
false
false
cenzuen/swiftAddressBook
swiftTest-10 AddressBook/ViewController.swift
1
4733
// // ViewController.swift // swiftTest-10 AddressBook // // Created by joey0824 on 2017/5/24. // Copyright © 2017年 JC. All rights reserved. // import UIKit import LKDBHelper class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView:UITableView? lazy var dataArr : [contactDBModel]? = { () -> [contactDBModel]? in guard let result = contactDBModel.search(withWhere: nil, orderBy: nil, offset: 0, count: 0) else{ return nil } return result as? [contactDBModel] }() var helper:LKDBHelper? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "联系人列表" self.helper = contactDBModel.getUsingLKDBHelper() setupTableView() setupNaviItem() print(NSHomeDirectory()) } //MARK: - tableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard (dataArr?.count) != nil else { return 0 } return (dataArr?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellId") } guard let data = dataArr?[indexPath.row] else { return cell! } cell?.textLabel?.text = data.name cell?.detailTextLabel?.text = data.phoneNum return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC:detailViewController = detailViewController() detailVC.contact = (dataArr?[indexPath.row])! detailVC.saveContact = { (contact:contactDBModel) in contact.updateToDB() self.dataArr?[indexPath.row] = contact self.tableView?.reloadData() } self.navigationController?.pushViewController(detailVC, animated: true) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delAction = UITableViewRowAction(style: .destructive, title: "删除") { (rowAction, indexPath) in self.dataArr?[indexPath.row].deleteToDB() self.dataArr?.remove(at: indexPath.row) self.tableView?.reloadData() } return [delAction] } //tabelView func setupTableView() { tableView = UITableView(frame: view.bounds, style: .plain) tableView?.center = view.center tableView?.delegate = self tableView?.dataSource = self view.addSubview(tableView!) } //NaviItem func setupNaviItem() { let rightItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(touchupAdd)) self.navigationItem.rightBarButtonItem = rightItem } func touchupAdd() { let detailVC = detailViewController() detailVC.contact = contactDBModel.init() detailVC.saveContact = { (contact:contactDBModel) in contactDBModel.insert(toDB: contact) self.dataArr?.append(contact) self.tableView?.reloadData() } self.navigationController?.pushViewController(detailVC, animated: true) } //批量生成虚拟数据 private func loadData(competion:@escaping (_ list:[contactDBModel])->()) { DispatchQueue.global().async { print("正在努力jiaz") var arrayM = [contactDBModel]() for i in 0..<20 { var contact = contactDBModel.init(name: "客户\(i)", phoneNum: "1860"+String(format: "%06d", arc4random_uniform(100000)))//contactModel.init(name: "客户\(i)", phoneNum: "1860"+String(format: "%06d", arc4random_uniform(100000))) arrayM.append(contact) } DispatchQueue.main.async(execute: { competion(arrayM) }) } } }
apache-2.0
da4be06d3a77369346a53adc56e2b743
25.463277
238
0.541845
5.459207
false
false
false
false
KiiPlatform/thing-if-iOSSample
SampleProject/IoTSchema.swift
1
6129
// // IoTSchema.swift // SampleProject // // Created by Yongping on 8/28/15. // Copyright © 2015 Kii Corporation. All rights reserved. // import Foundation import ThingIFSDK enum StatusType: String{ case BoolType = "boolean" case IntType = "integer" case DoubleType = "double" case StringType = "string" init?(string: String) { switch string { case StatusType.BoolType.rawValue: self = .BoolType case StatusType.IntType.rawValue: self = .IntType case StatusType.DoubleType.rawValue: self = .DoubleType case StatusType.StringType.rawValue: self = .StringType default: return nil } } } struct ActionStruct { let actionSchema: ActionSchema! var value: AnyObject! // the return Ditionary will be like: ["actionName": ["requiredStatus": value] ], where value can be Bool, Int or Double. ie. ["TurnPower": ["power": true]] func getActionDict() -> Dictionary<String, AnyObject> { let actionDict: Dictionary<String, AnyObject> = [actionSchema.name: [actionSchema.status.name: value]] return actionDict } init(actionSchema: ActionSchema, value: AnyObject) { self.actionSchema = actionSchema self.value = value } init?(actionSchema: ActionSchema, actionDict: Dictionary<String, AnyObject>) { self.actionSchema = actionSchema if actionDict.keys.count == 0 { return nil } let actionNameKey = Array(actionDict.keys)[0] if actionSchema.name == actionNameKey { if let statusDict = actionDict[actionNameKey] as? Dictionary<String, AnyObject> { let statusNameKey = Array(statusDict.keys)[0] if actionSchema.status.name == statusNameKey { self.value = statusDict[statusNameKey] }else{ return nil } }else { return nil } }else { return nil } } } class StatusSchema: NSObject, NSCoding { let name: String! let type: StatusType! var minValue: AnyObject? var maxValue: AnyObject? func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.type.rawValue, forKey: "type") aCoder.encodeObject(self.minValue, forKey: "minValue") aCoder.encodeObject(self.maxValue, forKey: "maxValue") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.type = StatusType(string: aDecoder.decodeObjectForKey("type") as! String)! self.minValue = aDecoder.decodeObjectForKey("minValue") self.maxValue = aDecoder.decodeObjectForKey("maxValue") } init(name: String, type: StatusType, minValue: AnyObject?, maxValue: AnyObject?) { self.name = name self.type = type self.minValue = minValue self.maxValue = maxValue } } class ActionSchema: NSObject, NSCoding { let name: String! let status: StatusSchema! func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.status, forKey: "status") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.status = aDecoder.decodeObjectForKey("status") as! StatusSchema } init(actionName: String, status: StatusSchema) { self.name = actionName self.status = status } } class IoTSchema: NSObject,NSCoding { let name: String! let version: Int! private var statusSchemaDict = Dictionary<String, StatusSchema>() private var actionSchemaDict = Dictionary<String, ActionSchema>() func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.version, forKey: "version") aCoder.encodeObject(self.statusSchemaDict, forKey: "statusSchemaDict") aCoder.encodeObject(self.actionSchemaDict, forKey: "actionSchemaDict") } // MARK: - Implements NSCoding protocol required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.version = aDecoder.decodeObjectForKey("version") as! Int self.statusSchemaDict = aDecoder.decodeObjectForKey("statusSchemaDict") as! Dictionary<String, StatusSchema> self.actionSchemaDict = aDecoder.decodeObjectForKey("actionSchemaDict") as! Dictionary<String, ActionSchema> } init(name: String, version: Int) { self.name = name self.version = version } func addStatus(statusName: String, statusType: StatusType) { statusSchemaDict[statusName] = StatusSchema(name: statusName, type: statusType, minValue: nil, maxValue: nil) } func addStatus(statusName: String, statusType: StatusType, minValue: AnyObject?, maxvalue: AnyObject?) { statusSchemaDict[statusName] = StatusSchema(name: statusName, type: statusType, minValue: minValue, maxValue: maxvalue) } func getStatusType(status: String) -> StatusType? { return statusSchemaDict[status]?.type } func getStatusSchema(status: String) -> StatusSchema? { return statusSchemaDict[status] } func addAction(actionName: String, statusName: String) -> Bool { if let statusSchema = getStatusSchema(statusName) { actionSchemaDict[actionName] = ActionSchema(actionName: actionName, status: statusSchema) return true }else { return false } } func getActionSchema(actionName: String) -> ActionSchema? { return actionSchemaDict[actionName] } func getActionNames() -> [String] { return Array(actionSchemaDict.keys) } func getStatusNames() -> [String] { return Array(statusSchemaDict.keys) } }
mit
d8f83ef61ec8de71e5de3100d7ffb04c
30.592784
160
0.646867
4.743034
false
false
false
false
tsolomko/SWCompression
Sources/7-Zip/7zContainer.swift
1
11445
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData /// Provides functions for work with 7-Zip containers. public class SevenZipContainer: Container { static let signatureHeaderSize = 32 /** Processes 7-Zip container and returns an array of `SevenZipEntry` with information and data for all entries. - Important: The order of entries is defined by 7-Zip container and, particularly, by the creator of a given 7-Zip container. It is likely that directories will be encountered earlier than files stored in those directories, but no particular order is guaranteed. - Parameter container: 7-Zip container's data. - Throws: `SevenZipError` or any other error associated with compression type depending on the type of the problem. It may indicate that either container is damaged or it might not be 7-Zip container at all. - Returns: Array of `SevenZipEntry`. */ public static func open(container data: Data) throws -> [SevenZipEntry] { var entries = [SevenZipEntry]() guard let header = try readHeader(data), let files = header.fileInfo?.files else { return [] } /// Total count of non-empty files. Used to iterate over SubstreamInfo. var nonEmptyFileIndex = 0 /// Index of currently opened folder in `streamInfo.coderInfo.folders`. var folderIndex = 0 /// Index of currently extracted file in `headerInfo.fileInfo.files`. var folderFileIndex = 0 /// Index of currently read stream. var streamIndex = -1 /// Total size of unpacked data for current folder. Used for consistency check. var folderUnpackSize = 0 /// Combined calculated CRC of entire folder == all files in folder. var folderCRC = CheckSums.crc32(Data()) /// `LittleEndianByteReader` object with unpacked stream's data. var unpackedStreamData = LittleEndianByteReader(data: Data()) let byteReader = LittleEndianByteReader(data: data) for file in files { if file.isEmptyStream { let info = file.isEmptyFile && !file.isAntiFile ? SevenZipEntryInfo(file, 0) : SevenZipEntryInfo(file) let data = file.isEmptyFile && !file.isAntiFile ? Data() : nil entries.append(SevenZipEntry(info, data)) continue } // Without `SevenZipStreamInfo` and `SevenZipPackInfo` we cannot find file data in container. guard let streamInfo = header.mainStreams, let packInfo = streamInfo.packInfo else { throw SevenZipError.internalStructureError } // SubstreamInfo is required to get files' data, and without it we can only return files' info. guard let substreamInfo = streamInfo.substreamInfo else { entries.append(SevenZipEntry(SevenZipEntryInfo(file), nil)) continue } // Check if there is enough folders. guard folderIndex < streamInfo.coderInfo.numFolders else { throw SevenZipError.internalStructureError } /// Folder which contains current file. let folder = streamInfo.coderInfo.folders[folderIndex] // There may be several streams in a single folder, so we have to iterate over them, if necessary. // If we switched folders or completed reading of a stream we need to move to the next stream. if folderFileIndex == 0 || unpackedStreamData.isFinished { streamIndex += 1 // First, we move to the stream's offset. We don't have any guarantees that streams will be // enountered in the same order, as they are placed in the container. Thus, we have to start moving // to stream's offset from the beginning. // TODO: Is this correct or the order of streams is guaranteed? byteReader.offset = signatureHeaderSize + packInfo.packPosition // Pack offset. if streamIndex != 0 { for i in 0..<streamIndex { byteReader.offset += packInfo.packSizes[i] } } // Load the stream. let streamData = Data(byteReader.bytes(count: packInfo.packSizes[streamIndex])) // Check stream's CRC, if it's available. if streamIndex < packInfo.digests.count, let storedStreamCRC = packInfo.digests[streamIndex] { guard CheckSums.crc32(streamData) == storedStreamCRC else { throw SevenZipError.wrongCRC } } // One stream can contain data for several files, so we need to decode the stream first, then split // it into files. unpackedStreamData = LittleEndianByteReader(data: try folder.unpack(data: streamData)) } // `SevenZipSubstreamInfo` object must contain information about file's size and may also contain // information about file's CRC32. // File's unpacked size is required to proceed. guard nonEmptyFileIndex < substreamInfo.unpackSizes.count else { throw SevenZipError.internalStructureError } let fileSize = substreamInfo.unpackSizes[nonEmptyFileIndex] // Check, if we aren't about to read too much from a stream. guard fileSize <= unpackedStreamData.bytesLeft else { throw SevenZipError.internalStructureError } let fileData = Data(unpackedStreamData.bytes(count: fileSize)) let calculatedFileCRC = CheckSums.crc32(fileData) if nonEmptyFileIndex < substreamInfo.digests.count { guard calculatedFileCRC == substreamInfo.digests[nonEmptyFileIndex] else { throw SevenZipError.wrongCRC } } let info = SevenZipEntryInfo(file, fileSize, calculatedFileCRC) let data = fileData entries.append(SevenZipEntry(info, data)) // Update folder's crc and unpack size. folderUnpackSize += fileSize folderCRC = CheckSums.crc32(fileData, prevValue: folderCRC) folderFileIndex += 1 nonEmptyFileIndex += 1 if folderFileIndex >= folder.numUnpackSubstreams { // If we read all files in folder... // Check folder's unpacked size as well as its CRC32 (if it is available). guard folderUnpackSize == folder.unpackSize() else { throw SevenZipError.wrongSize } if let storedFolderCRC = folder.crc { guard folderCRC == storedFolderCRC else { throw SevenZipError.wrongCRC } } // Reset folder's unpack size and CRC32. folderCRC = CheckSums.crc32(Data()) folderUnpackSize = 0 // Reset file index for the next folder. folderFileIndex = 0 // Move to the next folder. folderIndex += 1 } } return entries } /** Processes 7-Zip container and returns an array of `SevenZipEntryInfo` with information about entries in this container. - Important: The order of entries is defined by 7-Zip container and, particularly, by the creator of a given 7-Zip container. It is likely that directories will be encountered earlier than files stored in those directories, but no particular order is guaranteed. - Parameter container: 7-Zip container's data. - Throws: `SevenZipError` or any other error associated with compression type depending on the type of the problem. It may indicate that either container is damaged or it might not be 7-Zip container at all. - Returns: Array of `SevenZipEntryInfo`. */ public static func info(container data: Data) throws -> [SevenZipEntryInfo] { var entries = [SevenZipEntryInfo]() guard let header = try readHeader(data), let files = header.fileInfo?.files else { return [] } var nonEmptyFileIndex = 0 for file in files { if !file.isEmptyStream, let substreamInfo = header.mainStreams?.substreamInfo { let size = nonEmptyFileIndex < substreamInfo.unpackSizes.count ? substreamInfo.unpackSizes[nonEmptyFileIndex] : nil let crc = nonEmptyFileIndex < substreamInfo.digests.count ? substreamInfo.digests[nonEmptyFileIndex] : nil entries.append(SevenZipEntryInfo(file, size, crc)) nonEmptyFileIndex += 1 } else { let info = file.isEmptyFile ? SevenZipEntryInfo(file, 0) : SevenZipEntryInfo(file) entries.append(info) } } return entries } private static func readHeader(_ data: Data) throws -> SevenZipHeader? { // Valid 7-Zip container must contain at least a SignatureHeader, which is 32 bytes long. guard data.count >= 32 else { throw SevenZipError.wrongSignature } let bitReader = MsbBitReader(data: data) // **SignatureHeader** // Check signature. guard bitReader.bytes(count: 6) == [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C] else { throw SevenZipError.wrongSignature } // Check archive version. let majorVersion = bitReader.byte() let minorVersion = bitReader.byte() guard majorVersion == 0 && minorVersion > 0 && minorVersion <= 4 else { throw SevenZipError.wrongFormatVersion } let startHeaderCRC = bitReader.uint32() /// - Note: Relative to SignatureHeader let nextHeaderOffset = bitReader.int(fromBytes: 8) let nextHeaderSize = bitReader.int(fromBytes: 8) let nextHeaderCRC = bitReader.uint32() bitReader.offset -= 20 guard CheckSums.crc32(bitReader.bytes(count: 20)) == startHeaderCRC else { throw SevenZipError.wrongCRC } // **Header** bitReader.offset += nextHeaderOffset if bitReader.isFinished { return nil // In case of completely empty container. } let headerStartIndex = bitReader.offset let headerEndIndex: Int let type = bitReader.byte() let header: SevenZipHeader if type == 0x17 { let packedHeaderStreamInfo = try SevenZipStreamInfo(bitReader) headerEndIndex = bitReader.offset header = try SevenZipHeader(bitReader, using: packedHeaderStreamInfo) } else if type == 0x01 { header = try SevenZipHeader(bitReader) headerEndIndex = bitReader.offset } else { throw SevenZipError.internalStructureError } // Check header size guard headerEndIndex - headerStartIndex == nextHeaderSize else { throw SevenZipError.wrongSize } // Check header CRC bitReader.offset = headerStartIndex guard CheckSums.crc32(bitReader.bytes(count: nextHeaderSize)) == nextHeaderCRC else { throw SevenZipError.wrongCRC } return header } }
mit
7d4f737f2a67872a7240becb687bcbda
41.705224
120
0.623416
5.318309
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/Operation.swift
1
13240
#if SWIFT_PACKAGE import cllvm #endif /// Species the behavior that should occur on overflow during mathematical /// operations. public enum OverflowBehavior { /// The result value of the operator is the mathematical result modulo `2^n`, /// where `n` is the bit width of the result. case `default` /// The result value of the operator is a poison value if signed overflow /// occurs. case noSignedWrap /// The result value of the operator is a poison value if unsigned overflow /// occurs. case noUnsignedWrap } /// The condition codes available for integer comparison instructions. public enum IntPredicate { /// Yields `true` if the operands are equal, false otherwise without sign /// interpretation. case equal /// Yields `true` if the operands are unequal, false otherwise without sign /// interpretation. case notEqual /// Interprets the operands as unsigned values and yields true if the first is /// greater than the second. case unsignedGreaterThan /// Interprets the operands as unsigned values and yields true if the first is /// greater than or equal to the second. case unsignedGreaterThanOrEqual /// Interprets the operands as unsigned values and yields true if the first is /// less than the second. case unsignedLessThan /// Interprets the operands as unsigned values and yields true if the first is /// less than or equal to the second. case unsignedLessThanOrEqual /// Interprets the operands as signed values and yields true if the first is /// greater than the second. case signedGreaterThan /// Interprets the operands as signed values and yields true if the first is /// greater than or equal to the second. case signedGreaterThanOrEqual /// Interprets the operands as signed values and yields true if the first is /// less than the second. case signedLessThan /// Interprets the operands as signed values and yields true if the first is /// less than or equal to the second. case signedLessThanOrEqual private static let predicateMapping: [IntPredicate: LLVMIntPredicate] = [ .equal: LLVMIntEQ, .notEqual: LLVMIntNE, .unsignedGreaterThan: LLVMIntUGT, .unsignedGreaterThanOrEqual: LLVMIntUGE, .unsignedLessThan: LLVMIntULT, .unsignedLessThanOrEqual: LLVMIntULE, .signedGreaterThan: LLVMIntSGT, .signedGreaterThanOrEqual: LLVMIntSGE, .signedLessThan: LLVMIntSLT, .signedLessThanOrEqual: LLVMIntSLE, ] /// Retrieves the corresponding `LLVMIntPredicate`. var llvm: LLVMIntPredicate { return IntPredicate.predicateMapping[self]! } } /// The condition codes available for floating comparison instructions. public enum RealPredicate { /// No comparison, always returns `false`. case `false` /// Ordered and equal. case orderedEqual /// Ordered greater than. case orderedGreaterThan /// Ordered greater than or equal. case orderedGreaterThanOrEqual /// Ordered less than. case orderedLessThan /// Ordered less than or equal. case orderedLessThanOrEqual /// Ordered and not equal. case orderedNotEqual /// Ordered (no nans). case ordered /// Unordered (either nans). case unordered /// Unordered or equal. case unorderedEqual /// Unordered or greater than. case unorderedGreaterThan /// Unordered or greater than or equal. case unorderedGreaterThanOrEqual /// Unordered or less than. case unorderedLessThan /// Unordered or less than or equal. case unorderedLessThanOrEqual /// Unordered or not equal. case unorderedNotEqual /// No comparison, always returns `true`. case `true` private static let predicateMapping: [RealPredicate: LLVMRealPredicate] = [ .false: LLVMRealPredicateFalse, .orderedEqual: LLVMRealOEQ, .orderedGreaterThan: LLVMRealOGT, .orderedGreaterThanOrEqual: LLVMRealOGE, .orderedLessThan: LLVMRealOLT, .orderedLessThanOrEqual: LLVMRealOLE, .orderedNotEqual: LLVMRealONE, .ordered: LLVMRealORD, .unordered: LLVMRealUNO, .unorderedEqual: LLVMRealUEQ, .unorderedGreaterThan: LLVMRealUGT, .unorderedGreaterThanOrEqual: LLVMRealUGE, .unorderedLessThan: LLVMRealULT, .unorderedLessThanOrEqual: LLVMRealULE, .unorderedNotEqual: LLVMRealUNE, .true: LLVMRealPredicateTrue, ] /// Retrieves the corresponding `LLVMRealPredicate`. var llvm: LLVMRealPredicate { return RealPredicate.predicateMapping[self]! } } /// `AtomicOrdering` enumerates available memory ordering semantics. /// /// Atomic instructions (`cmpxchg`, `atomicrmw`, `fence`, `atomic load`, and /// `atomic store`) take ordering parameters that determine which other atomic /// instructions on the same address they synchronize with. These semantics are /// borrowed from Java and C++0x, but are somewhat more colloquial. If these /// descriptions aren’t precise enough, check those specs (see spec references /// in the atomics guide). fence instructions treat these orderings somewhat /// differently since they don’t take an address. See that instruction’s /// documentation for details. public enum AtomicOrdering: Comparable { /// A load or store which is not atomic case notAtomic /// Lowest level of atomicity, guarantees somewhat sane results, lock free. /// /// The set of values that can be read is governed by the happens-before /// partial order. A value cannot be read unless some operation wrote it. This /// is intended to provide a guarantee strong enough to model Java’s /// non-volatile shared variables. This ordering cannot be specified for /// read-modify-write operations; it is not strong enough to make them atomic /// in any interesting way. case unordered /// Guarantees that if you take all the operations affecting a specific /// address, a consistent ordering exists. /// /// In addition to the guarantees of unordered, there is a single total order /// for modifications by monotonic operations on each address. All /// modification orders must be compatible with the happens-before order. /// There is no guarantee that the modification orders can be combined to a /// global total order for the whole program (and this often will not be /// possible). The read in an atomic read-modify-write operation (cmpxchg and /// atomicrmw) reads the value in the modification order immediately before /// the value it writes. If one atomic read happens before another atomic read /// of the same address, the later read must see the same value or a later /// value in the address’s modification order. This disallows reordering of /// monotonic (or stronger) operations on the same address. If an address is /// written monotonic-ally by one thread, and other threads monotonic-ally /// read that address repeatedly, the other threads must eventually see the /// write. This corresponds to the C++0x/C1x memory_order_relaxed. case monotonic /// Acquire provides a barrier of the sort necessary to acquire a lock to /// access other memory with normal loads and stores. /// /// In addition to the guarantees of monotonic, a synchronizes-with edge may /// be formed with a release operation. This is intended to model C++’s /// `memory_order_acquire`. case acquire /// Release is similar to Acquire, but with a barrier of the sort necessary to /// release a lock. /// /// In addition to the guarantees of monotonic, if this operation writes a /// value which is subsequently read by an acquire operation, it /// synchronizes-with that operation. (This isn’t a complete description; see /// the C++0x definition of a release sequence.) This corresponds to the /// C++0x/C1x memory_order_release. case release /// provides both an Acquire and a Release barrier (for fences and operations /// which both read and write memory). /// /// This corresponds to the C++0x/C1x memory_order_acq_rel. case acquireRelease /// Provides Acquire semantics for loads and Release semantics for stores. /// /// In addition to the guarantees of acq_rel (acquire for an operation that /// only reads, release for an operation that only writes), there is a global /// total order on all sequentially-consistent operations on all addresses, /// which is consistent with the happens-before partial order and with the /// modification orders of all the affected addresses. Each /// sequentially-consistent read sees the last preceding write to the same /// address in this global order. This corresponds to the C++0x/C1x /// `memory_order_seq_cst` and Java volatile. case sequentiallyConsistent private static let orderingMapping: [AtomicOrdering: LLVMAtomicOrdering] = [ .notAtomic: LLVMAtomicOrderingNotAtomic, .unordered: LLVMAtomicOrderingUnordered, .monotonic: LLVMAtomicOrderingMonotonic, .acquire: LLVMAtomicOrderingAcquire, .release: LLVMAtomicOrderingRelease, .acquireRelease: LLVMAtomicOrderingAcquireRelease, .sequentiallyConsistent: LLVMAtomicOrderingSequentiallyConsistent, ] /// Returns whether the left atomic ordering is strictly weaker than the /// right atomic order. public static func <(lhs: AtomicOrdering, rhs: AtomicOrdering) -> Bool { return lhs.llvm.rawValue < rhs.llvm.rawValue } /// Retrieves the corresponding `LLVMAtomicOrdering`. var llvm: LLVMAtomicOrdering { return AtomicOrdering.orderingMapping[self]! } } /// `AtomicReadModifyWriteOperation` enumerates the kinds of supported atomic /// read-write-modify operations. public enum AtomicReadModifyWriteOperation { /// Set the new value and return the one old /// /// ``` /// *ptr = val /// ``` case xchg /// Add a value and return the old one /// /// ``` /// *ptr = *ptr + val /// ``` case add /// Subtract a value and return the old one /// /// ``` /// *ptr = *ptr - val /// ``` case sub /// And a value and return the old one /// /// ``` /// *ptr = *ptr & val /// ``` case and /// Not-And a value and return the old one /// /// ``` /// *ptr = ~(*ptr & val) /// ``` case nand /// OR a value and return the old one /// /// ``` /// *ptr = *ptr | val /// ``` case or /// Xor a value and return the old one /// /// ``` /// *ptr = *ptr ^ val /// ``` case xor /// Sets the value if it's greater than the original using a signed comparison /// and return the old one. /// /// ``` /// // Using a signed comparison /// *ptr = *ptr > val ? *ptr : val /// ``` case max /// Sets the value if it's Smaller than the original using a signed comparison /// and return the old one. /// /// ``` /// // Using a signed comparison /// *ptr = *ptr < val ? *ptr : val /// ``` case min /// Sets the value if it's greater than the original using an unsigned /// comparison and return the old one. /// /// ``` /// // Using an unsigned comparison /// *ptr = *ptr > val ? *ptr : val /// ``` case umax /// Sets the value if it's greater than the original using an unsigned /// comparison and return the old one. /// /// ``` /// // Using an unsigned comparison /// *ptr = *ptr < val ? *ptr : val /// ``` case umin private static let atomicRMWMapping: [AtomicReadModifyWriteOperation: LLVMAtomicRMWBinOp] = [ .xchg: LLVMAtomicRMWBinOpXchg, .add: LLVMAtomicRMWBinOpAdd, .sub: LLVMAtomicRMWBinOpSub, .and: LLVMAtomicRMWBinOpAnd, .nand: LLVMAtomicRMWBinOpNand, .or: LLVMAtomicRMWBinOpOr, .xor: LLVMAtomicRMWBinOpXor, .max: LLVMAtomicRMWBinOpMax, .min: LLVMAtomicRMWBinOpMin, .umax: LLVMAtomicRMWBinOpUMax, .umin: LLVMAtomicRMWBinOpUMin, ] /// Retrieves the corresponding `LLVMAtomicRMWBinOp`. var llvm: LLVMAtomicRMWBinOp { return AtomicReadModifyWriteOperation.atomicRMWMapping[self]! } } /// Enumerates the dialects of inline assembly LLVM's parsers can handle. public enum InlineAssemblyDialect { /// The dialect of assembly created at Bell Labs by AT&T. /// /// AT&T syntax differs from Intel syntax in a number of ways. Notably: /// /// - The source operand is before the destination operand /// - Immediate operands are prefixed by a dollar-sign (`$`) /// - Register operands are preceded by a percent-sign (`%`) /// - The size of memory operands is determined from the last character of the /// the opcode name. Valid suffixes include `b` for "byte" (8-bit), /// `w` for "word" (16-bit), `l` for "long-word" (32-bit), and `q` for /// "quad-word" (64-bit) memory references case att /// The dialect of assembly created at Intel. /// /// Intel syntax differs from AT&T syntax in a number of ways. Notably: /// /// - The destination operand is before the source operand /// - Immediate and register operands have no prefix. /// - Memory operands are annotated with their sizes. Valid annotations /// include `byte ptr` (8-bit), `word ptr` (16-bit), `dword ptr` (32-bit) and /// `qword ptr` (64-bit). case intel private static let dialectMapping: [InlineAssemblyDialect: LLVMInlineAsmDialect] = [ .att: LLVMInlineAsmDialectATT, .intel: LLVMInlineAsmDialectIntel, ] /// Retrieves the corresponding `LLVMInlineAsmDialect`. var llvm: LLVMInlineAsmDialect { return InlineAssemblyDialect.dialectMapping[self]! } }
mit
db8a754c30fb1e1d1a076145a56a3a6e
37.672515
95
0.712385
4.472776
false
false
false
false
LoopKit/LoopKit
LoopKit/DeviceManager/PumpManager.swift
1
12933
// // PumpManager.swift // Loop // // Copyright © 2018 LoopKit Authors. All rights reserved. // import Foundation import HealthKit public enum PumpManagerResult<T> { case success(T) case failure(PumpManagerError) } public protocol PumpManagerStatusObserver: AnyObject { func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) } public enum BolusActivationType: String, Codable { case manualNoRecommendation case manualRecommendationAccepted case manualRecommendationChanged case automatic public var isAutomatic: Bool { self == .automatic } static public func activationTypeFor(recommendedAmount: Double?, bolusAmount: Double) -> BolusActivationType { guard let recommendedAmount = recommendedAmount else { return .manualNoRecommendation } return recommendedAmount =~ bolusAmount ? .manualRecommendationAccepted : .manualRecommendationChanged } } public protocol PumpManagerDelegate: DeviceManagerDelegate, PumpManagerStatusObserver { func pumpManagerBLEHeartbeatDidFire(_ pumpManager: PumpManager) /// Queries the delegate as to whether Loop requires the pump to provide its own periodic scheduling /// via BLE. /// This is the companion to `PumpManager.setMustProvideBLEHeartbeat(_:)` func pumpManagerMustProvideBLEHeartbeat(_ pumpManager: PumpManager) -> Bool /// Informs the delegate that the manager is deactivating and should be deleted func pumpManagerWillDeactivate(_ pumpManager: PumpManager) /// Informs the delegate that the hardware this PumpManager has been reporting for has been replaced. func pumpManagerPumpWasReplaced(_ pumpManager: PumpManager) /// Triggered when pump model changes. With a more formalized setup flow (which requires a successful model fetch), /// this delegate method could go away. func pumpManager(_ pumpManager: PumpManager, didUpdatePumpRecordsBasalProfileStartEvents pumpRecordsBasalProfileStartEvents: Bool) /// Reports an error that should be surfaced to the user func pumpManager(_ pumpManager: PumpManager, didError error: PumpManagerError) /// This should be called any time the PumpManager synchronizes with the pump, even if there are no new doses in the log, as changes to lastReconciliation /// indicate we can trust insulin delivery status up until that point, even if there are no new doses. /// For pumps whose only source of dosing adjustments is Loop, lastReconciliation should be reflective of the last time we received telemetry from the pump. /// For pumps with a user interface and dosing history capabilities, lastReconciliation should be reflective of the last time we reconciled fully with pump history, and know /// that we have accounted for any external doses. It is possible for the pump to report reservoir data beyond the date of lastReconciliation, and Loop can use it for /// calculating IOB. func pumpManager(_ pumpManager: PumpManager, hasNewPumpEvents events: [NewPumpEvent], lastReconciliation: Date?, completion: @escaping (_ error: Error?) -> Void) func pumpManager(_ pumpManager: PumpManager, didReadReservoirValue units: Double, at date: Date, completion: @escaping (_ result: Result<(newValue: ReservoirValue, lastValue: ReservoirValue?, areStoredValuesContinuous: Bool), Error>) -> Void) func pumpManager(_ pumpManager: PumpManager, didAdjustPumpClockBy adjustment: TimeInterval) func pumpManagerDidUpdateState(_ pumpManager: PumpManager) func startDateToFilterNewPumpEvents(for manager: PumpManager) -> Date /// Indicates the system time offset from a trusted time source. If the return value is added to the system time, the result is the trusted time source value. If the trusted time source is earlier than the system time, the return value is negative. var detectedSystemTimeOffset: TimeInterval { get } } public protocol PumpManager: DeviceManager { /// The maximum number of scheduled basal rates in a single day supported by the pump. Used during onboarding by therapy settings. static var onboardingMaximumBasalScheduleEntryCount: Int { get } /// All user-selectable basal rates, in Units per Hour. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedBasalRates: [Double] { get } /// All user-selectable bolus volumes, in Units. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedBolusVolumes: [Double] { get } /// All user-selectable maximum bolus volumes, in Units. Must be non-empty. Used during onboarding by therapy settings. static var onboardingSupportedMaximumBolusVolumes: [Double] { get } /// The queue on which PumpManagerDelegate methods are called /// Setting to nil resets to a default provided by the manager var delegateQueue: DispatchQueue! { get set } /// Rounds a basal rate in U/hr to a rate supported by this pump. /// /// - Parameters: /// - unitsPerHour: A desired rate of delivery in Units per Hour /// - Returns: The rounded rate of delivery in Units per Hour. The rate returned should not be larger than the passed in rate. func roundToSupportedBasalRate(unitsPerHour: Double) -> Double /// Rounds a bolus volume in Units to a volume supported by this pump. /// /// - Parameters: /// - units: A desired volume of delivery in Units /// - Returns: The rounded bolus volume in Units. The volume returned should not be larger than the passed in rate. func roundToSupportedBolusVolume(units: Double) -> Double /// All user-selectable basal rates, in Units per Hour. Must be non-empty. var supportedBasalRates: [Double] { get } /// All user-selectable bolus volumes, in Units. Must be non-empty. var supportedBolusVolumes: [Double] { get } /// All user-selectable bolus volumes for setting the maximum allowed bolus, in Units. Must be non-empty. var supportedMaximumBolusVolumes: [Double] { get } /// The maximum number of scheduled basal rates in a single day supported by the pump var maximumBasalScheduleEntryCount: Int { get } /// The basal schedule duration increment, beginning at midnight, supported by the pump var minimumBasalScheduleEntryDuration: TimeInterval { get } /// The primary client receiving notifications about the pump lifecycle /// All delegate methods are called on `delegateQueue` var pumpManagerDelegate: PumpManagerDelegate? { get set } /// Whether the PumpManager provides DoseEntry values for scheduled basal delivery. If false, Loop will use the basal schedule to infer normal basal delivery during times not overridden by: /// - Temporary basal delivery /// - Suspend/Resume pairs /// - Rewind/Prime pairs var pumpRecordsBasalProfileStartEvents: Bool { get } /// The maximum reservoir volume of the pump var pumpReservoirCapacity: Double { get } /// The time of the last sync with the pump's event history, or reservoir, or last status check if pump does not provide history. var lastSync: Date? { get } /// The most-recent status var status: PumpManagerStatus { get } /// Adds an observer of changes in PumpManagerStatus /// /// Observers are held by weak reference. /// /// - Parameters: /// - observer: The observing object /// - queue: The queue on which the observer methods should be called func addStatusObserver(_ observer: PumpManagerStatusObserver, queue: DispatchQueue) /// Removes an observer of changes in PumpManagerStatus /// /// Since observers are held weakly, calling this method is not required when the observer is deallocated /// /// - Parameter observer: The observing object func removeStatusObserver(_ observer: PumpManagerStatusObserver) /// Ensure that the pump's data (reservoir/events) is up to date. If not, fetch it. /// The PumpManager should call the completion block with the date of last sync with the pump, nil if no sync has occurred func ensureCurrentPumpData(completion: ((_ lastSync: Date?) -> Void)?) /// Loop calls this method when the current environment requires the pump to provide its own periodic /// scheduling via BLE. /// The manager may choose to still enable its own heartbeat even if `mustProvideBLEHeartbeat` is false func setMustProvideBLEHeartbeat(_ mustProvideBLEHeartbeat: Bool) /// Returns a dose estimator for the current bolus, if one is in progress func createBolusProgressReporter(reportingOn dispatchQueue: DispatchQueue) -> DoseProgressReporter? /// Returns the estimated time for the bolus amount to be delivered func estimatedDuration(toBolus units: Double) -> TimeInterval /// Send a bolus command and handle the result /// /// - Parameters: /// - units: The number of units to deliver /// - automatic: Whether the dose was triggered automatically as opposed to commanded by user /// - completion: A closure called after the command is complete /// - error: An optional error describing why the command failed func enactBolus(units: Double, activationType: BolusActivationType, completion: @escaping (_ error: PumpManagerError?) -> Void) /// Cancels the current, in progress, bolus. /// /// - Parameters: /// - completion: A closure called after the command is complete /// - result: A DoseEntry containing the actual delivery amount of the canceled bolus, nil if canceled bolus information is not available, or an error describing why the command failed. func cancelBolus(completion: @escaping (_ result: PumpManagerResult<DoseEntry?>) -> Void) /// Send a temporary basal rate command and handle the result /// /// - Parameters: /// - unitsPerHour: The temporary basal rate to set /// - duration: The duration of the temporary basal rate. If you pass in a duration of 0, that cancels any currently running Temp Basal /// - completion: A closure called after the command is complete /// - error: An optional error describing why the command failed func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval, completion: @escaping (_ error: PumpManagerError?) -> Void) /// Send a command to the pump to suspend delivery /// /// - Parameters: /// - completion: A closure called after the command is complete /// - error: An error describing why the command failed func suspendDelivery(completion: @escaping (_ error: Error?) -> Void) /// Send a command to the pump to resume delivery /// /// - Parameters: /// - completion: A closure called after the command is complete /// - error: An error describing why the command failed func resumeDelivery(completion: @escaping (_ error: Error?) -> Void) /// Sync the schedule of basal rates to the pump, annotating the result with the proper time zone. /// /// - Precondition: /// - `scheduleItems` must not be empty. /// /// - Parameters: /// - scheduleItems: The items comprising the basal rate schedule /// - completion: A closure called after the command is complete /// - result: A BasalRateSchedule or an error describing why the command failed func syncBasalRateSchedule(items scheduleItems: [RepeatingScheduleValue<Double>], completion: @escaping (_ result: Result<BasalRateSchedule, Error>) -> Void) /// Sync the delivery limits for basal rate and bolus. If the pump does not support setting max bolus or max basal rates, the completion should be called with success including the provided delivery limits. /// /// - Parameters: /// - deliveryLimits: The delivery limits /// - completion: A closure called after the command is complete /// - result: The delivery limits set or an error describing why the command failed func syncDeliveryLimits(limits deliveryLimits: DeliveryLimits, completion: @escaping (_ result: Result<DeliveryLimits, Error>) -> Void) } public extension PumpManager { func roundToSupportedBasalRate(unitsPerHour: Double) -> Double { return supportedBasalRates.filter({$0 <= unitsPerHour}).max() ?? 0 } func roundToSupportedBolusVolume(units: Double) -> Double { return supportedBolusVolumes.filter({$0 <= units}).max() ?? 0 } /// Convenience wrapper for notifying the delegate of deactivation on the delegate queue /// /// - Parameters: /// - completion: A closure called from the delegate queue after the delegate is called func notifyDelegateOfDeactivation(completion: @escaping () -> Void) { delegateQueue.async { self.pumpManagerDelegate?.pumpManagerWillDeactivate(self) completion() } } }
mit
e0853338a8c0ca298f93de40cdb61352
49.913386
252
0.724018
5.123613
false
false
false
false
OpenStreetMap-Monitoring/OsMoiOs
iOsmo/AuthViewController.swift
2
7052
// // AuthViewController.swift // iOsmo // // Created by Olga Grineva on 22/12/14. // Copyright (c) 2014 Olga Grineva. All rights reserved. // import UIKit enum SignActions: Int { case SignIn = 1 //default case SignUp = 2 } protocol AuthResultProtocol { func succesfullLoginWithToken (_ controller: AuthViewController, info : AuthInfo) -> Void func loginCancelled (_ controller: AuthViewController) -> Void } open class AuthViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate { let log = LogQueue.sharedLogQueue @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passField: UITextField! @IBOutlet weak var nickField: UITextField! @IBOutlet weak var pass2Field: UITextField! @IBOutlet weak var signButton: UIButton! @IBOutlet weak var actButton: UIButton! @IBOutlet weak var forgotButton: UIButton! @IBOutlet weak var signLabel: UILabel! @IBOutlet weak var registerView: UIView! @IBOutlet weak var signToRegConstraint: NSLayoutConstraint! @IBOutlet weak var signToPassConstraint: NSLayoutConstraint! var signAction: SignActions = SignActions.SignIn @IBAction func OnCancel(_ sender: AnyObject) { delegate?.loginCancelled(self) } var delegate: AuthResultProtocol? override open func viewDidLoad() { super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Смена режима формы с логина на регистрацию и обратоно @IBAction func setSignMode(_ sender: UIButton) { if signAction == SignActions.SignIn { signAction = SignActions.SignUp } else { signAction = SignActions.SignIn } switch signAction { case SignActions.SignIn: signButton.setTitle(NSLocalizedString("Register", comment: "Register label"), for: .normal) actButton.setTitle(NSLocalizedString("Sign-In", comment: "Sign-in label"), for: .normal) signLabel.text = NSLocalizedString("Sign-In", comment: "Sign-in label") signToRegConstraint.priority = UILayoutPriority(rawValue: 500) signToPassConstraint.priority = UILayoutPriority(rawValue: 999) registerView.isHidden = true forgotButton.isHidden = false default: signButton.setTitle(NSLocalizedString("Sign-In", comment: "Sign-in label"), for: .normal) actButton.setTitle(NSLocalizedString("Register", comment: "Register label"), for: .normal) signLabel.text = NSLocalizedString("Register", comment: "Register label") signToRegConstraint.priority = UILayoutPriority(rawValue: 999) signToPassConstraint.priority = UILayoutPriority(rawValue: 500) registerView.isHidden = false forgotButton.isHidden = true } } @IBAction func signAction(_ sender: UIButton) { if (signAction == SignActions.SignUp ) { if (passField.text != pass2Field.text) { self.alert("OsMo registration", message: NSLocalizedString("Passwords didn't match!", comment: "Passwords didn't match!")) return } if (nickField.text == "") { self.alert("OsMo registration", message: NSLocalizedString("Enter nick!", comment: "Enter nick!")) return } } let device = SettingsManager.getKey(SettingKeys.device)! as String let url = URL(string: signAction == SignActions.SignIn ? "https://\(URLs.osmoDomain)/signin?" : "https://api2.osmo.mobi/signup?") let session = URLSession.shared; var urlReq = URLRequest(url: url!); var requestBody:String = "key=\(device)&email=\(emailField.text!)&password=\(passField.text!)" if (signAction == SignActions.SignUp) { requestBody = "\(requestBody)&nick=\(nickField.text!)" } urlReq.httpMethod = "POST" urlReq.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData urlReq.httpBody = requestBody.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let task = session.dataTask(with: urlReq as URLRequest) {(data, response, error) in var res : NSDictionary = [:] guard let data = data, let _:URLResponse = response, error == nil else { print("error: on send post request") LogQueue.sharedLogQueue.enqueue("error: on send post request") return } //let dataStr = NSString(data: data, encoding: String.Encoding.utf8.rawValue) do { let jsonDict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers); res = (jsonDict as? NSDictionary)! print(res) if let user = res["nick"] { DispatchQueue.main.async { self.delegate?.succesfullLoginWithToken(self, info: AuthInfo(accountName: user as! String, key: "")) } } else { if let error = res["error_description"] { DispatchQueue.main.async { self.alert("OsMo registration", message: error as! String ) } } } } catch { print("error serializing JSON from POST") LogQueue.sharedLogQueue.enqueue("error serializing JSON from POST") return } } task.resume() } @IBAction func forgotPassword(_ sender: UIButton) { UIApplication.shared.open(URL(string: "https://osmo.mobi/forgot?utm_campaign=OsMo.App&utm_source=iOsMo&utm_term=forgot")!, options: [:], completionHandler: nil) } func alert(_ title: String, message: String) { let myAlert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert) myAlert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"OK"), style: .default, handler: nil)) self.present(myAlert, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK UITextFieldDelegate public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
gpl-3.0
8c4d5dd0cb0a7881c5c1b4e65c503347
38.145251
168
0.619238
5.092297
false
false
false
false
leonereveel/Moya
Source/Moya.swift
1
6075
import Foundation import Result /// Closure to be executed when a request has completed. public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> () /// Closure to be executed when progress changes. public typealias ProgressBlock = (progress: ProgressResponse) -> Void public struct ProgressResponse { public let totalBytes: Int64 public let bytesExpected: Int64 public let response: Response? init(totalBytes: Int64 = 0, bytesExpected: Int64 = 0, response: Response? = nil) { self.totalBytes = totalBytes self.bytesExpected = bytesExpected self.response = response } public var progress: Double { return bytesExpected > 0 ? min(Double(totalBytes) / Double(bytesExpected), 1.0) : 1.0 } public var completed: Bool { return totalBytes >= bytesExpected && response != nil } } /// Request provider class. Requests should be made through this class only. public class MoyaProvider<Target: TargetType> { /// Closure that defines the endpoints for the provider. public typealias EndpointClosure = Target -> Endpoint<Target> /// Closure that decides if and what request should be performed public typealias RequestResultClosure = Result<NSURLRequest, Moya.Error> -> Void /// Closure that resolves an `Endpoint` into a `RequestResult`. public typealias RequestClosure = (Endpoint<Target>, RequestResultClosure) -> Void /// Closure that decides if/how a request should be stubbed. public typealias StubClosure = Target -> Moya.StubBehavior public let endpointClosure: EndpointClosure public let requestClosure: RequestClosure public let stubClosure: StubClosure public let manager: Manager /// A list of plugins /// e.g. for logging, network activity indicator or credentials public let plugins: [PluginType] public let trackInflights: Bool public internal(set) var inflightRequests = Dictionary<Endpoint<Target>, [Moya.Completion]>() /// Initializes a provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = MoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false) { self.endpointClosure = endpointClosure self.requestClosure = requestClosure self.stubClosure = stubClosure self.manager = manager self.plugins = plugins self.trackInflights = trackInflights } /// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`. public func endpoint(token: Target) -> Endpoint<Target> { return endpointClosure(token) } /// Designated request-making method. Returns a `Cancellable` token to cancel the request later. public func request(target: Target, completion: Moya.Completion) -> Cancellable { return self.request(target, queue: nil, completion: completion) } /// Designated request-making method with queue option. Returns a `Cancellable` token to cancel the request later. public func request(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> Cancellable { return requestNormal(target, queue: queue, progress: progress, completion: completion) } /// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method. /// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override. func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { let cancellableToken = CancellableToken { } notifyPluginsOfImpendingStub(request, target: target) let plugins = self.plugins let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins) switch stubBehavior { case .Immediate: stub() case .Delayed(let delay): let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC)) let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset) dispatch_after(killTime, dispatch_get_main_queue()) { stub() } case .Never: fatalError("Method called to stub request when stubbing is disabled.") } return cancellableToken } } /// Mark: Stubbing public extension MoyaProvider { // Swift won't let us put the StubBehavior enum inside the provider class, so we'll // at least add some class functions to allow easy access to common stubbing closures. public final class func NeverStub(_: Target) -> Moya.StubBehavior { return .Never } public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior { return .Immediate } public final class func DelayedStub(seconds: NSTimeInterval) -> (Target) -> Moya.StubBehavior { return { _ in return .Delayed(seconds: seconds) } } } public func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> Result<Moya.Response, Moya.Error> { switch (response, data, error) { case let (.Some(response), data, .None): let response = Moya.Response(statusCode: response.statusCode, data: data ?? NSData(), response: response) return .Success(response) case let (_, _, .Some(error)): let error = Moya.Error.Underlying(error) return .Failure(error) default: let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil)) return .Failure(error) } }
mit
5bde80355741ce01de40aca14cba05f8
40.609589
171
0.694486
4.995888
false
false
false
false
tapglue/ios_sample
TapglueSample/LoginSignInVC.swift
1
3217
// // LoginSignInVC.swift // TapglueSample // // Created by Özgür Celebi on 14/12/15. // Copyright © 2015 Özgür Celebi. All rights reserved. // import UIKit import Tapglue class LoginSignInVC: UIViewController { @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate override func viewDidLoad() { super.viewDidLoad() } override func viewWillDisappear(animated: Bool) { // Show navigationBar again when view disappears self.navigationController?.navigationBarHidden = false } @IBAction func signInButtonPressed(sender: UIButton) { // If textFields have more then 2 characters, begin Tapglue login if userNameTextField.text?.characters.count > 2 && passwordTextField.text?.characters.count > 2 { let username = userNameTextField.text! let password = passwordTextField.text! // NewSDK appDel.rxTapglue.loginUser(username, password: password).subscribe({ (event) in switch event { case .Next(let user): print("User logged in: \(user)") case .Error(let error): let err = error as! TapglueError switch err.code! { case 1001: let alertController = UIAlertController(title: "Error", message: "User does not exist.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) case 0: let alertController = UIAlertController(title: "Error", message: "Wrong password.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) default: "Error code was not added to switch" } case .Completed: self.navigationController?.popToRootViewControllerAnimated(false) } }).addDisposableTo(self.appDel.disposeBag) } else { let alertController = UIAlertController(title: "Not enough characters", message: "Username and Password must be at least 3 characters.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } }
apache-2.0
8240f7f009d78331e008eb70a7f1cc1a
41.263158
125
0.576899
6.014981
false
false
false
false
grandiere/box
box/Model/GridVisor/Camera/MGridVisorCamera.swift
1
5900
import UIKit import AVFoundation import ImageIO class MGridVisorCamera:NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { private var captureSession:AVCaptureSession? private weak var controller:CGridVisor! private weak var videoDataOutput:AVCaptureVideoDataOutput? private weak var captureDeviceInput:AVCaptureDeviceInput? private let queueCamera:DispatchQueue private let queueOutput:DispatchQueue private let kDevicePosition:AVCaptureDevicePosition = AVCaptureDevicePosition.back private let kMediaType:String = AVMediaTypeVideo private let kSessionPreset:String = AVCaptureSessionPreset640x480 private let kVideoGravity:String = AVLayerVideoGravityResizeAspect private let kVideoCodec:String = AVVideoCodecJPEG private let kQueueCameraLabel:String = "visorCameraQueue" private let kQueueOutputLabel:String = "visorOutputQueue" private let kImageOrientationUp:Int32 = 6 init(controller:CGridVisor) { self.controller = controller queueCamera = DispatchQueue( label:kQueueCameraLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency:DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global(qos:DispatchQoS.QoSClass.background)) queueOutput = DispatchQueue( label:kQueueOutputLabel, qos:DispatchQoS.background, attributes:DispatchQueue.Attributes(), autoreleaseFrequency:DispatchQueue.AutoreleaseFrequency.inherit, target:DispatchQueue.global(qos:DispatchQoS.QoSClass.background)) super.init() askAuthorization() } deinit { cleanSession() } //MARK: private private func askAuthorization() { AVCaptureDevice.requestAccess(forMediaType:kMediaType) { [weak self] (granted:Bool) in if granted { self?.queueCamera.async { [weak self] in self?.startSession() } } else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoAuth", comment:"") VAlert.messageOrange(message:error) } } } private func startSession() { let captureSession:AVCaptureSession = AVCaptureSession() captureSession.sessionPreset = kSessionPreset self.captureSession = captureSession var captureDevice:AVCaptureDevice? if #available(iOS 10.0, *) { captureDevice = AVCaptureDevice.defaultDevice( withDeviceType:AVCaptureDeviceType.builtInWideAngleCamera, mediaType:kMediaType, position:kDevicePosition) } else { let devices:[Any] = AVCaptureDevice.devices( withMediaType:kMediaType) for device:Any in devices { guard let capture:AVCaptureDevice = device as? AVCaptureDevice else { continue } if capture.position == kDevicePosition { captureDevice = capture break } } } guard let foundCaptureDevice:AVCaptureDevice = captureDevice else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoCaptureDevice", comment:"") VAlert.messageOrange(message:error) return } let captureDeviceInput:AVCaptureDeviceInput do { try captureDeviceInput = AVCaptureDeviceInput( device:foundCaptureDevice) } catch let error { print(error.localizedDescription) return } self.captureDeviceInput = captureDeviceInput captureSession.addInput(captureDeviceInput) let videoDataOutput:AVCaptureVideoDataOutput = AVCaptureVideoDataOutput() videoDataOutput.videoSettings = [String(kCVPixelBufferPixelFormatTypeKey) : Int(kCVPixelFormatType_32BGRA) as NSNumber] videoDataOutput.setSampleBufferDelegate( self, queue:queueOutput) self.videoDataOutput = videoDataOutput if captureSession.canAddOutput(videoDataOutput) { captureSession.addOutput(videoDataOutput) captureSession.startRunning() } else { let error:String = NSLocalizedString("MGridVisorCamera_errorNoOutput", comment:"") VAlert.messageOrange(message:error) } } //MARK: public func cleanSession() { captureSession?.stopRunning() captureSession?.removeInput(captureDeviceInput) captureSession?.removeOutput(videoDataOutput) } //MARK: captureOutput delegate func captureOutput(_ captureOutput:AVCaptureOutput!, didOutputSampleBuffer sampleBuffer:CMSampleBuffer!, from connection:AVCaptureConnection!) { guard let pixelBuffer:CVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } let ciimage:CIImage = CIImage(cvImageBuffer:pixelBuffer) let imageOriented:CIImage = ciimage.applyingOrientation(kImageOrientationUp) controller.modelRender?.updateCameraImage(cIImage:imageOriented) } }
mit
8efd206ad97549839ee45958246366ee
30.550802
146
0.596949
6.54102
false
false
false
false
ffreling/pigeon
Pigeon/Pigeon/PAppDelegate.swift
1
1017
// // AppDelegate.swift // Pigeon // // Created by Fabien on 2014-10-18. // Copyright (c) 2014 Fabien. All rights reserved. // import Cocoa import AppKit @NSApplicationMain class PAppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow! var pigeonStatus: NSStatusItem! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application activateStatusMenu() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func activateStatusMenu() { var bar = NSStatusBar.systemStatusBar() // self.pigeonStatus = bar.statusItemWithLength(NSVariableStatusItemLength) // // self.pigeonStatus.title = "Pigeon" // self.pigeonStatus.highlightMode = true // self.pigeonStatus.action = "self.openBrowser" } func openBrowser(sender: AnyObject?) { NSWorkspace.sharedWorkspace().openURL(NSURL(string: "https://www.fastmail.fm")!) } }
bsd-2-clause
7b24d4b3ac1ebab76d1c09c36df6daa9
22.651163
84
0.73058
4.273109
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/SandboxUpdateProductRequest.swift
1
1591
// // SandboxUpdateProductRequest.swift // UberGoCore // // Created by Nghia Tran on 6/20/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Alamofire import RxSwift import Unbox struct SandboxUpdateProductRequestParam: Parameter { public var productID: String? public var surgeMultiplier: Float? public var driversAvailable: Bool? func toDictionary() -> [String: Any] { var dict: [String: Any] = [:] if let surgeMultiplier = self.surgeMultiplier { dict["surge_multiplier"] = surgeMultiplier } if let driversAvailable = self.driversAvailable { dict["drivers_available"] = driversAvailable } return dict } } final class SandboxUpdateProductRequest: Request { // Type typealias Element = Void // Endpoint var endpoint: String { guard let param = self.param as? SandboxUpdateProductRequestParam else { return Constants.UberAPI.SandboxUpdateProduct } return Constants.UberAPI.SandboxUpdateProduct.replacingOccurrences(of: ":id", with: param.productID!) } // HTTP var httpMethod: HTTPMethod { return .put } // Param var param: Parameter? { return self._param } fileprivate var _param: SandboxUpdateProductRequestParam // MARK: - Init init(_ param: SandboxUpdateProductRequestParam) { self._param = param } // MARK: - Decode func decode(data: Any) throws -> Element? { return nil } }
mit
1af929416bd60bed63a08a2d5c541d30
25.065574
96
0.622642
4.907407
false
false
false
false
uptech/Constraid
Sources/Constraid/ProxyExtensions/ConstraidProxy+FlushWithMargins.swift
1
7323
// We don't conditional import AppKit like normal here because AppKit Autolayout doesn't support // the margin attributes that UIKit does. And of course this file isn't included in the MacOS // build target. #if os(iOS) import UIKit extension ConstraidProxy { /** Constrains the object's leading edge to the leading margin of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withLeadingMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withLeadingMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's trailing edge to the trailing margin of `item` - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to trailing margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the trailing margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTrailingMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTrailingMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top edge to the top margin of `item` - parameter itemB: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTopMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTopMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's bottom edge to the bottom margin of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to bottom margin of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the bottom margin of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withBottomMarginOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withBottomMarginOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top & bottom edge to the top & bottom margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top & bottom margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top & bottom margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withVerticalMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withVerticalMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading & trailing edge to the leading & trailing margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading & trailing margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading & trailing margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withHorizontalMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withHorizontalMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading, trailing, top, & bottom edge to the leading, trailing, top & bottom margins of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading, trailing, top & bottom margins of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading, trailing, top and bottom margins of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withMarginsOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withMarginsOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } } #endif
mit
7a1aab2dd2a808093950e04516ad7f0f
51.683453
201
0.720606
5.113827
false
false
false
false
BenEmdon/swift-algorithm-club
Binary Search Tree/Solution 2/BinarySearchTree.swift
1
2911
/* Binary search tree using value types The tree is immutable. Any insertions or deletions will create a new tree. */ public enum BinarySearchTree<T: Comparable> { case Empty case Leaf(T) indirect case Node(BinarySearchTree, T, BinarySearchTree) /* How many nodes are in this subtree. Performance: O(n). */ public var count: Int { switch self { case .Empty: return 0 case .Leaf: return 1 case let .Node(left, _, right): return left.count + 1 + right.count } } /* Distance of this node to its lowest leaf. Performance: O(n). */ public var height: Int { switch self { case .Empty: return 0 case .Leaf: return 1 case let .Node(left, _, right): return 1 + max(left.height, right.height) } } /* Inserts a new element into the tree. Performance: runs in O(h) time, where h is the height of the tree. */ public func insert(newValue: T) -> BinarySearchTree { switch self { case .Empty: return .Leaf(newValue) case .Leaf(let value): if newValue < value { return .Node(.Leaf(newValue), value, .Empty) } else { return .Node(.Empty, value, .Leaf(newValue)) } case .Node(let left, let value, let right): if newValue < value { return .Node(left.insert(newValue), value, right) } else { return .Node(left, value, right.insert(newValue)) } } } /* Finds the "highest" node with the specified value. Performance: runs in O(h) time, where h is the height of the tree. */ public func search(x: T) -> BinarySearchTree? { switch self { case .Empty: return nil case .Leaf(let y): return (x == y) ? self : nil case let .Node(left, y, right): if x < y { return left.search(x) } else if y < x { return right.search(x) } else { return self } } } public func contains(x: T) -> Bool { return search(x) != nil } /* Returns the leftmost descendent. O(h) time. */ public func minimum() -> BinarySearchTree { var node = self var prev = node while case let .Node(next, _, _) = node { prev = node node = next } if case .Leaf = node { return node } return prev } /* Returns the rightmost descendent. O(h) time. */ public func maximum() -> BinarySearchTree { var node = self var prev = node while case let .Node(_, _, next) = node { prev = node node = next } if case .Leaf = node { return node } return prev } } extension BinarySearchTree: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .Empty: return "." case .Leaf(let value): return "\(value)" case .Node(let left, let value, let right): return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))" } } }
mit
09c70a0b0466fa4193de125b024e42da
23.057851
82
0.591893
3.886515
false
false
false
false
yangalex/WeMeet
WeMeet/View Controllers/LoginViewController.swift
1
3527
// // LoginViewController.swift // WeMeet // // Created by Alexandre Yang on 8/9/15. // Copyright (c) 2015 Alex Yang. All rights reserved. // import UIKit import SVProgressHUD class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signUpButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // check if user is already logged in // if let user = PFUser.currentUser() { // if user.isAuthenticated() { // performSegueWithIdentifier("SignInSegue", sender: nil) // } // } let viewTapGesture = UITapGestureRecognizer(target: self, action: "dismissTextFields") viewTapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(viewTapGesture) setUpTextFields() setUpButton() } func dismissTextFields() { if usernameTextField.isFirstResponder() { usernameTextField.resignFirstResponder() } else if passwordTextField.isFirstResponder() { passwordTextField.resignFirstResponder() } } func setUpTextFields() { let bottomBorder = CALayer() bottomBorder.frame = CGRectMake(0, usernameTextField.frame.height-1, usernameTextField.frame.width, 1.0) bottomBorder.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.5).CGColor usernameTextField.tintColor = UIColor.whiteColor() passwordTextField.tintColor = UIColor.whiteColor() usernameTextField.layer.addSublayer(bottomBorder) usernameTextField.delegate = self passwordTextField.delegate = self } func setUpButton() { loginButton.backgroundColor = UIColor.whiteColor() signUpButton.backgroundColor = UIColor.whiteColor() } @IBAction func signInPressed(sender: UIButton) { let usernameText = usernameTextField.text let passwordText = passwordTextField.text SVProgressHUD.show() UIApplication.sharedApplication().beginIgnoringInteractionEvents() PFUser.logInWithUsernameInBackground(usernameText, password: passwordText) { (user: PFUser?, error: NSError?) in if user != nil { self.performSegueWithIdentifier("SignInSegue", sender: nil) } else { AlertControllerHelper.displayErrorController(self, withMessage: error!.localizedDescription) } SVProgressHUD.dismiss() UIApplication.sharedApplication().endIgnoringInteractionEvents() } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == usernameTextField { passwordTextField.becomeFirstResponder() } else if textField == passwordTextField { signInPressed(loginButton) } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
42ac287960cfc63eec2d709bf73f0415
32.273585
120
0.649277
5.810544
false
false
false
false
kosicki123/eidolon
Kiosk/Bid Fulfillment/BalancedManager.swift
1
1323
import UIKit import balanced_ios class BalancedManager: NSObject { let marketplace: String dynamic var cardName = "" dynamic var cardLastDigits = "" dynamic var cardToken = "" init(marketplace: String) { self.marketplace = marketplace } func registerCard(digits: String, month: Int, year: Int) -> RACSignal { let registeredCardSignal = RACSubject() let card = BPCard(number: digits, expirationMonth: UInt(month), expirationYear: UInt(year), optionalFields: nil) let balanced = Balanced(marketplaceURI:"/v1/marketplaces/\(marketplace)") balanced.tokenizeCard(card, onSuccess: { (dict) -> Void in if let data = dict["data"] as? [String: AnyObject] { // TODO: We don't capture names if let uri = data["uri"] as? String { self.cardToken = uri } if let last4 = data["last_four"] as? String { self.cardLastDigits = last4 } self.cardName = data["name"] as? String ?? "" registeredCardSignal.sendNext(self) } }) { (error) -> Void in registeredCardSignal.sendError(error) logger.error("Error tokenizing via balanced: \(error)") } return registeredCardSignal } }
mit
28060bcb95afbba6e699e8126a05a509
27.148936
120
0.588813
4.546392
false
false
false
false
daniel-barros/TV-Calendar
TraktKit/Common/TraktTrendingShow.swift
1
625
// // TraktTrendingShow.swift // TraktKit // // Created by Maximilian Litteral on 4/13/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktTrendingShow: TraktProtocol { // Extended: Min public let watchers: Int public let show: TraktShow // Initialize public init?(json: RawJSON?) { guard let json = json, let watchers = json["watchers"] as? Int, let show = TraktShow(json: json["show"] as? RawJSON) else { return nil } self.watchers = watchers self.show = show } }
gpl-3.0
f7bbc7df96fa99518b0467e137103153
23
84
0.608974
4.16
false
false
false
false
svbeemen/Eve
Eve/Eve/CalendarClass.swift
1
4900
// // CalendarClass.swift // Eve // // Created by Sangeeta van Beemen on 23/06/15. // Copyright (c) 2015 Sangeeta van Beemen. All rights reserved. // import Foundation class CalendarClass { var currentDate: NSDate var currentCalendar: NSCalendar var calenderDates: [[CycleDate]] var selectedDates: [CycleDate] var menstruationCycle: MenstrualCycle! var firstCalendarDate: NSDate! var lastCalendarDate: NSDate! init() { self.currentDate = NSDate() self.currentCalendar = NSCalendar.currentCalendar() self.calenderDates = [[CycleDate]]() self.selectedDates = [CycleDate]() self.firstCalendarDate = self.currentDate.firstYearDate().dateBySubtractingYears(1) self.lastCalendarDate = self.currentDate.lastYearDate().dateByAddingYears(1) self.menstruationCycle = MenstrualCycle(currentDate: self.currentDate, endPredictionDate: self.lastCalendarDate) } // Calculate dates for calendar func getDates() { let startCalendarDate = CycleDate(date: self.firstCalendarDate) let endCalendarDate = CycleDate(date: self.lastCalendarDate) self.calenderDates = [[CycleDate]]() while startCalendarDate.date.isEarlierThanOrEqualTo(endCalendarDate.date) { let daysInMonth = startCalendarDate.date.daysInMonth() var datesInMonth = [CycleDate]() for _ in 0 ..< daysInMonth { let date = CycleDate(date: startCalendarDate.date) datesInMonth.append(date) startCalendarDate.date = startCalendarDate.date.dateByAddingDays(1) } self.calenderDates.append(datesInMonth) } } // Adds and deletes selected date to menstruation array. func setSelectedDate(selectedDate: CycleDate) { if self.selectedDates.contains(selectedDate) { self.selectedDates = self.selectedDates.filter( {$0 != selectedDate} ) selectedDate.type = "" } else { self.selectedDates.append(selectedDate) selectedDate.type = "menstruation" } } // Calls function to calculate cycle in menstrualCycleClass // Sets the type date of the predicted dates to the calendar dates. func setDateTypes() { let datesTypes = self.menstruationCycle.predictedCycleDates + self.menstruationCycle.pastMenstruationDates + self.menstruationCycle.pastCycleDates // reset date type for months in calenderDates { for days in months { days.type = "" } } // set date type for dates in datesTypes { for months in self.calenderDates { for calandardays in months { if currentCalendar.isDate(dates.date, inSameDayAsDate: calandardays.date) { calandardays.type = dates.type } } } } } // Retrieve selected date and set type. func getSelectedDate() { // reset date type for months in calenderDates { for days in months { days.type = "" } } // set selected date type for dates in self.selectedDates { for months in self.calenderDates { for calandardays in months { if currentCalendar.isDate(dates.date, inSameDayAsDate: calandardays.date) { calandardays.type = "menstruation" } } } } } // Remove pased dates from predicted cycle dates, add to pastPredicted dates array. func refreshPastedDates() { if self.menstruationCycle.predictedCycleDates.isEmpty { return } menstruationCycle.predictedCycleDates = menstruationCycle.sortDates(self.menstruationCycle.predictedCycleDates) for cycleDates in self.menstruationCycle.predictedCycleDates { if cycleDates.date.isEarlierThan(self.currentDate) { self.menstruationCycle.pastCycleDates.append(cycleDates) if cycleDates.type == "menstruation" { self.menstruationCycle.pastMenstruationDates.append(cycleDates) } } } SavedDataManager.sharedInstance.savePastMenstruationDates(self.menstruationCycle.pastMenstruationDates) SavedDataManager.sharedInstance.savePastCycleDates(self.menstruationCycle.pastCycleDates) } }
mit
f75ebbbba906d182e0179d38cbfcc9ca
30.619355
154
0.582041
5.378705
false
false
false
false
google/JacquardSDKiOS
Example/JacquardSDK/TagManager/TagManagerViewController.swift
1
6309
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 Combine import JacquardSDK import MaterialComponents import UIKit class TagManagerViewController: UIViewController { struct TagCellModel: Hashable { var tag: JacquardTag static func == (lhs: TagCellModel, rhs: TagCellModel) -> Bool { return lhs.tag.identifier == rhs.tag.identifier } func hash(into hasher: inout Hasher) { tag.identifier.hash(into: &hasher) } } private var observations = [Cancellable]() @IBOutlet private weak var tagsTableView: UITableView! // Publishes a value every time the tag connects or disconnects. private var tagPublisher: AnyPublisher<ConnectedTag, Never>? /// Use to manage data and provide cells for a table view. private var tagsDiffableDataSource: UITableViewDiffableDataSource<Int, TagCellModel>? /// Datasource model. private var connectedTagModels = [TagCellModel]() init(tagPublisher: AnyPublisher<ConnectedTag, Never>?) { self.tagPublisher = tagPublisher super.init(nibName: "TagManagerViewController", bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let addBarButtonItem = UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(addNewTag) ) navigationItem.rightBarButtonItem = addBarButtonItem // Configure table view. let nib = UINib(nibName: String(describing: ConnectedTagTableViewCell.self), bundle: nil) tagsTableView.register( nib, forCellReuseIdentifier: ConnectedTagTableViewCell.reuseIdentifier ) tagsDiffableDataSource = UITableViewDiffableDataSource<Int, TagCellModel>( tableView: tagsTableView, cellProvider: { (tagsTableView, indexPath, connectedTagCellModel) -> UITableViewCell? in guard let cell = tagsTableView.dequeueReusableCell( withIdentifier: ConnectedTagTableViewCell.reuseIdentifier, for: indexPath ) as? ConnectedTagTableViewCell else { return UITableViewCell() } cell.configure(with: connectedTagCellModel) cell.checkboxTapped = { [weak self] in guard let self = self else { return } self.updateCurrentTag(connectedTagCellModel.tag) } return cell }) tagsTableView.dataSource = tagsDiffableDataSource } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureTableDataSource() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) observations.removeAll() } } // Extension contains only UI logic not related to Jacquard SDK API's extension TagManagerViewController { func configureTableDataSource() { // We need to track the currently connected tag so that the details screen can show more // info and disconnect if desired. The prepend(nil) is because we want the table to populate // even when there are no connected tags (would be better if tagPublisher propagated nil values) tagPublisher? .map { tag -> ConnectedTag? in tag } .prepend(nil) .sink(receiveValue: { [weak self] connectedTag in guard let self = self else { return } self.configureTableDataSource(currentConnectedTag: connectedTag) }).addTo(&observations) } private func configureTableDataSource(currentConnectedTag: ConnectedTag?) { tagsTableView.isHidden = Preferences.knownTags.isEmpty connectedTagModels = Preferences.knownTags .map { // Swap in the currently connected tag so that the details screen can show more // info and disconnect if desired. if let currentConnectedTag = currentConnectedTag, $0.identifier == currentConnectedTag.identifier { return TagCellModel(tag: currentConnectedTag) } else { return TagCellModel(tag: $0) } } var snapshot = NSDiffableDataSourceSnapshot<Int, TagCellModel>() snapshot.appendSections([0]) snapshot.appendItems(connectedTagModels, toSection: 0) tagsDiffableDataSource?.apply(snapshot, animatingDifferences: false) if Preferences.knownTags.count > 0 { let indexPath = IndexPath(row: 0, section: 0) tagsTableView.selectRow(at: indexPath, animated: true, scrollPosition: .top) } } /// Initiate scanning on add new tag. @objc func addNewTag() { let scanningVC = ScanningViewController() scanningVC.shouldShowCloseButton = true let navigationController = UINavigationController(rootViewController: scanningVC) navigationController.modalPresentationStyle = .fullScreen present(navigationController, animated: true) } private func updateCurrentTag(_ tag: JacquardTag) { // Set selected tag as first tag. guard let index = Preferences.knownTags.firstIndex(where: { $0.identifier == tag.identifier }) else { return } let tag = Preferences.knownTags[index] Preferences.knownTags.remove(at: index) Preferences.knownTags.insert(tag, at: 0) NotificationCenter.default.post(name: Notification.Name("setCurrentTag"), object: nil) navigationController?.popViewController(animated: true) } } /// Handle Tableview delegate methods. extension TagManagerViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let model = tagsDiffableDataSource?.itemIdentifier(for: indexPath) else { return } let tagDetailsVC = TagDetailsViewController(tagPublisher: tagPublisher, tag: model.tag) navigationController?.pushViewController(tagDetailsVC, animated: true) } }
apache-2.0
3665bb8718a1b1e0c6c10cd8b709b6d5
33.288043
100
0.717863
5.075623
false
false
false
false
bettkd/KenyaNews
Pods/Swift-YouTube-Player/YouTubePlayer/YouTubePlayer/VideoPlayerView.swift
1
9430
// // VideoPlayerView.swift // YouTubePlayer // // Created by Giles Van Gruisen on 12/21/14. // Copyright (c) 2014 Giles Van Gruisen. All rights reserved. // import UIKit public enum YouTubePlayerState: String { case Unstarted = "-1" case Ended = "0" case Playing = "1" case Paused = "2" case Buffering = "3" case Queued = "4" } public enum YouTubePlayerEvents: String { case YouTubeIframeAPIReady = "onYouTubeIframeAPIReady" case Ready = "onReady" case StateChange = "onStateChange" case PlaybackQualityChange = "onPlaybackQualityChange" } public enum YouTubePlaybackQuality: String { case Small = "small" case Medium = "medium" case Large = "large" case HD720 = "hd720" case HD1080 = "hd1080" case HighResolution = "highres" } public protocol YouTubePlayerDelegate { func playerReady(videoPlayer: YouTubePlayerView) func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) } private extension NSURL { func queryStringComponents() -> [String: AnyObject] { var dict = [String: AnyObject]() // Check for query string if let query = self.query { // Loop through pairings (separated by &) for pair in query.componentsSeparatedByString("&") { // Pull key, val from from pair parts (separated by =) and set dict[key] = value let components = pair.componentsSeparatedByString("=") dict[components[0]] = components[1] } } return dict } } public func videoIDFromYouTubeURL(videoURL: NSURL) -> String? { return videoURL.queryStringComponents()["v"] as! String? } /** Embed and control YouTube videos */ public class YouTubePlayerView: UIView, UIWebViewDelegate { public typealias YouTubePlayerParameters = [String: AnyObject] private var webView: UIWebView! /** The readiness of the player */ private(set) public var ready = false /** The current state of the video player */ private(set) public var playerState = YouTubePlayerState.Unstarted /** The current playback quality of the video player */ private(set) public var playbackQuality = YouTubePlaybackQuality.Small /** Used to configure the player */ public var playerVars = YouTubePlayerParameters() /** Used to respond to player events */ public var delegate: YouTubePlayerDelegate? // MARK: Various methods for initialization /* public init() { super.init() self.buildWebView(playerParameters()) } */ override public init(frame: CGRect) { super.init(frame: frame) buildWebView(playerParameters()) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) buildWebView(playerParameters()) } override public func layoutSubviews() { super.layoutSubviews() // Remove web view in case it's within view hierarchy, reset frame, add as subview webView.removeFromSuperview() webView.frame = bounds addSubview(webView) } // MARK: Web view initialization private func buildWebView(parameters: [String: AnyObject]) { webView = UIWebView() webView.allowsInlineMediaPlayback = true webView.mediaPlaybackRequiresUserAction = false webView.delegate = self } // MARK: Load player public func loadVideoURL(videoURL: NSURL) { if let videoID = videoIDFromYouTubeURL(videoURL) { loadVideoID(videoID) } } public func loadVideoID(videoID: String) { var playerParams = playerParameters() playerParams["videoId"] = videoID loadWebViewWithParameters(playerParams) } public func loadPlaylistID(playlistID: String) { // No videoId necessary when listType = playlist, list = [playlist Id] playerVars["listType"] = "playlist" playerVars["list"] = playlistID loadWebViewWithParameters(playerParameters()) } // MARK: Player controls public func play() { evaluatePlayerCommand("playVideo()") } public func pause() { evaluatePlayerCommand("pauseVideo()") } public func stop() { evaluatePlayerCommand("stopVideo()") } public func clear() { evaluatePlayerCommand("clearVideo()") } public func seekTo(seconds: Float, seekAhead: Bool) { evaluatePlayerCommand("seekTo(\(seconds), \(seekAhead))") } // MARK: Playlist controls public func previousVideo() { evaluatePlayerCommand("previousVideo()") } public func nextVideo() { evaluatePlayerCommand("nextVideo()") } private func evaluatePlayerCommand(command: String) { let fullCommand = "player." + command + ";" webView.stringByEvaluatingJavaScriptFromString(fullCommand) } // MARK: Player setup private func loadWebViewWithParameters(parameters: YouTubePlayerParameters) { // Get HTML from player file in bundle let rawHTMLString = htmlStringWithFilePath(playerHTMLPath())! // Get JSON serialized parameters string let jsonParameters = serializedJSON(parameters)! // Replace %@ in rawHTMLString with jsonParameters string let htmlString = rawHTMLString.stringByReplacingOccurrencesOfString("%@", withString: jsonParameters, options: [], range: nil) // Load HTML in web view webView.loadHTMLString(htmlString, baseURL: NSURL(string: "about:blank")) } private func playerHTMLPath() -> String { return NSBundle(forClass: self.classForCoder).pathForResource("YTPlayer", ofType: "html")! } private func htmlStringWithFilePath(path: String) -> String? { // Error optional for error handling var error: NSError? // Get HTML string from path let htmlString: NSString? do { htmlString = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 htmlString = nil } // Check for error if let _ = error { print("Lookup error: no HTML file found for path, \(path)") } return htmlString! as String } // MARK: Player parameters and defaults private func playerParameters() -> YouTubePlayerParameters { return [ "height": "100%", "width": "100%", "events": playerCallbacks(), "playerVars": playerVars ] } private func playerCallbacks() -> YouTubePlayerParameters { return [ "onReady": "onReady", "onStateChange": "onStateChange", "onPlaybackQualityChange": "onPlaybackQualityChange", "onError": "onPlayerError" ] } private func serializedJSON(object: AnyObject) -> String? { // Empty error var error: NSError? // Serialize json into NSData let jsonData: NSData? do { jsonData = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted) } catch let error1 as NSError { error = error1 jsonData = nil } // Check for error and return nil if let _ = error { print("Error parsing JSON") return nil } // Success, return JSON string return NSString(data: jsonData!, encoding: NSUTF8StringEncoding) as? String } // MARK: JS Event Handling private func handleJSEvent(eventURL: NSURL) { // Grab the last component of the queryString as string let data: String? = eventURL.queryStringComponents()["data"] as? String if let host = eventURL.host { if let event = YouTubePlayerEvents(rawValue: host) { // Check event type and handle accordingly switch event { case .YouTubeIframeAPIReady: ready = true break case .Ready: delegate?.playerReady(self) break case .StateChange: if let newState = YouTubePlayerState(rawValue: data!) { playerState = newState delegate?.playerStateChanged(self, playerState: newState) } break case .PlaybackQualityChange: if let newQuality = YouTubePlaybackQuality(rawValue: data!) { playbackQuality = newQuality delegate?.playerQualityChanged(self, playbackQuality: newQuality) } break } } } } // MARK: UIWebViewDelegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL // Check if ytplayer event and, if so, pass to handleJSEvent if url!.scheme == "ytplayer" { handleJSEvent(url!) } return true } }
apache-2.0
98df156433cd20027718ffa8d2eca0fb
27.489426
144
0.614528
5.215708
false
false
false
false
fousa/trackkit
Example/Pods/AEXML/Sources/Document.swift
1
3899
/** * https://github.com/tadija/AEXML * Copyright (c) Marko Tadić 2014-2018 * Licensed under the MIT license. See LICENSE file. */ import Foundation /** This class is inherited from `AEXMLElement` and has a few addons to represent **XML Document**. XML Parsing is also done with this object. */ open class AEXMLDocument: AEXMLElement { // MARK: - Properties /// Root (the first child element) element of XML Document **(Empty element with error if not exists)**. open var root: AEXMLElement { guard let rootElement = children.first else { let errorElement = AEXMLElement(name: "Error") errorElement.error = AEXMLError.rootElementMissing return errorElement } return rootElement } public let options: AEXMLOptions // MARK: - Lifecycle /** Designated initializer - Creates and returns new XML Document object. - parameter root: Root XML element for XML Document (defaults to `nil`). - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object. */ public init(root: AEXMLElement? = nil, options: AEXMLOptions = AEXMLOptions()) { self.options = options let documentName = String(describing: AEXMLDocument.self) super.init(name: documentName) // document has no parent element parent = nil // add root element to document (if any) if let rootElement = root { _ = addChild(rootElement) } } /** Convenience initializer - used for parsing XML data (by calling `loadXMLData:` internally). - parameter xmlData: XML data to parse. - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed. */ public convenience init(xml: Data, options: AEXMLOptions = AEXMLOptions()) throws { self.init(options: options) try loadXML(xml) } /** Convenience initializer - used for parsing XML string (by calling `init(xmlData:options:)` internally). - parameter xmlString: XML string to parse. - parameter encoding: String encoding for creating `Data` from `xmlString` (defaults to `String.Encoding.utf8`) - parameter options: Options for XML Document header and parser settings (defaults to `AEXMLOptions()`). - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed. */ public convenience init(xml: String, encoding: String.Encoding = String.Encoding.utf8, options: AEXMLOptions = AEXMLOptions()) throws { guard let data = xml.data(using: encoding) else { throw AEXMLError.parsingFailed } try self.init(xml: data, options: options) } // MARK: - Parse XML /** Creates instance of `AEXMLParser` (private class which is simple wrapper around `XMLParser`) and starts parsing the given XML data. Throws error if data could not be parsed. - parameter data: XML which should be parsed. */ open func loadXML(_ data: Data) throws { children.removeAll(keepingCapacity: false) let xmlParser = AEXMLParser(document: self, data: data) try xmlParser.parse() } // MARK: - Override /// Override of `xml` property of `AEXMLElement` - it just inserts XML Document header at the beginning. open override var xml: String { var xml = "\(options.documentHeader.xmlString)\n" xml += root.xml return xml } }
mit
3eecd7d781830c6385674cdb3ecfc9fa
35.092593
119
0.634171
4.946701
false
false
false
false
Lebron1992/SlackTextViewController-Swift
SlackTextViewController-Swift/SlackTextViewController-Swift/Source/SLKTextInput.swift
1
4970
// // SLKTextInput.swift // SlackTextViewController-Swift // // Created by Lebron on 16/06/2017. // Copyright © 2017 hacknocraft. All rights reserved. // import Foundation import UIKit /// Searches for any matching string prefix at the text input's caret position. When nothing found, the completion block returns nil values. public protocol SLKTextInput: UITextInput { /// Searches for any matching string prefix at the text input's caret position. When nothing found, the completion block returns nil values /// - Parameters: /// - prefixes: A set of prefixes to search for /// - completion: A completion block called whenever the text processing finishes, successfuly or not. Required. func lookForPrefixes(_ prefixes: Set<String>, completion: (String?, String?, NSRange) -> Void) /// Finds the word close to the caret's position, if any /// - Parameters: /// - range: range Returns the range of the found word /// - Returns: /// The found word func wordAtCaretRange(_ range: inout NSRange) -> String? /// - Parameters: /// - range: range The range to be used for searching the word /// - rangeInText: rangePointer Returns the range of the found word. /// - Returns: /// The found word func wordAtRange(_ range: NSRange, rangeInText: inout NSRange) -> String? } extension SLKTextInput { // MARK: - Default implementations public func lookForPrefixes(_ prefixes: Set<String>, completion: (String?, String?, NSRange) -> Void) { var wordRange = NSRange(location: 0, length: 0) guard let word = wordAtCaretRange(&wordRange), prefixes.count > 0 else { return } if !word.isEmpty { for prefix in prefixes where word.hasPrefix(prefix) { completion(prefix, word, wordRange) } } else { completion(nil, nil, NSRange(location: 0, length: 0)) } } public func wordAtCaretRange(_ range: inout NSRange) -> String? { return wordAtRange(slk_caretRange, rangeInText: &range) } @discardableResult public func wordAtRange(_ range: NSRange, rangeInText: inout NSRange) -> String? { let location = range.location if location == NSNotFound { return nil } guard let text = slk_text else { return nil } // Aborts in case minimum requieres are not fufilled if text.isEmpty || location < 0 || (range.location + range.length) > text.length { rangeInText = NSRange(location: 0, length: 0) return nil } let leftPortion = text.substring(toIndex: location) let leftComponents = leftPortion.components(separatedBy: .whitespacesAndNewlines) let rightPortion = text.substring(from: location) let rightComponents = rightPortion.components(separatedBy: .whitespacesAndNewlines) guard let rightPart = rightComponents.first, let leftWordPart = leftComponents.last else { return nil } if location > 0 { let characterBeforeCursor = text.substring(with: Range(uncheckedBounds: (location - 1, location))) if let whitespaceRange = characterBeforeCursor.rangeOfCharacter(from: .whitespaces) { let distance = characterBeforeCursor.distance(from: whitespaceRange.lowerBound, to: whitespaceRange.upperBound) if distance == 1 { // At the start of a word, just use the word behind the cursor for the current word rangeInText = NSRange(location: location, length: rightPart.length) return rightPart } } } // In the middle of a word, so combine the part of the word before the cursor, and after the cursor to get the current word rangeInText = NSRange(location: location - leftWordPart.length, length: leftWordPart.length + rightPart.length) var word: String = leftWordPart.appending(rightPart) let linebreak = "\n" // If a break is detected, return the last component of the string if word.range(of: linebreak) != nil { rangeInText = text.nsRange(of: word) if let last = word.components(separatedBy: linebreak).last { word = last } } return word } // MARK: - Private methods private var slk_text: String? { if let range = textRange(from: beginningOfDocument, to: endOfDocument) { return text(in: range) } return nil } private var slk_caretRange: NSRange { if let selectedRange = selectedTextRange { let location = offset(from: beginningOfDocument, to: selectedRange.start) let length = offset(from: selectedRange.start, to: selectedRange.end) return NSRange(location: location, length: length) } return NSRange(location: 0, length: 0) } }
mit
93a8e77785651de0498f1d820dc3a773
34.748201
143
0.63876
4.656982
false
false
false
false
xwu/swift
test/Constraints/bridging.swift
1
19299
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a type from another module. We only allow this for a // few specific types, like String. extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterSequence.Iterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterSequence.Iterator { let result: LazyFilterSequence.Iterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { func hash(into hasher: inout Hasher) {} func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' expected to be an instance of a class or class-constrained type}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{34-34= as! [NotBridgedStruct]}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{'NSArray' is not convertible to '[NotBridgedStruct]'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{35-37=as!}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // There is a note attached to a requirement `requirement from conditional conformance of 'Dictionary<Int, NotEquatable>' to 'Equatable'` return d == d // expected-error{{operator function '==' requires that 'NotEquatable' conform to 'Equatable'}} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 _ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}} var inferDouble2 = 1 / 3 / 3.0 let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'}} // expected-note@-2 {{did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error@-1 {{generic parameter 'K' could not be inferred}} // expected-error@-2 {{generic parameter 'V' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{7-7=(}} {{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{3-3=(}} {{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Int'}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note@-1{{overloads for '+'}} var v73 = true + [] // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'Array<Bool>'}} var v75 = true + "str" // expected-error@:13 {{cannot convert value of type 'Bool' to expected argument type 'String'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}} // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{19-19=(}} {{50-50=) as String}} // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'NSString'}} {{50-50= as NSString}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{20-20=(}} {{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // Make sure more complicated cast has correct parenthesization func castMoreComplicated(anInt: Int?) { let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}} } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{value of type 'T' expected to be an instance of a class or class-constrained type in assignment}} z = b z = c // expected-error{{value of type 'Any' expected to be an instance of a class or class-constrained type in assignment}} expected-note {{cast 'Any' to 'AnyObject'}} {{8-8= as AnyObject}} z = d // expected-error{{value of type 'KnownUnbridged' expected to be an instance of a class or class-constrained type in assignment}} z = e z = f z = g z = h // expected-error{{value of type 'String' expected to be an instance of a class or class-constrained type in assignment}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y } // Array defaulting and bridging type checking error per rdar://problem/54274245 func rdar54274245(_ arr: [Any]?) { _ = (arr ?? []) as [NSObject] // expected-warning {{coercion from '[Any]' to '[NSObject]' may fail; use 'as?' or 'as!' instead}} } // rdar://problem/60501780 - failed to infer NSString as a value type of a dictionary func rdar60501780() { func foo(_: [String: NSObject]) {} func bar(_ v: String) { foo(["": "", "": v as NSString]) } } // SR-15161 func SR15161_as(e: Error?) { let _ = e as? NSError // Ok } func SR15161_is(e: Error?) { _ = e is NSError // expected-warning{{checking a value with optional type 'Error?' against dynamic type 'NSError' succeeds whenever the value is non-nil; did you mean to use '!= nil'?}} } func SR15161_as_1(e: Error?) { let _ = e as! NSError // expected-warning{{forced cast from 'Error?' to 'NSError' only unwraps and bridges; did you mean to use '!' with 'as'?}} }
apache-2.0
288ec27dd654f8ec51eee9dfde4319d2
46.185819
236
0.690554
3.993172
false
false
false
false
ViterbiDevelopment/PhotoWithSwift
PhotoKit/PhotoKit/ViewController.swift
1
6050
// // ViewController.swift // PhotoKit // // Created by 掌上先机 on 16/12/3. // Copyright © 2016年 wangchao. All rights reserved. // import UIKit import Photos class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var tableView:UITableView! var SystemUserPhotoList:PHFetchResult<PHAssetCollection>! var UserPhotoList:PHFetchResult<PHCollection>! var allPhotoCollection:Array<PHAssetCollection>! var photoManager = PHCachingImageManager() var allPhotoFirstImage:Array<UIImage>! override func viewWillAppear(_ animated: Bool) { PHPhotoLibrary.shared().register(self) } override func viewDidLoad() { super.viewDidLoad() tableView = UITableView.init(frame: view.frame, style: .plain) tableView.tableFooterView = UIView.init() tableView.delegate = self tableView.dataSource = self tableView.register(thumbnailSizeCell.classForCoder(), forCellReuseIdentifier: "photoCell") view.addSubview(tableView) //这里是所有的智能相册 系统给创建的 SystemUserPhotoList = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) // 这里是所有自己创建的相册 UserPhotoList = PHCollectionList.fetchTopLevelUserCollections(with: nil) photoManager.allowsCachingHighQualityImages = false fetPhotoAndReloadTableView() } func fetPhotoAndReloadTableView() { if allPhotoCollection != nil { allPhotoCollection.removeAll() } else{ allPhotoCollection = [] } for i in 0..<SystemUserPhotoList.count{ let asset = SystemUserPhotoList.object(at: i) allPhotoCollection.append(asset) } for i in 0..<UserPhotoList.count{ let asset = UserPhotoList.object(at: i) as! PHAssetCollection allPhotoCollection.append(asset) } if allPhotoFirstImage != nil{ allPhotoFirstImage.removeAll() } else{ allPhotoFirstImage = [] } for i in 0..<allPhotoCollection.count{ let object = allPhotoCollection[i] let fetchResult = PHAsset.fetchAssets(in: object, options: nil) if fetchResult.count > 0{ // print("block j=======\(i)") //PHImageRequestOptions 设置同步执行 let options = PHImageRequestOptions() options.isSynchronous = true photoManager.requestImage(for: fetchResult.firstObject!, targetSize: CGSize(width: 44, height: 44), contentMode: .default, options: options, resultHandler: { (image, _) in self.allPhotoFirstImage.append(image!) // print("block i=======\(i)") }) }else{ let def = UIImage.init(named: "user_default") allPhotoFirstImage.append(def!) // print("i=======\(i)") } } tableView.reloadData() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "photoCell", for: indexPath) as! thumbnailSizeCell if allPhotoFirstImage.count>0 { let object = allPhotoCollection[indexPath.row] cell.imageName = object.localizedTitle cell.thumbnailSizeImage = allPhotoFirstImage[indexPath.row] } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let browPhoto = BrowsAllViewController() let object = allPhotoCollection[indexPath.row] browPhoto.fetchResult = PHAsset.fetchAssets(in: object, options: nil) browPhoto.PHManager = photoManager navigationController?.pushViewController(browPhoto, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allPhotoFirstImage.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } deinit{ PHPhotoLibrary.shared().unregisterChangeObserver(self) } } extension ViewController:PHPhotoLibraryChangeObserver{ func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.sync { if changeInstance.changeDetails(for: SystemUserPhotoList) != nil { let changes = changeInstance.changeDetails(for: SystemUserPhotoList) SystemUserPhotoList = changes?.fetchResultAfterChanges } if changeInstance.changeDetails(for: UserPhotoList) != nil{ let changes = changeInstance.changeDetails(for: UserPhotoList) UserPhotoList = changes?.fetchResultAfterChanges } fetPhotoAndReloadTableView() } } }
apache-2.0
8bf0c6e17c635e00239c302eefb3e9a2
25.303965
187
0.537431
6.42043
false
false
false
false
pwoosam/Surf-Map
Surf Map/Helpers.swift
1
1391
import Foundation import UIKit extension UIImage { func resizedImage(newSize: CGSize) -> UIImage { // Created by samwize on 6/1/16. // http://samwize.com/2016/06/01/resize-uiimage-in-swift/ // Copyright © 2016 samwize. All rights reserved. guard self.size != newSize else { return self } UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0); self.draw(in: CGRect(origin: CGPoint.zero, size: newSize)) let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } } extension String { func image() -> UIImage { // Created by appzYourLife on 8/6/16. // http://stackoverflow.com/questions/38809425/convert-apple-emoji-string-to-uiimage // Copyright © 2016 appzYourLife. All rights reserved. let size = CGSize(width: 30, height: 35) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.clear.set() let rect = CGRect(origin: CGPoint.zero, size: size) UIRectFill(CGRect(origin: CGPoint.zero, size: size)) (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
5bf34d4565632681b6c8a53d4818a361
37.583333
93
0.657307
4.480645
false
false
false
false
johnno1962e/swift-corelibs-foundation
Foundation/NSNotification.swift
2
7678
// 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 // open class NSNotification: NSObject, NSCopying, NSCoding { public struct Name : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(lhs: Name, rhs: Name) -> Bool { return lhs.rawValue == rhs.rawValue } } private(set) open var name: Name private(set) open var object: Any? private(set) open var userInfo: [AnyHashable : Any]? public convenience override init() { /* do not invoke; not a valid initializer for this class */ fatalError() } public init(name: Name, object: Any?, userInfo: [AnyHashable : Any]? = nil) { self.name = name self.object = object self.userInfo = userInfo } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let name = aDecoder.decodeObject(of: NSString.self, forKey:"NS.name") else { return nil } let object = aDecoder.decodeObject(forKey: "NS.object") // let userInfo = aDecoder.decodeObject(of: NSDictionary.self, forKey: "NS.userinfo") self.init(name: Name(rawValue: String._unconditionallyBridgeFromObjectiveC(name)), object: object as! NSObject, userInfo: nil) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.name.rawValue._bridgeToObjectiveC(), forKey:"NS.name") aCoder.encode(self.object, forKey:"NS.object") aCoder.encode(self.userInfo?._bridgeToObjectiveC(), forKey:"NS.userinfo") } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open override var description: String { var str = "\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque()) {" str += "name = \(self.name.rawValue)" if let object = self.object { str += "; object = \(object)" } if let userInfo = self.userInfo { str += "; userInfo = \(userInfo)" } str += "}" return str } } private class NSNotificationReceiver : NSObject { fileprivate weak var object: NSObject? fileprivate var name: Notification.Name? fileprivate var block: ((Notification) -> Void)? fileprivate var sender: AnyObject? fileprivate var queue: OperationQueue? } extension Sequence where Iterator.Element : NSNotificationReceiver { /// Returns collection of `NSNotificationReceiver`. /// /// Will return: /// - elements that property `object` is not equal to `observerToFilter` /// - elements that property `name` is not equal to parameter `name` if specified. /// - elements that property `sender` is not equal to parameter `object` if specified. /// fileprivate func filterOutObserver(_ observerToFilter: AnyObject, name:Notification.Name? = nil, object: Any? = nil) -> [Iterator.Element] { return self.filter { observer in let differentObserver = observer.object !== observerToFilter let nameSpecified = name != nil let differentName = observer.name != name let objectSpecified = object != nil let differentSender = observer.sender !== _SwiftValue.store(object) return differentObserver || (nameSpecified && differentName) || (objectSpecified && differentSender) } } /// Returns collection of `NSNotificationReceiver`. /// /// Will return: /// - elements that property `sender` is `nil` or equals specified parameter `sender`. /// - elements that property `name` is `nil` or equals specified parameter `name`. /// fileprivate func observersMatchingName(_ name:Notification.Name? = nil, sender: Any? = nil) -> [Iterator.Element] { return self.filter { observer in let emptyName = observer.name == nil let sameName = observer.name == name let emptySender = observer.sender == nil let sameSender = observer.sender === _SwiftValue.store(sender) return (emptySender || sameSender) && (emptyName || sameName) } } } private let _defaultCenter: NotificationCenter = NotificationCenter() open class NotificationCenter: NSObject { private var _observers: [NSNotificationReceiver] private let _observersLock = NSLock() public required override init() { _observers = [NSNotificationReceiver]() } open class var `default`: NotificationCenter { return _defaultCenter } open func post(_ notification: Notification) { let sendTo = _observersLock.synchronized({ return _observers.observersMatchingName(notification.name, sender: notification.object) }) for observer in sendTo { guard let block = observer.block else { continue } if let queue = observer.queue, queue != OperationQueue.current { queue.addOperation { block(notification) } queue.waitUntilAllOperationsAreFinished() } else { block(notification) } } } open func post(name aName: Notification.Name, object anObject: Any?, userInfo aUserInfo: [AnyHashable : Any]? = nil) { let notification = Notification(name: aName, object: anObject, userInfo: aUserInfo) post(notification) } open func removeObserver(_ observer: Any) { removeObserver(observer, name: nil, object: nil) } open func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object: Any?) { guard let observer = observer as? NSObject else { return } _observersLock.synchronized({ self._observers = _observers.filterOutObserver(observer, name: aName, object: object) }) } @available(*,obsoleted:4.0,renamed:"addObserver(forName:object:queue:using:)") open func addObserver(forName name: Notification.Name?, object obj: Any?, queue: OperationQueue?, usingBlock block: @escaping (Notification) -> Void) -> NSObjectProtocol { return addObserver(forName: name, object: obj, queue: queue, using: block) } open func addObserver(forName name: Notification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) -> NSObjectProtocol { let object = NSObject() let newObserver = NSNotificationReceiver() newObserver.object = object newObserver.name = name newObserver.block = block newObserver.sender = _SwiftValue.store(obj) newObserver.queue = queue _observersLock.synchronized({ _observers.append(newObserver) }) return object } }
apache-2.0
77e861eb6e55d07a3c764137b5bd0576
35.046948
175
0.625554
4.893563
false
false
false
false
jimmyaat10/AATTools
AATTools/Tools/Extensions/String+Extra.swift
1
39017
// // String+Extra.swift // AATTools // // Created by Albert Arroyo on 18/11/16. // Copyright © 2016 AlbertArroyo. All rights reserved. // /** * This Extension has different MARK sections * Add/Modify accordingly to mantain 'some order' :) * If you add/modify some method/property, please add a Test. @see StringTest.swift */ import UIKit public extension String { // MARK: Computed properties /// Convenience property, Int for the number of characters of self public var length: Int { return self.characters.count } /// Convenience property, Array of the individual substrings composing self public var chars: [String] { return Array(self.characters).map({String($0)}) } /// Convenience property, Set<String> of the unique characters in self public var charSet: Set<String> { return Set(self.characters.map{String($0)}) } /// Convenience property, String with first character of self public var firstCharacter: String? { return self.chars.first } /// Convenience property, String with last character of self public var lastCharacter: String? { return self.chars.last } /// Convenience property, Bool to know if the string is empty (has characters) public var isEmpty: Bool { return self.chars.isEmpty } /// Convenience property, Bool to know if the field is empty (has characters) public var isEmptyField: Bool { if self.isEmpty { return true } return self.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty } /// Computed property that returns a new string made by replacing /// all HTML character entity references with the corresponding character var stringByDecodingHTMLEntities: String { let x = decodeHTMLEntities() return x.decodedString } /// Convenience property, String with base64 representation public var base64: String { let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue) let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } /// Convenience property, count of words public var countofWords: Int { let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options()) return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0 } /// Convenience property, count of paragraphs public var countofParagraphs: Int { let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options()) let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1 } /// Convenience property, extracts URLS from self and return [URL] public var extractURLs: [URL] { var urls: [URL] = [] let detector: NSDataDetector? do { detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } catch _ as NSError { detector = nil } let text = self if let detector = detector { detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let result = result, let url = result.url { urls.append(url) } }) } return urls } /// Convenience property, converts html to NSAttributedString var html2AttStr: NSAttributedString? { guard let data = data(using: .utf8) else { return nil } do { return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch let error as NSError { print(error.code) return nil } } /// Convenience property, returns localized string public var localized: String? { return self.localized() } /// Convenience property, returns pathExtension from string url public var pathExtension: String? { return NSURL(fileURLWithPath: self).pathExtension } /// Convenience property, returns lastPathComponent from string url public var lastPathComponent: String? { return NSURL(fileURLWithPath: self).lastPathComponent } /// Convenience property, converts self to NSString public var toNSString: NSString { get { return self as NSString } } } // MARK: String manipulation / util methods public extension String { /// Method to remove the first character of self /// - Returns: string with first character removed public func removedFirstChar() -> String { return self.substring(from: self.index(after: self.startIndex)) } /// Method to remove the last character of self /// - Returns: string with last character removed public func removedLastChar() -> String { return self.substring(to: self.index(before: self.endIndex)) } /// Method to remove whitespaces from the start and end of self /// - Returns: string with no whitespaces public func trimmed() -> String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Method to reverse self /// - Returns: string reversed public func reversed() -> String { return String(self.characters.reversed()) } /// Method to replace `t` parameter with string `s` parameter /// - Parameters: /// - target: The target to replace /// - withString: The string to replace /// - Returns: string replaced func replaced(target t: String, withString s: String) -> String { return self.replacingOccurrences(of: t, with: s, options: .literal, range: nil) } /// Method to split string using a separator string `s` parameter /// - Parameters: /// - separator: The separator string /// - Returns: [String] public func splitted(separator s: String) -> [String] { return self.components(separatedBy: s).filter { !$0.trimmed().isEmpty } } /// Method to split string using a separator set `characters` parameter with delimiters /// - Parameters: /// - separator: The separator CharacterSet /// - Returns: [String] public func splitted(separator characters: CharacterSet) -> [String] { return self.components(separatedBy: characters).filter { !$0.trimmed().isEmpty } } /// Method to count number of instances of the `substring` parameter inside self /// - Parameters: /// - substring: The substring to count /// - Returns: Int with number of ocurrences public func count(substring s: String) -> Int { return components(separatedBy: s).count - 1 } /// Method to uppercase the first letter /// - Returns: string with first letter capitalized func uppercasedFirstLetter() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).uppercased()) return result } /// Method to uppercases first 'count' characters of String /// - Parameters: /// - firstNumberCharacters: the first count characters /// - Returns: String modified public func uppercasedPrefix(firstNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) return result } /// Method to uppercases last 'count' characters of self /// - Parameters: /// - lastNumberCharacters: the last count characters /// - Returns: String modified public func uppercasedSuffix(lastNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) return result } /// Method to uppercases string in range 'range' /// - Parameters: /// - range: CountableRange<Int> to uppercase /// - Returns: String modified public func uppercased(range r: CountableRange<Int>) -> String { let from = max(r.lowerBound, 0), to = min(r.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased()) return result } /// Method to lowercase the first letter /// - Returns: string with first letter lowercased public func lowercasedFirstLetter() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) return result } /// Method to lowercase first 'count' characters of String /// - Parameters: /// - firstNumberCharacters: the first count characters /// - Returns: String modified public func lowercasedPrefix(firstNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased()) return result } /// Method to lowercase last 'count' characters of self /// - Parameters: /// - lastNumberCharacters: the last count characters /// - Returns: String modified public func lowercasedSuffix(lastNumberCharacters count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) return result } /// Method to lowercase string in range 'range' /// - Parameters: /// - range: CountableRange<Int> to lowercase /// - Returns: String modified public func lowercased(range r: CountableRange<Int>) -> String { let from = max(r.lowerBound, 0), to = min(r.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased()) return result } /// Method to get the first index of the occurency of the character in self /// - Parameters: /// - character: Character to search /// - Returns: Int? with the position public func getIndexOf(character char: Character) -> Int? { for (index, c) in characters.enumerated() { if c == char { return index } } return nil } /// Method to get the height of rendered self /// - Parameters: /// - maxWidth: CGFloat /// - font: UIFont /// - lineBreakMode: NSLineBreakMode /// - Returns: CGFloat func height(maxWidth width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat { var attrib: [String: AnyObject] = [NSFontAttributeName: font] if lineBreakMode != nil { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode! attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName) } let size = CGSize(width: width, height: CGFloat(DBL_MAX)) return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height) } /// Method to copy string to pasteboard public func addToPasteboard() { let pasteboard = UIPasteboard.general pasteboard.string = self } } // MARK: String manipulation (mutating methods) // TODO: add some mutating functions public extension String { } // MARK: Wrapper for Index (String access) public extension String { /// Wrapper for index with startIndex offsetBy `from` parameter /// - Parameters: /// - from: Int /// - Returns: Index func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } /// Wrapper substring `from` parameter /// - Parameters: /// - from: Int /// - Returns: String func substring(from: Int) -> String { let fromIndex = index(from: from) return substring(from: fromIndex) } /// Wrapper substring `to` parameter /// - Parameters: /// - to: Int /// - Returns: String func substring(to: Int) -> String { let toIndex = index(from: to) return substring(to: toIndex) } /// Wrapper substring with range /// - Parameters: /// - with: Range<Int> /// - Returns: String func substring(with r: Range<Int>) -> String { let startIndex = index(from: r.lowerBound) let endIndex = index(from: r.upperBound) return substring(with: startIndex..<endIndex) } } // MARK: Subscript public extension String { /// Method to cut string from `integerIndex` parameter to the end /// - Parameters: /// - integerIndex: Int /// - Returns: Character public subscript(integerIndex: Int) -> Character { let index = characters.index(startIndex, offsetBy: integerIndex) return self[index] } /// Method to cut string from `integerRange` parameter /// - Parameters: /// - integerRange: Range<Int> /// - Returns: String public subscript(integerRange: Range<Int>) -> String { let start = characters.index(startIndex, offsetBy: integerRange.lowerBound) let end = characters.index(startIndex, offsetBy: integerRange.upperBound) return self[start..<end] } /// Method to cut string from `integerClosedRange` parameter /// - Parameters: /// - integerClosedRange: ClosedRange<Int> /// - Returns: String public subscript(integerClosedRange: ClosedRange<Int>) -> String { return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)] } } // MARK: Localization Methods public extension String { /// Method to localize self. /// Adding a bundle parameter with default value provide the possibility to test the method /// mocking the correct bundle /// - Parameters: /// - bundle: Bundle, by default Bundle.main /// - Returns: Localized string public func localized(bundle localizationBundle : Bundle = Bundle.main) -> String { return NSLocalizedString(self, bundle: localizationBundle, comment: "") } } // MARK: URL Methods public extension String { /// Method to encode the self string url /// - Returns: URL? with encoded URL public func encodeURL() -> URL? { if let originURL = URL(string: self) { return originURL } else { if let url = URL(string: self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!) { return url } else { return nil } } } /// Method to percent escapes values to be added to a URL query as specified in RFC 3986 /// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~". /// http://www.ietf.org/rfc/rfc3986.txt /// - Returns: String? with percent-escaped string func addedPercentToEncodedForUrl() -> String? { let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters) } } // MARK: Range / NSRange public extension String { /// Method to return NSRange from `range` parameter /// - Parameters: /// - from: Range<String.Index> /// - Returns: NSRange func nsRange(from range: Range<String.Index>) -> NSRange { let from = range.lowerBound.samePosition(in: utf16) let to = range.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to)) } /// Method to return Range from `nsRange` parameter /// - Parameters: /// - from: NSRange /// - Returns: Range? func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } } // MARK: String satisfying certain conditions public extension String { /// Method to know if self is an email /// - Returns: Bool with condition public func isEmail() -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } /// Method to know if self is numeric /// - Returns: Bool with condition public func isNumber() -> Bool { let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) return (range == nil) } /// Method to know if self contains given sensitive `s` parameter /// - Parameters: /// - string: String to search /// - Returns: Bool with condition public func containsSensitive(string s: String) -> Bool { return self.range(of: s) != nil } /// Method to know if self contains given not sensitive `s` parameter /// - Parameters: /// - string: String to search /// - Returns: Bool with condition public func containsNotSensitive(string s: String) -> Bool { return self.lowercased().range(of: s) != nil } /// Method to find matches of regular expression in string /// - Parameters: /// - regex: String with regex /// - Returns: [String] with matches public func matchesForRegexInText(regex reg: String!) -> [String] { let regex = try? NSRegularExpression(pattern: reg, options: []) let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? [] return results.map { self.substring(with: self.range(from: $0.range)!) } } } // MARK: Tracting Numbers / Conversions / Utils for Banking Apps public extension String { /// More efficient not to create a number formatter every time if not modify properties static let numberFormatterInstance = NumberFormatter() /// Method to format a string to double /// - Returns: Double? public func toDouble() -> Double? { if let num = String.numberFormatterInstance.number(from: self) { return num.doubleValue } else { return nil } } /// Method to format a string to int /// - Returns: Int? public func toInt() -> Int? { if let num = String.numberFormatterInstance.number(from: self) { return num.intValue } else { return nil } } /// Method to format a string to float /// - Returns: Float? public func toFloat() -> Float? { if let num = String.numberFormatterInstance.number(from: self) { return num.floatValue } else { return nil } } /// Method to format a string to bool /// - Returns: Bool? public func toBool() -> Bool? { let trimmedString = trimmed().lowercased() if trimmedString == "true" || trimmedString == "false" { return (trimmedString as NSString).boolValue } return nil } /// Method to format a string to double with given `d` parameter /// - Parameters: /// - decimals: Int /// - Returns: String? public func formatNumber(decimals d: Int) -> String? { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.maximumFractionDigits = d guard let nDouble = self.toDouble() else { return nil } return numberFormatter.string(from: NSNumber(value: nDouble)) } /// Method to remove white spaces /// - Returns: String public func removedWitheSpaces() -> String { return self.replaced(target: " ", withString: "") } /// Method to format a string to an account number /// Verifications are not in this scope /// - Returns: String formatted func formattedAccountNumber() -> String { if self.length > 19 { let r1 : Range<Int> = 0..<4 let part1 = self.substring(with: r1) let r2 : Range<Int> = 4..<8 let part2 = self.substring(with: r2) let r3 : Range<Int> = 8..<10 let part3 = self.substring(with: r3) let r4 : Range<Int> = 10..<20 let part4 = self.substring(with: r4) return "\(part1)-\(part2)-\(part3)-\(part4)" } return self } /// Method to format a string to an iban number /// Verifications are not in this scope /// - Returns: String formatted func formattedIbanNumber() -> String { if self.length > 23 { let r1 : Range<Int> = 0..<4 let part1 = self.substring(with: r1) let r2 : Range<Int> = 4..<8 let part2 = self.substring(with: r2) let r3 : Range<Int> = 8..<12 let part3 = self.substring(with: r3) let r4 : Range<Int> = 12..<16 let part4 = self.substring(with: r4) let r5 : Range<Int> = 16..<20 let part5 = self.substring(with: r5) let r6 : Range<Int> = 20..<24 let part6 = self.substring(with: r6) return "\(part1) \(part2) \(part3) \(part4) \(part5) \(part6)" } return self } /// Method to remove trailing zeros to a given fraction digits `d` parameter /// Verifications are not in this scope /// - Parameters: /// - decimals: Int /// - Returns: String formatted func removedTrailingZeros(decimals d: Int) -> String { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = d numberFormatter.minimumFractionDigits = 0 guard let strRemovedTrailing = numberFormatter.string(from: NSNumber(value: self.toDouble()!)) else { return self } if self.hasPrefix("0") { return "0\(strRemovedTrailing)" } return strRemovedTrailing } } // MARK: NSAttributedString public extension String { /// Method to bold self /// - Returns: NSAttributedString public func bold() -> NSAttributedString { let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) return boldString } /// Method to underline self /// - Returns: NSAttributedString public func underline() -> NSAttributedString { let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) return underlineString } /// Method to italic self /// - Returns: NSAttributedString public func italic() -> NSAttributedString { let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) return italicString } /// Method to color self /// - Parameters: /// - _ : UIColor /// - Returns: NSAttributedString public func color(_ color: UIColor) -> NSAttributedString { let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) return colorString } /// Method to color substring of self /// - Parameters: /// - substring : String to apply the color in self /// - color : UIColor /// - Returns: NSAttributedString public func color(substring s: String, color: UIColor) -> NSMutableAttributedString { var start = 0 var ranges: [NSRange] = [] while true { let range = (self as NSString).range(of: s, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start)) if range.location == NSNotFound { break } else { ranges.append(range) start = range.location + range.length } } let attrText = NSMutableAttributedString(string: self) for range in ranges { attrText.addAttribute(NSForegroundColorAttributeName, value: color, range: range) } return attrText } } // MARK: Emoji public extension String { /// Method to check if String contains Emoji /// - Returns: Bool public func containsEmoji() -> Bool { for i in 0...length { let c: unichar = (self as NSString).character(at: i) if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) { return true } } return false } } // MARK: HTML //Source : https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555 private let characterEntities : [String: Character] = [ // XML predefined entities: "&quot;" : "\"", "&amp;" : "&", "&apos;" : "'", "&lt;" : "<", "&gt;" : ">", // HTML character entity references: "&nbsp;" : "\u{00A0}", "&iexcl;" : "\u{00A1}", "&cent;" : "\u{00A2}", "&pound;" : "\u{00A3}", "&curren;" : "\u{00A4}", "&yen;" : "\u{00A5}", "&brvbar;" : "\u{00A6}", "&sect;" : "\u{00A7}", "&uml;" : "\u{00A8}", "&copy;" : "\u{00A9}", "&ordf;" : "\u{00AA}", "&laquo;" : "\u{00AB}", "&not;" : "\u{00AC}", "&shy;" : "\u{00AD}", "&reg;" : "\u{00AE}", "&macr;" : "\u{00AF}", "&deg;" : "\u{00B0}", "&plusmn;" : "\u{00B1}", "&sup2;" : "\u{00B2}", "&sup3;" : "\u{00B3}", "&acute;" : "\u{00B4}", "&micro;" : "\u{00B5}", "&para;" : "\u{00B6}", "&middot;" : "\u{00B7}", "&cedil;" : "\u{00B8}", "&sup1;" : "\u{00B9}", "&ordm;" : "\u{00BA}", "&raquo;" : "\u{00BB}", "&frac14;" : "\u{00BC}", "&frac12;" : "\u{00BD}", "&frac34;" : "\u{00BE}", "&iquest;" : "\u{00BF}", "&Agrave;" : "\u{00C0}", "&Aacute;" : "\u{00C1}", "&Acirc;" : "\u{00C2}", "&Atilde;" : "\u{00C3}", "&Auml;" : "\u{00C4}", "&Aring;" : "\u{00C5}", "&AElig;" : "\u{00C6}", "&Ccedil;" : "\u{00C7}", "&Egrave;" : "\u{00C8}", "&Eacute;" : "\u{00C9}", "&Ecirc;" : "\u{00CA}", "&Euml;" : "\u{00CB}", "&Igrave;" : "\u{00CC}", "&Iacute;" : "\u{00CD}", "&Icirc;" : "\u{00CE}", "&Iuml;" : "\u{00CF}", "&ETH;" : "\u{00D0}", "&Ntilde;" : "\u{00D1}", "&Ograve;" : "\u{00D2}", "&Oacute;" : "\u{00D3}", "&Ocirc;" : "\u{00D4}", "&Otilde;" : "\u{00D5}", "&Ouml;" : "\u{00D6}", "&times;" : "\u{00D7}", "&Oslash;" : "\u{00D8}", "&Ugrave;" : "\u{00D9}", "&Uacute;" : "\u{00DA}", "&Ucirc;" : "\u{00DB}", "&Uuml;" : "\u{00DC}", "&Yacute;" : "\u{00DD}", "&THORN;" : "\u{00DE}", "&szlig;" : "\u{00DF}", "&agrave;" : "\u{00E0}", "&aacute;" : "\u{00E1}", "&acirc;" : "\u{00E2}", "&atilde;" : "\u{00E3}", "&auml;" : "\u{00E4}", "&aring;" : "\u{00E5}", "&aelig;" : "\u{00E6}", "&ccedil;" : "\u{00E7}", "&egrave;" : "\u{00E8}", "&eacute;" : "\u{00E9}", "&ecirc;" : "\u{00EA}", "&euml;" : "\u{00EB}", "&igrave;" : "\u{00EC}", "&iacute;" : "\u{00ED}", "&icirc;" : "\u{00EE}", "&iuml;" : "\u{00EF}", "&eth;" : "\u{00F0}", "&ntilde;" : "\u{00F1}", "&ograve;" : "\u{00F2}", "&oacute;" : "\u{00F3}", "&ocirc;" : "\u{00F4}", "&otilde;" : "\u{00F5}", "&ouml;" : "\u{00F6}", "&divide;" : "\u{00F7}", "&oslash;" : "\u{00F8}", "&ugrave;" : "\u{00F9}", "&uacute;" : "\u{00FA}", "&ucirc;" : "\u{00FB}", "&uuml;" : "\u{00FC}", "&yacute;" : "\u{00FD}", "&thorn;" : "\u{00FE}", "&yuml;" : "\u{00FF}", "&OElig;" : "\u{0152}", "&oelig;" : "\u{0153}", "&Scaron;" : "\u{0160}", "&scaron;" : "\u{0161}", "&Yuml;" : "\u{0178}", "&fnof;" : "\u{0192}", "&circ;" : "\u{02C6}", "&tilde;" : "\u{02DC}", "&Alpha;" : "\u{0391}", "&Beta;" : "\u{0392}", "&Gamma;" : "\u{0393}", "&Delta;" : "\u{0394}", "&Epsilon;" : "\u{0395}", "&Zeta;" : "\u{0396}", "&Eta;" : "\u{0397}", "&Theta;" : "\u{0398}", "&Iota;" : "\u{0399}", "&Kappa;" : "\u{039A}", "&Lambda;" : "\u{039B}", "&Mu;" : "\u{039C}", "&Nu;" : "\u{039D}", "&Xi;" : "\u{039E}", "&Omicron;" : "\u{039F}", "&Pi;" : "\u{03A0}", "&Rho;" : "\u{03A1}", "&Sigma;" : "\u{03A3}", "&Tau;" : "\u{03A4}", "&Upsilon;" : "\u{03A5}", "&Phi;" : "\u{03A6}", "&Chi;" : "\u{03A7}", "&Psi;" : "\u{03A8}", "&Omega;" : "\u{03A9}", "&alpha;" : "\u{03B1}", "&beta;" : "\u{03B2}", "&gamma;" : "\u{03B3}", "&delta;" : "\u{03B4}", "&epsilon;" : "\u{03B5}", "&zeta;" : "\u{03B6}", "&eta;" : "\u{03B7}", "&theta;" : "\u{03B8}", "&iota;" : "\u{03B9}", "&kappa;" : "\u{03BA}", "&lambda;" : "\u{03BB}", "&mu;" : "\u{03BC}", "&nu;" : "\u{03BD}", "&xi;" : "\u{03BE}", "&omicron;" : "\u{03BF}", "&pi;" : "\u{03C0}", "&rho;" : "\u{03C1}", "&sigmaf;" : "\u{03C2}", "&sigma;" : "\u{03C3}", "&tau;" : "\u{03C4}", "&upsilon;" : "\u{03C5}", "&phi;" : "\u{03C6}", "&chi;" : "\u{03C7}", "&psi;" : "\u{03C8}", "&omega;" : "\u{03C9}", "&thetasym;" : "\u{03D1}", "&upsih;" : "\u{03D2}", "&piv;" : "\u{03D6}", "&ensp;" : "\u{2002}", "&emsp;" : "\u{2003}", "&thinsp;" : "\u{2009}", "&zwnj;" : "\u{200C}", "&zwj;" : "\u{200D}", "&lrm;" : "\u{200E}", "&rlm;" : "\u{200F}", "&ndash;" : "\u{2013}", "&mdash;" : "\u{2014}", "&lsquo;" : "\u{2018}", "&rsquo;" : "\u{2019}", "&sbquo;" : "\u{201A}", "&ldquo;" : "\u{201C}", "&rdquo;" : "\u{201D}", "&bdquo;" : "\u{201E}", "&dagger;" : "\u{2020}", "&Dagger;" : "\u{2021}", "&bull;" : "\u{2022}", "&hellip;" : "\u{2026}", "&permil;" : "\u{2030}", "&prime;" : "\u{2032}", "&Prime;" : "\u{2033}", "&lsaquo;" : "\u{2039}", "&rsaquo;" : "\u{203A}", "&oline;" : "\u{203E}", "&frasl;" : "\u{2044}", "&euro;" : "\u{20AC}", "&image;" : "\u{2111}", "&weierp;" : "\u{2118}", "&real;" : "\u{211C}", "&trade;" : "\u{2122}", "&alefsym;" : "\u{2135}", "&larr;" : "\u{2190}", "&uarr;" : "\u{2191}", "&rarr;" : "\u{2192}", "&darr;" : "\u{2193}", "&harr;" : "\u{2194}", "&crarr;" : "\u{21B5}", "&lArr;" : "\u{21D0}", "&uArr;" : "\u{21D1}", "&rArr;" : "\u{21D2}", "&dArr;" : "\u{21D3}", "&hArr;" : "\u{21D4}", "&forall;" : "\u{2200}", "&part;" : "\u{2202}", "&exist;" : "\u{2203}", "&empty;" : "\u{2205}", "&nabla;" : "\u{2207}", "&isin;" : "\u{2208}", "&notin;" : "\u{2209}", "&ni;" : "\u{220B}", "&prod;" : "\u{220F}", "&sum;" : "\u{2211}", "&minus;" : "\u{2212}", "&lowast;" : "\u{2217}", "&radic;" : "\u{221A}", "&prop;" : "\u{221D}", "&infin;" : "\u{221E}", "&ang;" : "\u{2220}", "&and;" : "\u{2227}", "&or;" : "\u{2228}", "&cap;" : "\u{2229}", "&cup;" : "\u{222A}", "&int;" : "\u{222B}", "&there4;" : "\u{2234}", "&sim;" : "\u{223C}", "&cong;" : "\u{2245}", "&asymp;" : "\u{2248}", "&ne;" : "\u{2260}", "&equiv;" : "\u{2261}", "&le;" : "\u{2264}", "&ge;" : "\u{2265}", "&sub;" : "\u{2282}", "&sup;" : "\u{2283}", "&nsub;" : "\u{2284}", "&sube;" : "\u{2286}", "&supe;" : "\u{2287}", "&oplus;" : "\u{2295}", "&otimes;" : "\u{2297}", "&perp;" : "\u{22A5}", "&sdot;" : "\u{22C5}", "&lceil;" : "\u{2308}", "&rceil;" : "\u{2309}", "&lfloor;" : "\u{230A}", "&rfloor;" : "\u{230B}", "&lang;" : "\u{2329}", "&rang;" : "\u{232A}", "&loz;" : "\u{25CA}", "&spades;" : "\u{2660}", "&clubs;" : "\u{2663}", "&hearts;" : "\u{2665}", "&diams;" : "\u{2666}", ] public extension String { /// Method that returns a tuple containing the string made by replacing in the /// `String` all HTML character entity references with the corresponding /// character. Also returned is an array of offset information describing /// the location and length offsets for each replacement. This allows /// for the correct adjust any attributes that may be associated with /// with substrings within the `String` func decodeHTMLEntities() -> (decodedString: String, replacementOffsets: [Range<String.Index>]) { // ===== Utility functions ===== // Record the index offsets of each replacement // This allows anyone to correctly adjust any attributes that may be // associated with substrings within the string var replacementOffsets: [Range<String.Index>] = [] // Convert the number in the string to the corresponding // Unicode character, e.g. // decodeNumeric("64", 10) --> "@" // decodeNumeric("20ac", 16) --> "€" func decodeNumeric(string : String, base : Int32) -> Character? { let code = UInt32(strtoul(string, nil, base)) return Character(UnicodeScalar(code)!) } // Decode the HTML character entity to the corresponding // Unicode character, return `nil` for invalid input. // decode("&#64;") --> "@" // decode("&#x20ac;") --> "€" // decode("&lt;") --> "<" // decode("&foo;") --> nil func decode(entity : String) -> Character? { if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){ return decodeNumeric(string: entity.substring(from: entity.index(entity.startIndex, offsetBy: 3)), base: 16) } else if entity.hasPrefix("&#") { return decodeNumeric(string: entity.substring(from: entity.index(entity.startIndex, offsetBy: 2)), base: 10) } else { return characterEntities[entity] } } // ===== Method starts here ===== var result = "" var position = startIndex // Find the next '&' and copy the characters preceding it to `result`: while let ampRange = self.range(of:"&", range: position ..< endIndex) { result += self[position ..< ampRange.lowerBound] position = ampRange.lowerBound // Find the next ';' and copy everything from '&' to ';' into `entity` if let semiRange = self.range(of:";", range: position ..< endIndex) { let entity = self[position ..< semiRange.upperBound] if let decoded = decode(entity: entity) { // Replace by decoded character: result.append(decoded) replacementOffsets.append(Range(position ..< semiRange.upperBound)) } else { // Invalid entity, copy verbatim: result += entity } position = semiRange.upperBound } else { // No matching ';'. break } } // Copy remaining characters to `result`: result += self[position ..< endIndex] // Return results return (decodedString: result, replacementOffsets: replacementOffsets) } }
mit
3c4352fbb6ded8c78175646f581dfcea
35.803774
215
0.551112
4.032665
false
false
false
false
AimobierCocoaPods/OddityUI
Classes/NewFeedListViewController/NewFeedListDataSource.swift
1
12508
// // NewFeedListDataSource.swift // OddityUI // // Created by Mister on 16/8/29. // Copyright © 2016年 aimobier. All rights reserved. // import UIKit import PINCache // ///// 属性字符串 缓存器 //class TableViewHeightCached { // // // private static var __once: () = { () -> Void in // backTaskLeton.instance = TableViewHeightCached() // }() // // lazy var cache = PINMemoryCache() // // class var sharedHeightCached:TableViewHeightCached!{ // get{ // struct backTaskLeton{ // static var predicate:Int = 0 // static var instance:TableViewHeightCached? = nil // } // _ = TableViewHeightCached.__once // return backTaskLeton.instance // } // } // // func cacheHeight(_ nid : Int,height:CGFloat){ // // self.cache.setObject(height, forKey: "\(nid)") // } // // /** // 根据提供的 title 字符串 (title 针对于频道时唯一的,可以当作唯一标识来使用)在缓存中获取UIViewController // // - parameter string: 原本 字符串 // - parameter font: 字体 对象 默认为 系统2号字体 // // - returns: 返回属性字符串 // */ // func heightForNewNID(_ nid : Int ) -> CGFloat { // //// if let channelViewController = self.cache.objectForKey(nid) as? CG { return channelViewController } //// //// let channelViewController = getDisplayViewController(channel.cname) //// //// channelViewController.channel = channel //// //// if channel.id == 1{ //// //// channelViewController.newsResults = New.allArray().filter("ishotnew = 1 AND isdelete = 0") //// }else{ //// //// channelViewController.newsResults = New.allArray().filter("(ANY channelList.channel = %@ AND isdelete = 0 ) OR ( channel = %@ AND isidentification = 1 )",channel.id,channel.id) //// } //// //// self.cache.setObject(channelViewController, forKey: channel.cname) // // return self.cache.object(forKey: "\(nid)") as? CGFloat ?? -1 // } //} extension NewFeedListViewController:UITableViewDataSource{ fileprivate func getTableViewCell(_ indexPath : IndexPath) -> UITableViewCell{ let new = newsResults[(indexPath as NSIndexPath).row] if new.rtype == 4 { let cell = tableView.dequeueReusableCell(withIdentifier: "SpecialTableViewCell") as! SpecialTableViewCell cell.setNewObject(new) return cell } var cell :NewBaseTableViewCell! if new.isidentification == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "refreshcell")! as UITableViewCell return cell } if new.style == 0 { cell = tableView.dequeueReusableCell(withIdentifier: "NewNormalTableViewCell") as! NewNormalTableViewCell cell.setNewObject(new) }else if new.style == 1 { cell = tableView.dequeueReusableCell(withIdentifier: "NewOneTableViewCell") as! NewOneTableViewCell cell.setNewObject(new) }else if new.style == 2 { cell = tableView.dequeueReusableCell(withIdentifier: "NewTwoTableViewCell") as! NewTwoTableViewCell cell.setNewObject(new) }else if new.style == 3 { cell = tableView.dequeueReusableCell(withIdentifier: "NewThreeTableViewCell") as! NewThreeTableViewCell cell.setNewObject(new) }else{ cell = tableView.dequeueReusableCell(withIdentifier: "NewTwoTableViewCell") as! NewTwoTableViewCell switch new.style { case 5: cell.setNewObject(new,bigImg: 0) case 11: cell.setNewObject(new,bigImg: 0) case 12: cell.setNewObject(new,bigImg: 1) default: cell.setNewObject(new,bigImg: 2) } } cell.noLikeButton.removeActions(events: UIControlEvents.touchUpInside) cell.noLikeButton.addAction(events: UIControlEvents.touchUpInside) { (_) in self.handleActionMethod(cell, indexPath: indexPath) } // if self.channel?.id == 1 { cell.setPPPLabel(new) // } return cell } /** 设置新闻的个数 判断当前视图没有newResults对象,如果没有 默认返回0 有则正常返回其数目 - parameter tableView: 表格对象 - parameter section: section index - returns: 新闻的个数 */ public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsResults.count } /** 返回每一个新闻的展示 其中当遇到 这个新闻的 `isidentification` 的标示为 1 的时候,说明这条新闻是用来显示一个刷新视图的。 其它的新闻会根据起 style 参数进行 没有图 一张图 两张图 三张图的 新闻展示形式进行不同形式的展示 - parameter tableView: 表格对象 - parameter indexPath: 当前新闻展示的位置 - returns: 返回新闻的具体战士杨视图 */ public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return self.getTableViewCell(indexPath) } /** 处理用户的点击新闻视图中的 不喜欢按钮处理方法 首先获取当前cell基于注视图的point。用于传递给上层视图进行 cell 新闻的展示 计算cell所在的位置,之后预估起全部展开的位置大小,是否会被遮挡,如果被遮挡 ,就先进性cel的移动,使其不会被遮挡 之后将这个cell和所在的point传递给上层视图 使用的传递工具为 delegate 之后上层视图处理完成之后,返回是否删除动作,当前tableview进行删除或者刷新cell - parameter cell: 返回被点击的cell - parameter indexPath: 被点击的位置 */ fileprivate func handleActionMethod(_ cell :NewBaseTableViewCell,indexPath:IndexPath){ var delayInSeconds = 0.0 let porint = cell.convert(cell.bounds, to: self.view).origin if porint.y < 0 { delayInSeconds = 0.5 self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true) } let needHeight = porint.y+cell.frame.height+128 if needHeight > self.tableView.frame.height { delayInSeconds = 0.5 let result = needHeight-self.tableView.frame.height let toPoint = CGPoint(x: 0, y: self.tableView.contentOffset.y+result) self.tableView.setContentOffset(toPoint, animated: true) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // 2 self.predelegate.ClickNoLikeButtonOfUITableViewCell?(cell, finish: { (cancel) in if !cancel { self.newsResults[(indexPath as NSIndexPath).row].suicide() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { // 2 self.showNoInterest() self.tableView.reloadData() } }else{ self.tableView.reloadData() } }) } } } extension NewFeedListViewController:UITableViewDelegate{ /** 点击cell 之后处理的方法 如果是刷新的cell就进行当前新闻的刷新 如果是新闻cell就进行 - parameter tableView: tableview 对象 - parameter indexPath: 点击的indexPath */ public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let new = newsResults[(indexPath as NSIndexPath).row] if new.isidentification == 1 { return self.tableView.mj_header.beginRefreshing() } if new.rtype == 4, let view = OddityViewControllerManager.shareManager.storyBoard.instantiateViewController(withIdentifier: "SpecialViewController") as? SpecialViewController { view.tid = new.nid view.odditySetting = self.odditySetting view.oddityDelegate = self.oddityDelegate return self.present(view, animated: true, completion: nil) } if new.rtype == 3, let view = OddityViewControllerManager.shareManager.storyBoard.instantiateViewController(withIdentifier: "AdsWebViewController") as? AdsWebViewController { view.adsUrlString = new.purl return self.present(view, animated: true, completion: nil) } let viewController = OddityViewControllerManager.shareManager.getDetailAndCommitViewController(new) viewController.odditySetting = self.odditySetting viewController.oddityDelegate = self.oddityDelegate self.show(viewController, sender: nil) if new.isread == 0 { new.isRead() // 设置为已读 } } } open class AdsWebViewController : UIViewController,UIViewControllerTransitioningDelegate { var adsUrlString = "" var waitView:WaitView! @IBOutlet var dissButton: UIButton! // 左上角更多按钮 @IBOutlet var webView:UIWebView! let DismissedAnimation = CustomViewControllerDismissedAnimation() let PresentdAnimation = CustomViewControllerPresentdAnimation() // 切换全屏活着完成反悔上一个界面 @IBAction func touchViewController(_ sender: AnyObject) { return self.dismiss(animated: true, completion: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.transitioningDelegate = self self.modalPresentationCapturesStatusBarAppearance = false // self.modalPresentationStyle = UIModalPresentationStyle.Custom } open override func viewDidLoad() { super.viewDidLoad() self.webView.delegate = self guard let encodedStr = adsUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),let url = URL(string: encodedStr) else { return } self.webView.loadRequest(URLRequest(url: url)) } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PresentdAnimation } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DismissedAnimation } } extension AdsWebViewController:UIWebViewDelegate,WaitLoadProtcol { public func webViewDidStartLoad(_ webView: UIWebView) { self.showWaitLoadView() } public func webViewDidFinishLoad(_ webView: UIWebView) { self.hiddenWaitLoadView() } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.waitView.setNoNetWork { guard let encodedStr = self.adsUrlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),let url = URL(string: encodedStr) else { return } self.webView.loadRequest(URLRequest(url: url)) } } }
mit
4e0ae261088065a9723fe9d225de6723
30.137097
192
0.58465
4.935236
false
false
false
false
WeltN24/Carlos
Example/Example/MemoryWarningSampleViewController.swift
1
1049
import Carlos import Combine import Foundation import UIKit class MemoryWarningSampleViewController: BaseCacheViewController { private var cache: BasicCache<URL, NSData>! private var token: NSObjectProtocol? var cancellable: AnyCancellable? override func fetchRequested() { super.fetchRequested() cancellable = cache.get(URL(string: urlKeyField?.text ?? "")!) .sink(receiveCompletion: { _ in }, receiveValue: { _ in }) } override func titleForScreen() -> String { "Memory warnings" } override func setupCache() { super.setupCache() cache = simpleCache() } @IBAction func memoryWarningSwitchValueChanged(_ sender: UISwitch) { if sender.isOn, token == nil { token = cache.listenToMemoryWarnings() } else if let token = token, !sender.isOn { unsubscribeToMemoryWarnings(token) self.token = nil } } @IBAction func simulateMemoryWarning(_: AnyObject) { NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil) } }
mit
64d5a45c65332e6aedcf77575d409176
24.585366
105
0.709247
4.580786
false
false
false
false
rdlester/simply-giphy
Pods/ReactiveCocoa/ReactiveCocoa/NSObject+Intercepting.swift
1
16280
import Foundation import ReactiveSwift import enum Result.NoError /// Whether the runtime subclass has already been prepared for method /// interception. fileprivate let interceptedKey = AssociationKey(default: false) /// Holds the method signature cache of the runtime subclass. fileprivate let signatureCacheKey = AssociationKey<SignatureCache>() /// Holds the method selector cache of the runtime subclass. fileprivate let selectorCacheKey = AssociationKey<SelectorCache>() extension Reactive where Base: NSObject { /// Create a signal which sends a `next` event at the end of every /// invocation of `selector` on the object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A trigger signal. public func trigger(for selector: Selector) -> Signal<(), NoError> { return base.intercept(selector).map { _ in } } /// Create a signal which sends a `next` event, containing an array of /// bridged arguments, at the end of every invocation of `selector` on the /// object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A signal that sends an array of bridged arguments. public func signal(for selector: Selector) -> Signal<[Any?], NoError> { return base.intercept(selector).map(unpackInvocation) } } extension NSObject { /// Setup the method interception. /// /// - parameters: /// - object: The object to be intercepted. /// - selector: The selector of the method to be intercepted. /// /// - returns: A signal that sends the corresponding `NSInvocation` after /// every invocation of the method. @nonobjc fileprivate func intercept(_ selector: Selector) -> Signal<AnyObject, NoError> { guard let method = class_getInstanceMethod(objcClass, selector) else { fatalError("Selector `\(selector)` does not exist in class `\(String(describing: objcClass))`.") } let typeEncoding = method_getTypeEncoding(method)! assert(checkTypeEncoding(typeEncoding)) return synchronized { let alias = selector.alias let stateKey = AssociationKey<InterceptingState?>(alias) let interopAlias = selector.interopAlias if let state = associations.value(forKey: stateKey) { return state.signal } let subclass: AnyClass = swizzleClass(self) let subclassAssociations = Associations(subclass as AnyObject) // FIXME: Compiler asks to handle a mysterious throw. try! ReactiveCocoa.synchronized(subclass) { let isSwizzled = subclassAssociations.value(forKey: interceptedKey) let signatureCache: SignatureCache let selectorCache: SelectorCache if isSwizzled { signatureCache = subclassAssociations.value(forKey: signatureCacheKey) selectorCache = subclassAssociations.value(forKey: selectorCacheKey) } else { signatureCache = SignatureCache() selectorCache = SelectorCache() subclassAssociations.setValue(signatureCache, forKey: signatureCacheKey) subclassAssociations.setValue(selectorCache, forKey: selectorCacheKey) subclassAssociations.setValue(true, forKey: interceptedKey) enableMessageForwarding(subclass, selectorCache) setupMethodSignatureCaching(subclass, signatureCache) } selectorCache.cache(selector) if signatureCache[selector] == nil { let signature = NSMethodSignature.signature(withObjCTypes: typeEncoding) signatureCache[selector] = signature } // If an immediate implementation of the selector is found in the // runtime subclass the first time the selector is intercepted, // preserve the implementation. // // Example: KVO setters if the instance is swizzled by KVO before RAC // does. if !class_respondsToSelector(subclass, interopAlias) { let immediateImpl = class_getImmediateMethod(subclass, selector) .flatMap(method_getImplementation) .flatMap { $0 != _rac_objc_msgForward ? $0 : nil } if let impl = immediateImpl { let succeeds = class_addMethod(subclass, interopAlias, impl, typeEncoding) precondition(succeeds, "RAC attempts to swizzle a selector that has message forwarding enabled with a runtime injected implementation. This is unsupported in the current version.") } } } let state = InterceptingState(lifetime: reactive.lifetime) associations.setValue(state, forKey: stateKey) // Start forwarding the messages of the selector. _ = class_replaceMethod(subclass, selector, _rac_objc_msgForward, typeEncoding) return state.signal } } } /// Swizzle `realClass` to enable message forwarding for method interception. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. private func enableMessageForwarding(_ realClass: AnyClass, _ selectorCache: SelectorCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass) typealias ForwardInvocationImpl = @convention(block) (Unmanaged<NSObject>, AnyObject) -> Void let newForwardInvocation: ForwardInvocationImpl = { objectRef, invocation in let selector = invocation.selector! let alias = selectorCache.alias(for: selector) let interopAlias = selectorCache.interopAlias(for: selector) defer { let stateKey = AssociationKey<InterceptingState?>(alias) if let state = objectRef.takeUnretainedValue().associations.value(forKey: stateKey) { state.observer.send(value: invocation) } } let method = class_getInstanceMethod(perceivedClass, selector)! let typeEncoding = method_getTypeEncoding(method) if class_respondsToSelector(realClass, interopAlias) { // RAC has preserved an immediate implementation found in the runtime // subclass that was supplied by an external party. // // As the KVO setter relies on the selector to work, it has to be invoked // by swapping in the preserved implementation and restore to the message // forwarder afterwards. // // However, the IMP cache would be thrashed due to the swapping. let topLevelClass: AnyClass = object_getClass(objectRef.takeUnretainedValue()) // The locking below prevents RAC swizzling attempts from intervening the // invocation. // // Given the implementation of `swizzleClass`, `topLevelClass` can only be: // (1) the same as `realClass`; or (2) a subclass of `realClass`. In other // words, this would deadlock only if the locking order is not followed in // other nested locking scenarios of these metaclasses at compile time. synchronized(topLevelClass) { func swizzle() { let interopImpl = class_getMethodImplementation(topLevelClass, interopAlias) let previousImpl = class_replaceMethod(topLevelClass, selector, interopImpl, typeEncoding) invocation.invoke() _ = class_replaceMethod(topLevelClass, selector, previousImpl, typeEncoding) } if topLevelClass != realClass { synchronized(realClass) { // In addition to swapping in the implementation, the message // forwarding needs to be temporarily disabled to prevent circular // invocation. _ = class_replaceMethod(realClass, selector, nil, typeEncoding) swizzle() _ = class_replaceMethod(realClass, selector, _rac_objc_msgForward, typeEncoding) } } else { swizzle() } } return } if let impl = method_getImplementation(method), impl != _rac_objc_msgForward { // The perceived class, or its ancestors, responds to the selector. // // The implementation is invoked through the selector alias, which // reflects the latest implementation of the selector in the perceived // class. if class_getMethodImplementation(realClass, alias) != impl { // Update the alias if and only if the implementation has changed, so as // to avoid thrashing the IMP cache. _ = class_replaceMethod(realClass, alias, impl, typeEncoding) } invocation.setSelector(alias) invocation.invoke() return } // Forward the invocation to the closest `forwardInvocation(_:)` in the // inheritance hierarchy, or the default handler returned by the runtime // if it finds no implementation. typealias SuperForwardInvocation = @convention(c) (Unmanaged<NSObject>, Selector, AnyObject) -> Void let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.forwardInvocation) let forwardInvocation = unsafeBitCast(impl, to: SuperForwardInvocation.self) forwardInvocation(objectRef, ObjCSelector.forwardInvocation, invocation) } _ = class_replaceMethod(realClass, ObjCSelector.forwardInvocation, imp_implementationWithBlock(newForwardInvocation as Any), ObjCMethodEncoding.forwardInvocation) } /// Swizzle `realClass` to accelerate the method signature retrieval, using a /// signature cache that covers all known intercepted selectors of `realClass`. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. /// - signatureCache: The method signature cache. private func setupMethodSignatureCaching(_ realClass: AnyClass, _ signatureCache: SignatureCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass) let newMethodSignatureForSelector: @convention(block) (Unmanaged<NSObject>, Selector) -> AnyObject? = { objectRef, selector in if let signature = signatureCache[selector] { return signature } typealias SuperMethodSignatureForSelector = @convention(c) (Unmanaged<NSObject>, Selector, Selector) -> AnyObject? let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.methodSignatureForSelector) let methodSignatureForSelector = unsafeBitCast(impl, to: SuperMethodSignatureForSelector.self) return methodSignatureForSelector(objectRef, ObjCSelector.methodSignatureForSelector, selector) } _ = class_replaceMethod(realClass, ObjCSelector.methodSignatureForSelector, imp_implementationWithBlock(newMethodSignatureForSelector as Any), ObjCMethodEncoding.methodSignatureForSelector) } /// The state of an intercepted method specific to an instance. private final class InterceptingState { let (signal, observer) = Signal<AnyObject, NoError>.pipe() /// Initialize a state specific to an instance. /// /// - parameters: /// - lifetime: The lifetime of the instance. init(lifetime: Lifetime) { lifetime.ended.observeCompleted(observer.sendCompleted) } } private final class SelectorCache { private var map: [Selector: (main: Selector, interop: Selector)] = [:] init() {} /// Cache the aliases of the specified selector in the cache. /// /// - warning: Any invocation of this method must be synchronized against the /// runtime subclass. @discardableResult func cache(_ selector: Selector) -> (main: Selector, interop: Selector) { if let pair = map[selector] { return pair } let aliases = (selector.alias, selector.interopAlias) map[selector] = aliases return aliases } /// Get the alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func alias(for selector: Selector) -> Selector { if let (main, _) = map[selector] { return main } return selector.alias } /// Get the secondary alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func interopAlias(for selector: Selector) -> Selector { if let (_, interop) = map[selector] { return interop } return selector.interopAlias } } // The signature cache for classes that have been swizzled for method // interception. // // Read-copy-update is used here, since the cache has multiple readers but only // one writer. private final class SignatureCache { // `Dictionary` takes 8 bytes for the reference to its storage and does CoW. // So it should not encounter any corrupted, partially updated state. private var map: [Selector: AnyObject] = [:] init() {} /// Get or set the signature for the specified selector. /// /// - warning: Any invocation of the setter must be synchronized against the /// runtime subclass. /// /// - parameters: /// - selector: The method signature. subscript(selector: Selector) -> AnyObject? { get { return map[selector] } set { if map[selector] == nil { map[selector] = newValue } } } } /// Assert that the method does not contain types that cannot be intercepted. /// /// - parameters: /// - types: The type encoding C string of the method. /// /// - returns: `true`. private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool { // Some types, including vector types, are not encoded. In these cases the // signature starts with the size of the argument frame. assert(types.pointee < Int8(UInt8(ascii: "1")) || types.pointee > Int8(UInt8(ascii: "9")), "unknown method return type not supported in type encoding: \(String(cString: types))") assert(types.pointee != Int8(UInt8(ascii: "(")), "union method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "{")), "struct method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "[")), "array method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "j")), "complex method return type not supported") return true } /// Extract the arguments of an `NSInvocation` as an array of objects. /// /// - parameters: /// - invocation: The `NSInvocation` to unpack. /// /// - returns: An array of objects. private func unpackInvocation(_ invocation: AnyObject) -> [Any?] { let invocation = invocation as AnyObject let methodSignature = invocation.objcMethodSignature! let count = UInt(methodSignature.numberOfArguments!) var bridged = [Any?]() bridged.reserveCapacity(Int(count - 2)) // Ignore `self` and `_cmd` at index 0 and 1. for position in 2 ..< count { let rawEncoding = methodSignature.argumentType(at: position) let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined func extract<U>(_ type: U.Type) -> U { let pointer = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) defer { pointer.deallocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) } invocation.copy(to: pointer, forArgumentAt: Int(position)) return pointer.assumingMemoryBound(to: type).pointee } let value: Any? switch encoding { case .char: value = NSNumber(value: extract(CChar.self)) case .int: value = NSNumber(value: extract(CInt.self)) case .short: value = NSNumber(value: extract(CShort.self)) case .long: value = NSNumber(value: extract(CLong.self)) case .longLong: value = NSNumber(value: extract(CLongLong.self)) case .unsignedChar: value = NSNumber(value: extract(CUnsignedChar.self)) case .unsignedInt: value = NSNumber(value: extract(CUnsignedInt.self)) case .unsignedShort: value = NSNumber(value: extract(CUnsignedShort.self)) case .unsignedLong: value = NSNumber(value: extract(CUnsignedLong.self)) case .unsignedLongLong: value = NSNumber(value: extract(CUnsignedLongLong.self)) case .float: value = NSNumber(value: extract(CFloat.self)) case .double: value = NSNumber(value: extract(CDouble.self)) case .bool: value = NSNumber(value: extract(CBool.self)) case .object: value = extract((AnyObject?).self) case .type: value = extract((AnyClass?).self) case .selector: value = extract((Selector?).self) case .undefined: var size = 0, alignment = 0 NSGetSizeAndAlignment(rawEncoding, &size, &alignment) let buffer = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment) defer { buffer.deallocate(bytes: size, alignedTo: alignment) } invocation.copy(to: buffer, forArgumentAt: Int(position)) value = NSValue(bytes: buffer, objCType: rawEncoding) } bridged.append(value) } return bridged }
apache-2.0
4874dc4bbb704eae283224c3628be212
34.545852
186
0.714128
4.270724
false
false
false
false
narner/AudioKit
AudioKit/Common/Internals/AudioUnit Host/AKAudioUnitInstrument.swift
1
1868
// // AKAudioUnitInstrument.swift // AudioKit // // Created by Ryan Francesconi, revision history on Github. // Copyright © 2017 AudioKit. All rights reserved. // /// Wrapper for audio units that accept MIDI (ie. instruments) open class AKAudioUnitInstrument: AKMIDIInstrument { /// Initialize the audio unit instrument /// /// - parameter audioUnit: AVAudioUnitMIDIInstrument to wrap /// public init?(audioUnit: AVAudioUnitMIDIInstrument) { super.init() self.midiInstrument = audioUnit AudioKit.engine.attach(audioUnit) // assign the output to the mixer self.avAudioNode = audioUnit self.name = audioUnit.name } /// Send MIDI Note On information to the audio unit /// /// - Parameters /// - noteNumber: MIDI note number to play /// - velocity: MIDI velocity to play the note at /// - channel: MIDI channel to play the note on /// open func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity = 64, channel: MIDIChannel = 0) { guard self.midiInstrument != nil else { AKLog("no midiInstrument exists") return } self.midiInstrument!.startNote(noteNumber, withVelocity: velocity, onChannel: channel) } /// Send MIDI Note Off information to the audio unit /// /// - Parameters /// - noteNumber: MIDI note number to stop /// - channel: MIDI channel to stop the note on /// override open func stop(noteNumber: MIDINoteNumber) { stop(noteNumber: noteNumber, channel: 0) } override open func stop(noteNumber: MIDINoteNumber, channel: MIDIChannel) { guard self.midiInstrument != nil else { AKLog("no midiInstrument exists") return } self.midiInstrument!.stopNote(noteNumber, onChannel: channel) } }
mit
74e50b0d2b14c3f793d60fd85fb4a4e7
30.644068
103
0.641671
4.750636
false
false
false
false
Sadmansamee/quran-ios
Quran/Container.swift
1
7937
// // Container.swift // Quran // // Created by Mohamed Afifi on 4/20/16. // Copyright © 2016 Quran.com. All rights reserved. // import UIKit class Container { fileprivate static let DownloadsBackgroundIdentifier = "com.quran.ios.downloading.audio" fileprivate let imagesCache: Cache<Int, UIImage> = { let cache = Cache<Int, UIImage>() cache.countLimit = 5 return cache }() fileprivate var downloadManager: DownloadManager! = nil init() { let configuration = URLSessionConfiguration.background(withIdentifier: "DownloadsBackgroundIdentifier") downloadManager = URLSessionDownloadManager(configuration: configuration, persistence: createSimplePersistence()) } func createRootViewController() -> UIViewController { let controller = MainTabBarController() controller.viewControllers = [createSurasNavigationController(), createJuzsNavigationController(), createBookmarksController()] return controller } func createSurasNavigationController() -> UIViewController { return SurasNavigationController(rootViewController: createSurasViewController()) } func createJuzsNavigationController() -> UIViewController { return JuzsNavigationController(rootViewController: createJuzsViewController()) } func createSurasViewController() -> UIViewController { return SurasViewController(dataRetriever: createSurasRetriever(), quranControllerCreator: createCreator(createQuranController)) } func createJuzsViewController() -> UIViewController { return JuzsViewController(dataRetriever: createQuartersRetriever(), quranControllerCreator: createCreator(createQuranController)) } func createSearchController() -> UIViewController { return SearchNavigationController(rootViewController: SearchViewController()) } func createSettingsController() -> UIViewController { return SettingsNavigationController(rootViewController: SettingsViewController()) } func createBookmarksController() -> UIViewController { return BookmarksNavigationController(rootViewController: createBookmarksViewController()) } func createBookmarksViewController() -> UIViewController { return BookmarksTableViewController( quranControllerCreator: createCreator(createQuranController), simplePersistence: createSimplePersistence(), lastPagesPersistence: createLastPagesPersistence(), bookmarksPersistence: createBookmarksPersistence(), ayahPersistence: createAyahTextStorage()) } func createQariTableViewController() -> QariTableViewController { return QariTableViewController(style: .plain) } func createSurasRetriever() -> AnyDataRetriever<[(Juz, [Sura])]> { return SurasDataRetriever().erasedType() } func createQuartersRetriever() -> AnyDataRetriever<[(Juz, [Quarter])]> { return QuartersDataRetriever().erasedType() } func createQuranPagesRetriever() -> AnyDataRetriever<[QuranPage]> { return QuranPagesDataRetriever().erasedType() } func createQarisDataRetriever() -> AnyDataRetriever<[Qari]> { return QariDataRetriever().erasedType() } func createAyahInfoPersistence() -> AyahInfoPersistence { return SQLiteAyahInfoPersistence() } func createAyahTextStorage() -> AyahTextPersistence { return SQLiteAyahTextPersistence() } func createAyahInfoRetriever() -> AyahInfoRetriever { return DefaultAyahInfoRetriever(persistence: createAyahInfoPersistence()) } func createQuranController(page: Int, lastPage: LastPage?) -> QuranViewController { return QuranViewController( imageService : createQuranImageService(), dataRetriever : createQuranPagesRetriever(), ayahInfoRetriever : createAyahInfoRetriever(), audioViewPresenter : createAudioBannerViewPresenter(), qarisControllerCreator : createCreator(createQariTableViewController), bookmarksPersistence : createBookmarksPersistence(), lastPagesPersistence : createLastPagesPersistence(), page : page, lastPage : lastPage ) } func createCreator<CreatedObject, Parameters>( _ creationClosure: @escaping (Parameters) -> CreatedObject) -> AnyCreator<CreatedObject, Parameters> { return AnyCreator(createClosure: creationClosure).erasedType() } func createQuranImageService() -> QuranImageService { return DefaultQuranImageService(imagesCache: createImagesCache()) } func createImagesCache() -> Cache<Int, UIImage> { return imagesCache } func createAudioBannerViewPresenter() -> AudioBannerViewPresenter { return DefaultAudioBannerViewPresenter(persistence: createSimplePersistence(), qariRetreiver: createQarisDataRetriever(), gaplessAudioPlayer: createGaplessAudioPlayerInteractor(), gappedAudioPlayer: createGappedAudioPlayerInteractor()) } func createUserDefaults() -> UserDefaults { return UserDefaults.standard } func createSimplePersistence() -> SimplePersistence { return UserDefaultsSimplePersistence(userDefaults: createUserDefaults()) } func createSuraLastAyahFinder() -> LastAyahFinder { return SuraBasedLastAyahFinder() } func createPageLastAyahFinder() -> LastAyahFinder { return PageBasedLastAyahFinder() } func createJuzLastAyahFinder() -> LastAyahFinder { return JuzBasedLastAyahFinder() } func createDownloadManager() -> DownloadManager { return downloadManager } func createGappedAudioDownloader() -> AudioFilesDownloader { return GappedAudioFilesDownloader(downloader: createDownloadManager()) } func createGaplessAudioDownloader() -> AudioFilesDownloader { return GaplessAudioFilesDownloader(downloader: createDownloadManager()) } func createGappedAudioPlayer() -> AudioPlayer { return GappedAudioPlayer() } func createGaplessAudioPlayer() -> AudioPlayer { return GaplessAudioPlayer(timingRetriever: createQariTimingRetriever()) } func createGaplessAudioPlayerInteractor() -> AudioPlayerInteractor { return GaplessAudioPlayerInteractor(downloader: createGaplessAudioDownloader(), lastAyahFinder: createJuzLastAyahFinder(), player: createGaplessAudioPlayer()) } func createGappedAudioPlayerInteractor() -> AudioPlayerInteractor { return GappedAudioPlayerInteractor(downloader: createGappedAudioDownloader(), lastAyahFinder: createJuzLastAyahFinder(), player: createGappedAudioPlayer()) } func createQariTimingRetriever() -> QariTimingRetriever { return SQLiteQariTimingRetriever(persistence: createQariAyahTimingPersistence()) } func createQariAyahTimingPersistence() -> QariAyahTimingPersistence { return SQLiteAyahTimingPersistence() } func createBookmarksPersistence() -> BookmarksPersistence { return SQLiteBookmarksPersistence() } func createLastPagesPersistence() -> LastPagesPersistence { return SQLiteLastPagesPersistence(simplePersistence: createSimplePersistence()) } }
mit
405cfeda24d8fcafbf70ddfd01c32b2a
37.524272
137
0.671749
6.668908
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/RepositoryDetail/View/RepoDetailHeaderView.swift
1
5698
// // RepoDetailHeaderView.swift // OpenCode // // Created by 陈亮 on 16/5/14. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit class RepoDetailHeaderView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ var headerImgView:UIImageView? var repoNameLabel:UILabel? var repoDescLabel:UILabel? var infoBlock1:RepoInfoView? var infoBlock2:RepoInfoView? var infoBlock3:RepoInfoView? var repoDesc1:RepoDescView?//isPrivate var repoDesc2:RepoDescView?//language var repoDesc3:RepoDescView?//issues num var repoDesc4:RepoDescView?//branch num var repoDesc5:RepoDescView?//create data var repoDesc6:RepoDescView?//size override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func initView(){ let headerView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 200)) headerView.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1) headerImgView = UIImageView(frame: CGRect(x: headerView.frame.width / 2 - 50, y: 25, width: 100, height: 100)) //headerImgView!.backgroundColor = UIColor(white: 1, alpha: 1) headerView.addSubview(headerImgView!) self.repoNameLabel = UILabel(frame: CGRect(x: 0, y: 130, width: self.frame.width, height: 40)) repoNameLabel!.text = "" repoNameLabel!.textColor = UIColor(white: 1, alpha: 1) repoNameLabel!.font = UIFont(descriptor: UIFontDescriptor(), size: 20) repoNameLabel!.textAlignment = NSTextAlignment.Center headerView.addSubview(repoNameLabel!) self.repoDescLabel = UILabel(frame: CGRect(x: 0, y: 160, width: self.frame.width, height: 40)) repoDescLabel!.text = "" repoDescLabel!.numberOfLines = 2 repoDescLabel!.textColor = UIColor(white: 1, alpha: 1) repoDescLabel!.font = UIFont(descriptor: UIFontDescriptor(), size: 14) repoDescLabel!.textAlignment = NSTextAlignment.Center headerView.addSubview(repoDescLabel!) //信息部分 let infoBlockWidth = floor(frame.width / 3) let infoBlockSpace = (frame.width - infoBlockWidth * 3)/2 self.infoBlock1 = RepoInfoView(frame: CGRectMake(0, 200, infoBlockWidth, 40), name: "Stargazers", value: 1) self.infoBlock2 = RepoInfoView(frame: CGRectMake(infoBlockWidth * 1 + infoBlockSpace * 1, 200, infoBlockWidth, 40), name: "Watchers", value: 3) self.infoBlock3 = RepoInfoView(frame: CGRectMake(infoBlockWidth * 2 + infoBlockSpace * 2, 200, infoBlockWidth, 40), name: "Forks", value: 5) self.addSubview(infoBlock1!) self.addSubview(infoBlock2!) self.addSubview(infoBlock3!) //描述部分 let descStartY:CGFloat = 250 let descWidth = floor(frame.width / 2) let descHeight:CGFloat = 40 self.repoDesc1 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*0, descWidth, 40), icon: UIImage(named: "watch")!, desc: "") repoDesc1!.backgroundColor = UIColor.whiteColor() self.repoDesc2 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*0, descWidth, 40), icon: UIImage(named: "code")!, desc: "") repoDesc2!.backgroundColor = UIColor.whiteColor() self.repoDesc3 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*1, descWidth, 40), icon: UIImage(named: "comment")!, desc: "") repoDesc3!.backgroundColor = UIColor.whiteColor() self.repoDesc4 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*1, descWidth, 40), icon: UIImage(named: "fork")!, desc: "") repoDesc4!.backgroundColor = UIColor.whiteColor() self.repoDesc5 = RepoDescView(frame: CGRectMake(0, descStartY + descHeight*2, descWidth, 40), icon: UIImage(named: "tag")!, desc: "") repoDesc5!.backgroundColor = UIColor.whiteColor() self.repoDesc6 = RepoDescView(frame: CGRectMake(descWidth, descStartY + descHeight*2, descWidth, 40), icon: UIImage(named: "repo")!, desc: "") repoDesc6!.backgroundColor = UIColor.whiteColor() self.addSubview(repoDesc1!) self.addSubview(repoDesc2!) self.addSubview(repoDesc3!) self.addSubview(repoDesc4!) self.addSubview(repoDesc5!) self.addSubview(repoDesc6!) self.addSubview(headerView) } func setData(icon:UIImage?, repoName:String?, repoDesc:String?, blockValue1:Int?, blockValue2:Int?, blockValue3:Int?){ self.headerImgView?.image = icon self.repoNameLabel?.text = repoName self.repoDescLabel?.text = repoDesc self.infoBlock1?.setValue(blockValue1!) self.infoBlock2?.setValue(blockValue2!) self.infoBlock3?.setValue(blockValue3!) } func setDescData(isPrivate:Bool, language:String, issuesNum:Int, defaultBranch:String, createdDate:String, size:Int){ self.repoDesc1?.descLabel.text = isPrivate ? "Private" : "Public" self.repoDesc2?.descLabel.text = language self.repoDesc3?.descLabel.text = "\(issuesNum) Issues" self.repoDesc4?.descLabel.text = defaultBranch self.repoDesc5?.descLabel.text = GithubTime(dateStr: createdDate).onlyDay() self.repoDesc6?.descLabel.text = size > 1024 ? "\(String(format: "%.2f", Float(size) / 1024))MB":"\(size)KB" } }
gpl-2.0
8a3bc44bab04e5ace1f0c6d7c592d9ef
45.900826
153
0.665551
4.299242
false
false
false
false
crxiaoluo/DouYuZhiBo
DYZB/DYZB/Class/Tools/Swift+Extension/Foundation/String+Extension.swift
1
2952
// // String-Extension.swift // date // // Created by Apple on 16/9/9. // Copyright © 2016年 Apple. All rights reserved. // import UIKit extension String { /** 根据日期字符串生成对应的日期格式化字符串 */ func CreateDateString () -> String { let fmt = DateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" // fmt.locale = NSLocale(localeIdentifier: "en") fmt.locale = Locale.current guard let creatDate = fmt.date(from: self) else { return "" } //获取当前时间 let nowDate = Date() //比较两个时间 let intervalDoble = (nowDate.timeIntervalSince1970 - creatDate.timeIntervalSince1970) let interval = quad_t (intervalDoble) //创建日历对象 let calender = Calendar.current let comps = (calender as NSCalendar).components(.year, from: creatDate, to: nowDate, options: []) if comps.year! < 1 { //昨天 if calender.isDateInYesterday(creatDate) { //ios 8 fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.string(from: creatDate) return timeStr }else if calender.isDateInToday(creatDate) { if interval >= 60 * 60 { //1天内 return "\(interval/(60 * 60))小时前" } if interval > 60 { //1小时内 return "\(interval / 60)分钟前" } else{ //1分钟内 return "刚刚" } }else { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.string(from: creatDate) return timeStr } }else { //超出一年 fmt.dateFormat = "yyyy-MM-dd" let timeStr = fmt.string(from: creatDate) return timeStr } } } extension String { func setSize(_ font: CGFloat , width: CGFloat , height: CGFloat) -> CGSize { let size = CGSize(width: width, height: height) let rect = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: font) ], context:nil) return rect.size } func setSize(_ font : CGFloat , width: CGFloat) -> CGSize { return setSize(font, width: width, height: CGFloat.greatestFiniteMagnitude) } func setSize(_ font : CGFloat) -> CGSize { return setSize(font, width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) } }
mit
d9cbbc4e33580e1fd61992e82e76dea4
24
165
0.48885
4.95614
false
false
false
false
sarukun99/CoreStore
CoreStore/Convenience Helpers/NSProgress+Convenience.swift
1
4058
// // NSProgress+Convenience.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - NSProgress public extension NSProgress { // MARK: Public /** Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO. - parameter closure: the closure to execute on progress change */ public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) { self.progressObserver.progressHandler = closure } // MARK: Private private struct PropertyKeys { static var progressObserver: Void? } private var progressObserver: ProgressObserver { get { let object: ProgressObserver? = getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self) if let observer = object { return observer } let observer = ProgressObserver(self) setAssociatedRetainedObject( observer, forKey: &PropertyKeys.progressObserver, inObject: self ) return observer } } } @objc private final class ProgressObserver: NSObject { private unowned let progress: NSProgress private var progressHandler: ((progress: NSProgress) -> Void)? { didSet { let progressHandler = self.progressHandler if (progressHandler == nil) == (oldValue == nil) { return } if let _ = progressHandler { self.progress.addObserver( self, forKeyPath: "fractionCompleted", options: [.Initial, .New], context: nil ) } else { self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } } private init(_ progress: NSProgress) { self.progress = progress super.init() } deinit { if let _ = self.progressHandler { self.progressHandler = nil self.progress.removeObserver(self, forKeyPath: "fractionCompleted") } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else { return } GCDQueue.Main.async { [weak self] () -> Void in self?.progressHandler?(progress: progress) } } }
mit
b90ccf8c0ae59b053b7ec3123d55469e
29.977099
157
0.588221
5.536153
false
false
false
false
iOS-Swift-Developers/Swift
基础语法/枚举/main.swift
1
3993
// // main.swift // 枚举 // // Created by 韩俊强 on 2017/6/12. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* Swift枚举: Swift中的枚举比OC中的枚举强大, 因为Swift中的枚举是一等类型, 它可以像类和结构体一样增加属性和方法 格式: enum Method{ case 枚举值 } */ enum Method { case Add case Sub case Mul case Div //可以连在一起写 // case Add, Sub, Mul, Div } // 可以使用枚举类型变量或者常量接收枚举值 var m:Method = .Add print(m) // 注意: 如果变量或者常量没有指定类型, 那么前面必须加上该值属于哪个枚举类型 var m1 = Method.Add print(m1) // 利用Switch匹配 // 注意: 如果case中包含了所有的值, 可以不写default; 如果case没有包含枚举中所有的值, 必须写default switch (Method.Add){ case Method.Add: print("加法") case Method.Sub: print("减法") case Method.Mul: print("除法") case Method.Div: print("乘法") //default: // print("都不是") } /* 原始值: OC中枚举的本质就是整数,所以OC中的枚举是有原始值的,默认是从0开始 而Swift中的枚举默认是没有原始值的, 但是可以在定义时告诉系统让枚举有原始值 enum Method: 枚举值原始值类型{ case 枚举值 } */ enum Method2: Int { case Add, Sub, Mul, Div } // 和OC中的枚举一样, 也可以指定原始值, 后面的值默认 +1 enum Method3: Int { case Add = 5, Sub, Mul, Div } // Swift中的枚举除了可以指定整型以外还可以指定其他类型, 但是如果指定其他类型, 必须给所有枚举值赋值, 因为不能自动递增 enum Method4: Double { case Add = 5.0, Sub = 6.0, Mul = 7.0, Div = 8.0 } // rawValue代表将枚举值转换为原始值, 注意老版本中转换为原始值的方法名叫toRaw // 最新的Swift版本不再支持toRaw和fromRaw了,只有rawValue属性和hashValue属性了! print(Method4.Sub.rawValue) // hashValue来访问成员值所对应的哈希值,这个哈希值是不能改变的,由编译器自动生成,之后不可改变,Swift在背后实际上使用哈希值来识别枚举符号的(即成员) print(Method4.Mul.hashValue) // 原始值转换为枚举值 enum Method5: String { case Add = "add", Sub = "sub", Mul = "mul", Div = "div" } // 通过原始值创建枚举值 /* 注意: 1.原始值区分大小写 2.返回的是一个可选值,因为原始值对应的枚举值不一定存在 3.老版本中为fromRaw("add") */ let m2:Method5 = Method5(rawValue: "add")! print(m2) //func chooseMethod(op:Method2) func chooseMethod5(rawString: String) { // 由于返回值是可选类型, 所以有可能为nil, 最好使用可选绑定 if let opE = Method5(rawValue: rawString) { switch (opE) { case .Add: print("加法") case .Sub: print("减法") case .Mul: print("除法") case .Div: print("乘法") } } } print(chooseMethod5(rawString: "add")) /* 枚举相关值: 可以让枚举值对应的原始值不是唯一的, 而是一个变量. 每一个枚举可以是在某种模式下的一些特定值 */ enum lineSegmentDescriptor { case StartAndEndPattern(start: Double, end: Double) case StartAndLengthPattern(start: Double, length: Double) } var lsd = lineSegmentDescriptor.StartAndLengthPattern(start: 0.0, length: 100.0) lsd = lineSegmentDescriptor.StartAndEndPattern(start: 0.0, end: 50.0) print(lsd) // 利用switch提取枚举关联值 /* switch lsd { case .StartAndEndPattern(let s, let e): print("start = \(s) end = \(e)") case .StartAndLengthPattern(let s, let l): print("start = \(s) lenght = \(l)") } */ // 提取关联值优化写法 switch lsd { case let .StartAndEndPattern(s, e): print("start = \(s) end = \(e)") case .StartAndLengthPattern(let s, let l): print("start = \(s) l = \(l)") }
mit
fb8bbc5084b74a5c76c46f89de74836f
17.270968
83
0.659605
2.624652
false
false
false
false
StevenUpForever/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/CLIBootstrapper.swift
2
3926
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl @objc open class CLIBootstrapper : NSObject { open static func bootstrap() -> Int32 { let arguments = Array(CommandLine.arguments.dropFirst(1)) let environment = ProcessInfo.processInfo.environment let (cli, writer, reporter, _) = CLI.fromArguments(arguments, environment: environment).bootstrap() return CLIRunner(cli: cli, writer: writer, reporter: reporter).runForStatus() } } struct CLIRunner : Runner { let cli: CLI let writer: Writer let reporter: EventReporter func run() -> CommandResult { switch self.cli { case .run(let command): return BaseCommandRunner(reporter: self.reporter, command: command).run() case .show(let help): return HelpRunner(reporter: self.reporter, help: help).run() case .print(let action): return PrintRunner(action: action, writer: self.writer).run() } } func runForStatus() -> Int32 { // Start the runner let result = self.run() // Now we're done. Terminate any remaining asynchronous work for handle in result.handles { handle.terminate() } switch result.outcome { case .failure(let message): self.reporter.reportError(message) return 1 case .success(.some(let subject)): self.reporter.report(subject) fallthrough default: return 0 } } } struct PrintRunner : Runner { let action: Action let writer: Writer func run() -> CommandResult { switch self.action { case .core(let action): let output = action.printable() self.writer.write(output) return .success(nil) default: break } return .failure("Action \(self.action) not printable") } } extension CLI { struct CLIError : Error, CustomStringConvertible { let description: String } public static func fromArguments(_ arguments: [String], environment: [String : String]) -> CLI { do { let (_, cli) = try CLI.parser.parse(arguments) return cli.appendEnvironment(environment) } catch let error as (CustomStringConvertible & Error) { let help = Help(outputOptions: OutputOptions(), error: error, command: nil) return CLI.show(help) } catch { let error = CLIError(description: "An Unknown Error Occurred") let help = Help(outputOptions: OutputOptions(), error: error, command: nil) return CLI.show(help) } } public func bootstrap() -> (CLI, Writer, EventReporter, FBControlCoreLoggerProtocol) { let writer = self.createWriter() let reporter = self.createReporter(writer) if case .run(let command) = self { let configuration = command.configuration let debugEnabled = configuration.outputOptions.contains(OutputOptions.DebugLogging) let bridge = ControlCoreLoggerBridge(reporter: reporter) let logger = LogReporter(bridge: bridge, debug: debugEnabled) FBControlCoreGlobalConfiguration.defaultLogger = logger return (self, writer, reporter, logger) } let logger = FBControlCoreGlobalConfiguration.defaultLogger return (self, writer, reporter, logger) } private func createWriter() -> Writer { switch self { case .show: return FileHandleWriter.stdErrWriter case .print: return FileHandleWriter.stdOutWriter case .run(let command): return command.createWriter() } } } extension Command { func createWriter() -> Writer { for action in self.actions { if case .stream = action { return FileHandleWriter.stdErrWriter } } return FileHandleWriter.stdOutWriter } }
bsd-3-clause
74a6edfa02380598a1159ac90a4e714b
28.969466
103
0.680846
4.267391
false
false
false
false
SlackKit/SKServer
Sources/SKServer/Model/WebhookRequest.swift
3
2253
// // WebhookRequest.swift // // Copyright © 2017 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct WebhookRequest { public let token: String? public let teamID: String? public let teamDomain: String? public let channelID: String? public let channelName: String? public let ts: String? public let userID: String? public let userName: String? public let command: String? public let text: String? public let triggerWord: String? public let responseURL: String? internal init(request: [String: Any]?) { token = request?["token"] as? String teamID = request?["team_id"] as? String teamDomain = request?["team_domain"] as? String channelID = request?["channel_id"] as? String channelName = request?["channel_name"] as? String ts = request?["timestamp"] as? String userID = request?["user_id"] as? String userName = request?["user_name"] as? String command = request?["command"] as? String text = request?["text"] as? String triggerWord = request?["trigger_word"] as? String responseURL = request?["response_url"] as? String } }
mit
98525ab17d55887516eccb880841d9af
42.307692
80
0.70071
4.486056
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Entities/UserEntity.swift
2
4784
// // UserEntity.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 18/10/2016. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kUserUserIdKey: String = "userId" let kUserTokenKey: String = "token" let kUserSalutationKey: String = "salutation" let kUserFirstNameKey: String = "firstName" let kUserLastNameKey: String = "lastName" let kUserAddressKey: String = "address" let kUserAddressOptionalKey: String = "addressOptional" let kUserZipCodeKey: String = "zipCode" let kUserCountryCodeKey: String = "countryCode" let kUserStateCodeKey: String = "stateCode" let kUserCityKey: String = "city" let kUserEmailKey: String = "email" let kUserPhoneKey: String = "phone" let kUserPasswordKey: String = "password" protocol UserEntityProtocol: ParsableEntityProtocol { var userId: String! {get set} var token: String? {get set} var salutation: String! {get set} var firstName: String! {get set} var lastName: String! {get set} var address: String! {get set} var addressOptional: String? {get set} var zipCode: String! {get set} var countryCode: String! {get set} var stateCode: String! {get set} var city: String! {get set} var phone: String! {get set} var email: String! {get set} var password: String? {get set} } class UserEntity: UserEntityProtocol { // MARK: UserEntityProtocol var userId: String! var token: String? var salutation: String! var firstName: String! var lastName: String! var address: String! var addressOptional: String? var zipCode: String! var countryCode: String! var stateCode: String! var city: String! var phone: String! var email: String! var password: String? required init (){ // ... } required init(dict: Dictionary <String, Any>) { self.userId = dict[kUserUserIdKey] as! String! self.salutation = dict[kUserSalutationKey] as! String! self.firstName = dict[kUserFirstNameKey] as! String! self.lastName = dict[kUserLastNameKey] as! String! self.address = dict[kUserAddressKey] as! String! if let addr = dict[kUserAddressOptionalKey] as? String { self.addressOptional = addr } self.zipCode = dict[kUserZipCodeKey] as! String! self.city = dict[kUserCityKey] as! String! self.countryCode = dict[kUserCountryCodeKey] as! String! self.stateCode = dict[kUserStateCodeKey] as! String! self.phone = dict[kUserPhoneKey] as! String! self.email = dict[kUserEmailKey] as! String! self.token = dict[kUserTokenKey] as! String? } func serializedDict()-> Dictionary <String, Any>? { var dict:Dictionary <String, Any>? = Dictionary() // dict? unwraps dictionary into value, and then ? (Optional chaining) makes sure setValue on dictionary is called when dict is not nill only. dict?[kUserUserIdKey] = userId dict?[kUserSalutationKey] = salutation dict?[kUserFirstNameKey] = firstName dict?[kUserLastNameKey] = lastName dict?[kUserAddressKey] = address dict?[kUserAddressOptionalKey] = addressOptional dict?[kUserZipCodeKey] = zipCode dict?[kUserCityKey] = city dict?[kUserCountryCodeKey] = countryCode dict?[kUserStateCodeKey] = stateCode dict?[kUserPhoneKey] = phone dict?[kUserEmailKey] = email dict?[kUserPasswordKey] = password return dict //return ["test":"test"] } }
mit
bc315f1d30dd98ebcb349476de7a4683
35.227273
150
0.679005
4.269643
false
false
false
false
HabitRPG/habitrpg-ios
HabiticaTests/UI/Challenges/ChallengeDetailsSpecs.swift
1
3798
// // ChallengeDetailsSpecs.swift // HabiticaTests // // Created by Elliot Schrock on 10/28/17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import Foundation import Quick import Nimble @testable import Habitica import Habitica_Models class ChallengeDetailsViewModelSpec: QuickSpec { var challenge: ChallengeProtocol? override func spec() { describe("challenge details view model") { /*beforeEach { self.challenge = NSEntityDescription.insertNewObject(forEntityName: "Challenge", into: HRPGManager.shared().getManagedObjectContext()) as! Challenge } context("button cell") { it("allows joining") { let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.joinLeaveStyleProvider.buttonStateSignal.observeValues({ (state) in expect(state).to(equal(ChallengeButtonState.join)) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } it("allows leaving") { self.challenge.user = NSEntityDescription.insertNewObject(forEntityName: "User", into: HRPGManager.shared().getManagedObjectContext()) as! User let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.joinLeaveStyleProvider.buttonStateSignal.observeValues({ (state) in expect(state).to(equal(ChallengeButtonState.leave)) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) }*/ //TODO: Re enable once creator mode is in /* context("when has tasks") { it("allows publishing") { self.challenge.dailies = [ NSEntityDescription.insertNewObject(forEntityName: "ChallengeTask", into: HRPGManager.shared().getManagedObjectContext()) as! ChallengeTask] let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.publishStyleProvider.enabledSignal.observeValues({ (isEnabled) in expect(isEnabled).to(beTrue()) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } } context("when no tasks") { it("doesn't allow publishing") { let vm = ChallengeDetailViewModel(challenge: self.challenge) waitUntil(action: { (done) in vm.publishStyleProvider.enabledSignal.observeValues({ (isEnabled) in expect(isEnabled).to(beFalse()) done() }) vm.setChallenge(self.challenge) vm.joinLeaveStyleProvider.triggerStyle() }) } } }*/ context("creator cell") { } } } }
gpl-3.0
82cae903c1d89171ccb4f99a7a526f57
40.725275
191
0.475375
6.490598
false
false
false
false
apple/swift-syntax
Sources/SwiftParser/Expressions.swift
1
90746
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension TokenConsumer { func atStartOfExpression() -> Bool { switch self.at(anyIn: ExpressionStart.self) { case (.awaitTryMove, let handle)?: var backtrack = self.lookahead() backtrack.eat(handle) if backtrack.atStartOfDeclaration() || backtrack.atStartOfStatement() { // If after the 'try' we are at a declaration or statement, it can't be a valid expression. // Decide how we want to consume the 'try': // If the declaration or statement starts at a new line, the user probably just forgot to write the expression after 'try' -> parse it as a TryExpr // If the declaration or statement starts at the same line, the user maybe tried to use 'try' as a modifier -> parse it as unexpected text in front of that decl or stmt. return backtrack.currentToken.isAtStartOfLine } else { return true } case (_, _)?: return true case nil: break } if self.at(.atSign) || self.at(.inoutKeyword) { var backtrack = self.lookahead() if backtrack.canParseType() { return true } } return false } } extension Parser { public enum ExprFlavor { case basic case trailingClosure } public enum PatternContext { /// There is no ambient pattern context. case none /// We're parsing a matching pattern that is not introduced via `let` or `var`. /// /// In this context, identifiers are references to the enclosing scopes, not a variable binding. /// /// ``` /// case x.y <- 'x' must refer to some 'x' defined in another scope, it cannot be e.g. an enum type. /// ``` case matching /// We're parsing a matching pattern that is introduced via `let` or `var`. /// /// ``` /// case let x.y <- 'x' must refer to the base of some member access, y must refer to some pattern-compatible identfier /// ``` case letOrVar var admitsBinding: Bool { switch self { case .letOrVar: return true case .none, .matching: return false } } } /// Parse an expression. /// /// Grammar /// ======= /// /// expression → try-operator? await-operator? prefix-expression infix-expressions? /// expression-list → expression | expression ',' expression-list @_spi(RawSyntax) public mutating func parseExpression(_ flavor: ExprFlavor = .trailingClosure, pattern: PatternContext = .none) -> RawExprSyntax { // If we are parsing a refutable pattern, check to see if this is the start // of a let/var/is pattern. If so, parse it as an UnresolvedPatternExpr and // let pattern type checking determine its final form. // // Only do this if we're parsing a pattern, to improve QoI on malformed // expressions followed by (e.g.) let/var decls. if pattern != .none, self.at(anyIn: MatchingPatternStart.self) != nil { let pattern = self.parseMatchingPattern(context: .matching) return RawExprSyntax(RawUnresolvedPatternExprSyntax(pattern: pattern, arena: self.arena)) } return RawExprSyntax(self.parseSequenceExpression(flavor, pattern: pattern)) } } extension Parser { /// Parse a sequence of expressions. /// /// Grammar /// ======= /// /// infix-expression → infix-operator prefix-expression /// infix-expression → assignment-operator try-operator? prefix-expression /// infix-expression → conditional-operator try-operator? prefix-expression /// infix-expression → type-casting-operator /// infix-expressions → infix-expression infix-expressions? @_spi(RawSyntax) public mutating func parseSequenceExpression( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { if forDirective && self.currentToken.isAtStartOfLine { return RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } // Parsed sequence elements except 'lastElement'. var elements = [RawExprSyntax]() // The last element parsed. we don't eagarly append to 'elements' because we // don't want to populate the 'Array' unless the expression is actually // sequenced. var lastElement: RawExprSyntax lastElement = self.parseSequenceExpressionElement(flavor, forDirective: forDirective, pattern: pattern) var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { guard !lastElement.is(RawMissingExprSyntax.self), !(forDirective && self.currentToken.isAtStartOfLine) else { break } // Parse the operator. guard let (operatorExpr, rhsExpr) = self.parseSequenceExpressionOperator(flavor, pattern: pattern) else { // Not an operator. We're done. break } elements.append(lastElement) elements.append(operatorExpr) if let rhsExpr = rhsExpr { // Operator parsing returned the RHS. lastElement = rhsExpr } else if forDirective && self.currentToken.isAtStartOfLine { // Don't allow RHS at a newline for `#if` conditions. lastElement = RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) break } else { lastElement = self.parseSequenceExpressionElement(flavor, forDirective: forDirective, pattern: pattern) } } // There was no operators. Return the only element we parsed. if elements.isEmpty { return lastElement } assert(elements.count.isMultiple(of: 2), "elements must have a even number of elements") elements.append(lastElement) return RawExprSyntax(RawSequenceExprSyntax( elements: RawExprListSyntax(elements: elements, arena: self.arena), arena: self.arena)) } /// Parse an expression sequence operators. /// /// Returns `nil` if the current token is not at an operator. /// Returns a tuple of an operator expression and a optional right operand /// expression. The right operand is only returned if it is not a common /// sequence element. /// /// Grammar /// ======= /// /// infix-operator → operator /// assignment-operator → '=' /// conditional-operator → '?' expression ':' /// type-casting-operator → 'is' type /// type-casting-operator → 'as' type /// type-casting-operator → 'as' '?' type /// type-casting-operator → 'as' '!' type /// arrow-operator -> 'async' '->' /// arrow-operator -> 'throws' '->' /// arrow-operator -> 'async' 'throws' '->' mutating func parseSequenceExpressionOperator( _ flavor: ExprFlavor, pattern: PatternContext ) -> (operator: RawExprSyntax, rhs: RawExprSyntax?)? { enum ExpectedTokenKind: RawTokenKindSubset { case spacedBinaryOperator case unspacedBinaryOperator case infixQuestionMark case equal case isKeyword case asKeyword case async case arrow case throwsKeyword init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .spacedBinaryOperator: self = .spacedBinaryOperator case .unspacedBinaryOperator: self = .unspacedBinaryOperator case .infixQuestionMark: self = .infixQuestionMark case .equal: self = .equal case .isKeyword: self = .isKeyword case .asKeyword: self = .asKeyword case .identifier where lexeme.tokenText == "async": self = .async case .arrow: self = .arrow case .throwsKeyword: self = .throwsKeyword default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .spacedBinaryOperator: return .spacedBinaryOperator case .unspacedBinaryOperator: return .unspacedBinaryOperator case .infixQuestionMark: return .infixQuestionMark case .equal: return .equal case .isKeyword: return .isKeyword case .asKeyword: return .asKeyword case .async: return .identifier case .arrow: return .arrow case .throwsKeyword: return .throwsKeyword } } var contextualKeyword: SyntaxText? { switch self { case .async: return "async" default: return nil } } } switch self.at(anyIn: ExpectedTokenKind.self) { case (.spacedBinaryOperator, let handle)?, (.unspacedBinaryOperator, let handle)?: // Parse the operator. let operatorToken = self.eat(handle) let op = RawBinaryOperatorExprSyntax(operatorToken: operatorToken, arena: arena) return (RawExprSyntax(op), nil) case (.infixQuestionMark, let handle)?: // Save the '?'. let question = self.eat(handle) let firstChoice = self.parseSequenceExpression(flavor, pattern: pattern) // Make sure there's a matching ':' after the middle expr. let (unexpectedBeforeColon, colon) = self.expect(.colon) let op = RawUnresolvedTernaryExprSyntax( questionMark: question, firstChoice: firstChoice, unexpectedBeforeColon, colonMark: colon, arena: self.arena) let rhs: RawExprSyntax? if colon.isMissing { // If the colon is missing there's not much more structure we can // expect out of this expression sequence. Emit a missing expression // to end the parsing here. rhs = RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } else { rhs = nil } return (RawExprSyntax(op), rhs) case (.equal, let handle)?: switch pattern { case .matching, .letOrVar: return nil case .none: let eq = self.eat(handle) let op = RawAssignmentExprSyntax( assignToken: eq, arena: self.arena ) return (RawExprSyntax(op), nil) } case (.isKeyword, let handle)?: let isKeyword = self.eat(handle) let op = RawUnresolvedIsExprSyntax( isTok: isKeyword, arena: self.arena ) // Parse the right type expression operand as part of the 'is' production. let type = self.parseType() let rhs = RawTypeExprSyntax(type: type, arena: self.arena) return (RawExprSyntax(op), RawExprSyntax(rhs)) case (.asKeyword, let handle)?: let asKeyword = self.eat(handle) let failable = self.consume(ifAny: [.postfixQuestionMark, .exclamationMark]) let op = RawUnresolvedAsExprSyntax( asTok: asKeyword, questionOrExclamationMark: failable, arena: self.arena ) // Parse the right type expression operand as part of the 'as' production. let type = self.parseType() let rhs = RawTypeExprSyntax(type: type, arena: self.arena) return (RawExprSyntax(op), RawExprSyntax(rhs)) case (.async, _)?: if self.peek().tokenKind == .arrow || self.peek().tokenKind == .throwsKeyword { fallthrough } else { return nil } case (.arrow, _)?, (.throwsKeyword, _)?: var asyncKeyword = self.consumeIfContextualKeyword("async") var throwsKeyword = self.consume(if: .throwsKeyword) let (unexpectedBeforeArrow, arrow) = self.expect(.arrow) // Recover if effect modifiers are specified after '->' by eating them into // unexpectedAfterArrow and inserting the corresponding effects modifier as // missing into the ArrowExprSyntax. This reflect the semantics the user // originally intended. var effectModifiersAfterArrow: [RawTokenSyntax] = [] if let asyncAfterArrow = self.consumeIfContextualKeyword("async") { effectModifiersAfterArrow.append(asyncAfterArrow) if asyncKeyword == nil { asyncKeyword = missingToken(.contextualKeyword, text: "async") } } if let throwsAfterArrow = self.consume(if: .throwsKeyword) { effectModifiersAfterArrow.append(throwsAfterArrow) if throwsKeyword == nil { throwsKeyword = missingToken(.throwsKeyword, text: nil) } } let unexpectedAfterArrow = effectModifiersAfterArrow.isEmpty ? nil : RawUnexpectedNodesSyntax( elements: effectModifiersAfterArrow.map { RawSyntax($0) }, arena: self.arena ) let op = RawArrowExprSyntax( asyncKeyword: asyncKeyword, throwsToken: throwsKeyword, unexpectedBeforeArrow, arrowToken: arrow, unexpectedAfterArrow, arena: self.arena ) return (RawExprSyntax(op), nil) case nil: // Not an operator. return nil } } /// Parse an expression sequence element. /// /// Grammar /// ======= /// /// expression → try-operator? await-operator? prefix-expression infix-expressions? /// expression-list → expression | expression ',' expression-list @_spi(RawSyntax) public mutating func parseSequenceExpressionElement( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { // Try to parse '@' sign or 'inout' as a attributed typerepr. if self.at(any: [.atSign, .inoutKeyword]) { var backtrack = self.lookahead() if backtrack.canParseType() { let type = self.parseType() return RawExprSyntax(RawTypeExprSyntax(type: type, arena: self.arena)) } } switch self.at(anyIn: AwaitTryMove.self) { case (.awaitContextualKeyword, let handle)?: let awaitTok = self.eat(handle) let sub = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawAwaitExprSyntax( awaitKeyword: awaitTok, expression: sub, arena: self.arena )) case (.tryKeyword, let handle)?: let tryKeyword = self.eat(handle) let mark = self.consume(ifAny: [.exclamationMark, .postfixQuestionMark]) let expression = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawTryExprSyntax( tryKeyword: tryKeyword, questionOrExclamationMark: mark, expression: expression, arena: self.arena )) case (._moveContextualKeyword, let handle)?: let moveTok = self.eat(handle) let sub = self.parseSequenceExpressionElement( flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawMoveExprSyntax( moveKeyword: moveTok, expression: sub, arena: self.arena)) case nil: return self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) } } /// Parse an optional prefix operator followed by an expression. /// /// Grammar /// ======= /// /// prefix-expression → prefix-operator? postfix-expression /// prefix-expression → in-out-expression /// /// in-out-expression → '&' identifier @_spi(RawSyntax) public mutating func parseUnaryExpression( _ flavor: ExprFlavor, forDirective: Bool = false, pattern: PatternContext = .none ) -> RawExprSyntax { // First check to see if we have the start of a regex literal `/.../`. // tryLexRegexLiteral(/*forUnappliedOperator*/ false) switch self.at(anyIn: ExpressionPrefixOperator.self) { case (.prefixAmpersand, let handle)?: let amp = self.eat(handle) let expr = self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawInOutExprSyntax( ampersand: amp, expression: RawExprSyntax(expr), arena: self.arena )) case (.backslash, _)?: return RawExprSyntax(self.parseKeyPathExpression(forDirective: forDirective, pattern: pattern)) case (.prefixOperator, let handle)?: let op = self.eat(handle) let postfix = self.parseUnaryExpression(flavor, forDirective: forDirective, pattern: pattern) return RawExprSyntax(RawPrefixOperatorExprSyntax( operatorToken: op, postfixExpression: postfix, arena: self.arena )) default: // If the next token is not an operator, just parse this as expr-postfix. return self.parsePostfixExpression( flavor, forDirective: forDirective, pattern: pattern) } } /// Parse a postfix expression applied to another expression. /// /// Grammar /// ======= /// /// postfix-expression → primary-expression /// postfix-expression → postfix-expression postfix-operator /// postfix-expression → function-call-expression /// postfix-expression → initializer-expression /// postfix-expression → explicit-member-expression /// postfix-expression → postfix-self-expression /// postfix-expression → subscript-expression /// postfix-expression → forced-value-expression /// postfix-expression → optional-chaining-expression @_spi(RawSyntax) public mutating func parsePostfixExpression( _ flavor: ExprFlavor, forDirective: Bool, pattern: PatternContext ) -> RawExprSyntax { let head = self.parsePrimaryExpression(pattern: pattern, flavor: flavor) guard !head.is(RawMissingExprSyntax.self) else { return head } return self.parsePostfixExpressionSuffix( head, flavor, forDirective: forDirective, pattern: pattern) } @_spi(RawSyntax) public mutating func parseDottedExpressionSuffix() -> ( period: RawTokenSyntax, name: RawTokenSyntax, declNameArgs: RawDeclNameArgumentsSyntax?, generics: RawGenericArgumentClauseSyntax? ) { assert(self.at(any: [.period, .prefixPeriod])) let period = self.consumeAnyToken(remapping: .period) // Parse the name portion. let name: RawTokenSyntax let declNameArgs: RawDeclNameArgumentsSyntax? if let index = self.consume(if: .integerLiteral) { // Handle "x.42" - a tuple index. name = index declNameArgs = nil } else if let selfKeyword = self.consume(if: .selfKeyword) { // Handle "x.self" expr. name = selfKeyword declNameArgs = nil } else { // Handle an arbitrary declararion name. (name, declNameArgs) = self.parseDeclNameRef([.keywords, .compoundNames]) } // Parse the generic arguments, if any. let generics: RawGenericArgumentClauseSyntax? if self.lookahead().canParseAsGenericArgumentList() { generics = self.parseGenericArguments() } else { generics = nil } return (period, name, declNameArgs, generics) } @_spi(RawSyntax) public mutating func parseDottedExpressionSuffix(_ start: RawExprSyntax?) -> RawExprSyntax { let (period, name, declNameArgs, generics) = parseDottedExpressionSuffix() let memberAccess = RawMemberAccessExprSyntax( base: start, dot: period, name: name, declNameArguments: declNameArgs, arena: self.arena) guard let generics = generics else { return RawExprSyntax(memberAccess) } return RawExprSyntax(RawSpecializeExprSyntax( expression: RawExprSyntax(memberAccess), genericArgumentClause: generics, arena: self.arena)) } @_spi(RawSyntax) public mutating func parseIfConfigExpressionSuffix( _ start: RawExprSyntax?, _ flavor: ExprFlavor, forDirective: Bool ) -> RawExprSyntax { assert(self.at(.poundIfKeyword)) let config = self.parsePoundIfDirective { parser -> RawExprSyntax? in let head: RawExprSyntax if parser.at(any: [.period, .prefixPeriod]) { head = parser.parseDottedExpressionSuffix(nil) } else if parser.at(.poundIfKeyword) { head = parser.parseIfConfigExpressionSuffix(nil, flavor, forDirective: forDirective) } else { // TODO: diagnose and skip. return nil } let result = parser.parsePostfixExpressionSuffix( head, flavor, forDirective: forDirective, pattern: .none ) // TODO: diagnose and skip the remaining token in the current clause. return result } syntax: { (parser, elements) -> RawIfConfigClauseSyntax.Elements? in switch elements.count { case 0: return nil case 1: return .postfixExpression(elements.first!) default: fatalError("Postfix #if should only have one element") } } return RawExprSyntax(RawPostfixIfConfigExprSyntax( base: start, config: config, arena: self.arena)) } /// Parse the suffix of a postfix expression. /// /// Grammar /// ======= /// /// postfix-expression → postfix-expression postfix-operator /// postfix-expression → function-call-expression /// postfix-expression → initializer-expression /// postfix-expression → explicit-member-expression /// postfix-expression → postfix-self-expression /// postfix-expression → subscript-expression /// postfix-expression → forced-value-expression /// postfix-expression → optional-chaining-expression @_spi(RawSyntax) public mutating func parsePostfixExpressionSuffix( _ start: RawExprSyntax, _ flavor: ExprFlavor, forDirective: Bool, pattern: PatternContext ) -> RawExprSyntax { // Handle suffix expressions. var leadingExpr = start var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { if forDirective && self.currentToken.isAtStartOfLine { return leadingExpr } // Check for a .foo suffix. if self.at(any: [.period, .prefixPeriod]) { leadingExpr = self.parseDottedExpressionSuffix(leadingExpr) continue } // If there is an expr-call-suffix, parse it and form a call. if let lparen = self.consume(if: .leftParen, where: { !$0.isAtStartOfLine }) { let args = self.parseArgumentListElements(pattern: pattern) let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } leadingExpr = RawExprSyntax(RawFunctionCallExprSyntax( calledExpression: leadingExpr, leftParen: lparen, argumentList: RawTupleExprElementListSyntax(elements: args, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena)) continue } // Check for a [expr] suffix. // Note that this cannot be the start of a new line. if let lsquare = self.consume(if: .leftSquareBracket, where: { !$0.isAtStartOfLine }) { let args: [RawTupleExprElementSyntax] if self.at(.rightSquareBracket) { args = [] } else { args = self.parseArgumentListElements(pattern: pattern) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) // If we can parse trailing closures, do so. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } leadingExpr = RawExprSyntax(RawSubscriptExprSyntax( calledExpression: leadingExpr, leftBracket: lsquare, argumentList: RawTupleExprElementListSyntax(elements: args, arena: self.arena), unexpectedBeforeRSquare, rightBracket: rsquare, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena)) continue } // Check for a trailing closure, if allowed. if self.at(.leftBrace) && self.lookahead().isValidTrailingClosure(flavor) { // FIXME: if Result has a trailing closure, break out. // Add dummy blank argument list to the call expression syntax. let list = RawTupleExprElementListSyntax(elements: [], arena: self.arena) let (first, rest) = self.parseTrailingClosures(flavor) leadingExpr = RawExprSyntax(RawFunctionCallExprSyntax( calledExpression: leadingExpr, leftParen: nil, argumentList: list, rightParen: nil, trailingClosure: first, additionalTrailingClosures: rest, arena: self.arena)) // We only allow a single trailing closure on a call. This could be // generalized in the future, but needs further design. if self.at(.leftBrace) { break } continue } // Check for a ? suffix. if let question = self.consume(if: .postfixQuestionMark) { leadingExpr = RawExprSyntax(RawOptionalChainingExprSyntax( expression: leadingExpr, questionMark: question, arena: self.arena)) continue } // Check for a ! suffix. if let exlaim = self.consume(if: .exclamationMark) { leadingExpr = RawExprSyntax(RawForcedValueExprSyntax( expression: leadingExpr, exclamationMark: exlaim, arena: self.arena)) continue } // Check for a postfix-operator suffix. if let op = self.consume(if: .postfixOperator) { leadingExpr = RawExprSyntax(RawPostfixUnaryExprSyntax( expression: leadingExpr, operatorToken: op, arena: self.arena )) continue } if self.at(.poundIfKeyword) { // Check if the first '#if' body starts with '.' <identifier>, and parse // it as a "postfix ifconfig expression". do { var backtrack = self.lookahead() // Skip to the first body. We may need to skip multiple '#if' directives // since we support nested '#if's. e.g. // baseExpr // #if CONDITION_1 // #if CONDITION_2 // .someMember var loopProgress = LoopProgressCondition() repeat { backtrack.eat(.poundIfKeyword) while !backtrack.at(.eof) && !backtrack.currentToken.isAtStartOfLine { backtrack.skipSingle() } } while backtrack.at(.poundIfKeyword) && loopProgress.evaluate(backtrack.currentToken) guard backtrack.isAtStartOfPostfixExprSuffix() else { break } } leadingExpr = self.parseIfConfigExpressionSuffix( leadingExpr, flavor, forDirective: forDirective) continue } // Otherwise, we don't know what this token is, it must end the expression. break } return leadingExpr } } extension Parser { /// Determine if this is a key path postfix operator like ".?!?". private func getNumOptionalKeyPathPostfixComponents( _ tokenText: SyntaxText ) -> Int? { // Make sure every character is ".", "!", or "?", without two "."s in a row. var numComponents = 0 var lastWasDot = false for byte in tokenText { if byte == UInt8(ascii: ".") { if lastWasDot { return nil } lastWasDot = true continue } if byte == UInt8(ascii: "!") || byte == UInt8(ascii: "?") { lastWasDot = false numComponents += 1 continue } return nil } return numComponents } /// Consume the optional key path postfix ino a set of key path components. private mutating func consumeOptionalKeyPathPostfix( numComponents: Int ) -> [RawKeyPathComponentSyntax] { var components: [RawKeyPathComponentSyntax] = [] for _ in 0..<numComponents { // Consume a period, if there is one. let period: RawTokenSyntax? if self.currentToken.starts(with: ".") { period = self.consumePrefix(".", as: .period) } else { period = nil } // Consume the '!' or '?'. let questionOrExclaim: RawTokenSyntax if self.currentToken.starts(with: "!") { questionOrExclaim = self.consumePrefix("!", as: .exclamationMark) } else { assert(self.currentToken.starts(with: "?")) questionOrExclaim = self.consumePrefix("?", as: .postfixQuestionMark) } components.append(RawKeyPathComponentSyntax( period: period, component: .optional(RawKeyPathOptionalComponentSyntax( questionOrExclamationMark: questionOrExclaim, arena: self.arena)), arena: self.arena)) } return components } /// Parse a keypath expression. /// /// Grammar /// ======= /// /// key-path-expression → '\' type? '.' key-path-components /// /// key-path-components → key-path-component | key-path-component '.' key-path-components /// key-path-component → identifier key-path-postfixes? | key-path-postfixes /// /// key-path-postfixes → key-path-postfix key-path-postfixes? /// key-path-postfix → '?' | '!' | 'self' | '[' function-call-argument-list ']' @_spi(RawSyntax) public mutating func parseKeyPathExpression(forDirective: Bool, pattern: PatternContext) -> RawKeyPathExprSyntax { // Consume '\'. let (unexpectedBeforeBackslash, backslash) = self.expect(.backslash) // For uniformity, \.foo is parsed as if it were MAGIC.foo, so we need to // make sure the . is there, but parsing the ? in \.? as .? doesn't make // sense. This is all made more complicated by .?. being considered an // operator token. Since keypath allows '.!' '.?' and '.[', consume '.' // the token is a operator starts with '.', or the following token is '['. let rootType: RawTypeSyntax? if !self.currentToken.starts(with: ".") { rootType = self.parseSimpleType(stopAtFirstPeriod: true) } else { rootType = nil } var components: [RawKeyPathComponentSyntax] = [] var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { // Check for a [] or .[] suffix. The latter is only permitted when there // are no components. if self.at(.leftSquareBracket, where: { !$0.isAtStartOfLine }) || (components.isEmpty && self.at(any: [.period, .prefixPeriod]) && self.peek().tokenKind == .leftSquareBracket) { // Consume the '.', if it's allowed here. let period: RawTokenSyntax? if !self.at(.leftSquareBracket) { period = self.consumeAnyToken(remapping: .period) } else { period = nil } assert(self.at(.leftSquareBracket)) let lsquare = self.consumeAnyToken() let args: [RawTupleExprElementSyntax] if self.at(.rightSquareBracket) { args = [] } else { args = self.parseArgumentListElements(pattern: pattern) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) components.append(RawKeyPathComponentSyntax( period: period, component: .subscript(RawKeyPathSubscriptComponentSyntax( leftBracket: lsquare, argumentList: RawTupleExprElementListSyntax( elements: args, arena: self.arena), unexpectedBeforeRSquare, rightBracket: rsquare, arena: self.arena)), arena: self.arena)) continue } // Check for an operator starting with '.' that contains only // periods, '?'s, and '!'s. Expand that into key path components. if self.at(any: [ .postfixOperator, .postfixQuestionMark, .exclamationMark, .prefixOperator, .unspacedBinaryOperator ]), let numComponents = getNumOptionalKeyPathPostfixComponents( self.currentToken.tokenText) { components.append( contentsOf: self.consumeOptionalKeyPathPostfix( numComponents: numComponents)) continue } // Check for a .name or .1 suffix. if self.at(any: [.period, .prefixPeriod]) { let (period, name, declNameArgs, generics) = parseDottedExpressionSuffix() components.append(RawKeyPathComponentSyntax( period: period, component: .property(RawKeyPathPropertyComponentSyntax( identifier: name, declNameArguments: declNameArgs, genericArgumentClause: generics, arena: self.arena)), arena: self.arena)) continue } // No more postfix expressions. break } return RawKeyPathExprSyntax( unexpectedBeforeBackslash, backslash: backslash, root: rootType, components: RawKeyPathComponentListSyntax( elements: components, arena: self.arena), arena: self.arena) } } extension Parser { /// Parse a "primary expression" - these are the most basic leaves of the /// Swift expression grammar. /// /// Grammar /// ======= /// /// primary-expression → identifier generic-argument-clause? /// primary-expression → literal-expression /// primary-expression → self-expression /// primary-expression → superclass-expression /// primary-expression → closure-expression /// primary-expression → parenthesized-expression /// primary-expression → tuple-expression /// primary-expression → implicit-member-expression /// primary-expression → wildcard-expression /// primary-expression → key-path-expression /// primary-expression → selector-expression /// primary-expression → key-path-string-expression /// primary-expression → macro-expansion-expression @_spi(RawSyntax) public mutating func parsePrimaryExpression( pattern: PatternContext, flavor: ExprFlavor ) -> RawExprSyntax { switch self.at(anyIn: PrimaryExpressionStart.self) { case (.integerLiteral, let handle)?: let digits = self.eat(handle) return RawExprSyntax(RawIntegerLiteralExprSyntax( digits: digits, arena: self.arena )) case (.floatingLiteral, let handle)?: let digits = self.eat(handle) return RawExprSyntax(RawFloatLiteralExprSyntax( floatingDigits: digits, arena: self.arena )) case (.stringLiteral, _)?: return RawExprSyntax(self.parseStringLiteral()) case (.regexLiteral, _)?: return RawExprSyntax(self.parseRegexLiteral()) case (.nilKeyword, let handle)?: let nilKeyword = self.eat(handle) return RawExprSyntax(RawNilLiteralExprSyntax( nilKeyword: nilKeyword, arena: self.arena )) case (.trueKeyword, let handle)?, (.falseKeyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawBooleanLiteralExprSyntax( booleanLiteral: tok, arena: self.arena )) case (.__file__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundFileExprSyntax( poundFile: tok, arena: self.arena )) case (.__function__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundFunctionExprSyntax( poundFunction: tok, arena: self.arena )) case (.__line__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundLineExprSyntax( poundLine: tok, arena: self.arena )) case (.__column__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundColumnExprSyntax( poundColumn: tok, arena: self.arena )) case (.__dso_handle__Keyword, let handle)?: let tok = self.eat(handle) return RawExprSyntax(RawPoundDsohandleExprSyntax( poundDsohandle: tok, arena: self.arena )) case (.identifier, let handle)?, (.selfKeyword, let handle)?, (.initKeyword, let handle)?: // If we have "case let x." or "case let x(", we parse x as a normal // name, not a binding, because it is the start of an enum pattern or // call pattern. if pattern.admitsBinding && !self.lookahead().isNextTokenCallPattern() { let identifier = self.eat(handle) let pattern = RawPatternSyntax(RawIdentifierPatternSyntax( identifier: identifier, arena: self.arena)) return RawExprSyntax(RawUnresolvedPatternExprSyntax(pattern: pattern, arena: self.arena)) } // 'any' followed by another identifier is an existential type. if self.atContextualKeyword("any"), self.peek().tokenKind == .identifier, !self.peek().isAtStartOfLine { let ty = self.parseType() return RawExprSyntax(RawTypeExprSyntax(type: ty, arena: self.arena)) } return RawExprSyntax(self.parseIdentifierExpression()) case (.capitalSelfKeyword, _)?: // Self return RawExprSyntax(self.parseIdentifierExpression()) case (.anyKeyword, _)?: // Any let anyType = RawTypeSyntax(self.parseAnyType()) return RawExprSyntax(RawTypeExprSyntax(type: anyType, arena: self.arena)) case (.dollarIdentifier, _)?: return RawExprSyntax(self.parseAnonymousClosureArgument()) case (.wildcardKeyword, let handle)?: // _ let wild = self.eat(handle) return RawExprSyntax(RawDiscardAssignmentExprSyntax( wildcard: wild, arena: self.arena )) case (.pound, _)?: return RawExprSyntax( self.parseMacroExpansionExpr(pattern: pattern, flavor: flavor) ) case (.poundSelectorKeyword, _)?: return RawExprSyntax(self.parseObjectiveCSelectorLiteral()) case (.poundKeyPathKeyword, _)?: return RawExprSyntax(self.parseObjectiveCKeyPathExpression()) case (.leftBrace, _)?: // expr-closure return RawExprSyntax(self.parseClosureExpression()) case (.period, let handle)?, //=.foo (.prefixPeriod, let handle)?: // .foo let dot = self.eat(handle) let (name, args) = self.parseDeclNameRef([ .keywords, .compoundNames ]) return RawExprSyntax(RawMemberAccessExprSyntax( base: nil, dot: dot, name: name, declNameArguments: args, arena: self.arena)) case (.superKeyword, _)?: // 'super' return RawExprSyntax(self.parseSuperExpression()) case (.leftParen, _)?: // Build a tuple expression syntax node. // AST differentiates paren and tuple expression where the former allows // only one element without label. However, libSyntax tree doesn't have this // differentiation. A tuple expression node in libSyntax can have a single // element without label. return RawExprSyntax(self.parseTupleExpression(pattern: pattern)) case (.leftSquareBracket, _)?: return self.parseCollectionLiteral() case nil: return RawExprSyntax(RawMissingExprSyntax(arena: self.arena)) } } } extension Parser { /// Parse an identifier as an expression. /// /// Grammar /// ======= /// /// primary-expression → identifier @_spi(RawSyntax) public mutating func parseIdentifierExpression() -> RawExprSyntax { let (name, args) = self.parseDeclNameRef(.compoundNames) guard self.lookahead().canParseAsGenericArgumentList() else { if name.tokenText.isEditorPlaceholder && args == nil { return RawExprSyntax( RawEditorPlaceholderExprSyntax( identifier: name, arena: self.arena)) } return RawExprSyntax(RawIdentifierExprSyntax( identifier: name, declNameArguments: args, arena: self.arena)) } let identifier = RawIdentifierExprSyntax( identifier: name, declNameArguments: args, arena: self.arena) let generics = self.parseGenericArguments() return RawExprSyntax(RawSpecializeExprSyntax( expression: RawExprSyntax(identifier), genericArgumentClause: generics, arena: self.arena)) } } extension Parser { /// Parse a macro expansion as an expression. /// /// /// Grammar /// ======= /// /// macro-expansion-expression → '#' identifier expr-call-suffix? @_spi(RawSyntax) public mutating func parseMacroExpansionExpr( pattern: PatternContext, flavor: ExprFlavor ) -> RawMacroExpansionExprSyntax { let poundKeyword = self.consumeAnyToken() let (unexpectedBeforeMacro, macro) = self.expectIdentifier() // Parse the optional generic argument list. let generics: RawGenericArgumentClauseSyntax? if self.lookahead().canParseAsGenericArgumentList() { generics = self.parseGenericArguments() } else { generics = nil } // Parse the optional parenthesized argument list. let leftParen = self.consume(if: .leftParen, where: { !$0.isAtStartOfLine }) let args: [RawTupleExprElementSyntax] let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax? let rightParen: RawTokenSyntax? if leftParen != nil { args = parseArgumentListElements(pattern: pattern) (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) } else { args = [] unexpectedBeforeRightParen = nil rightParen = nil } // Parse the optional trailing closures. let trailingClosure: RawClosureExprSyntax? let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax? if case .trailingClosure = flavor, self.at(.leftBrace), self.lookahead().isValidTrailingClosure(flavor) { (trailingClosure, additionalTrailingClosures) = self.parseTrailingClosures(flavor) } else { trailingClosure = nil additionalTrailingClosures = nil } return RawMacroExpansionExprSyntax( poundToken: poundKeyword, unexpectedBeforeMacro, macro: macro, genericArguments: generics, leftParen: leftParen, argumentList: RawTupleExprElementListSyntax( elements: args, arena: self.arena ), unexpectedBeforeRightParen, rightParen: rightParen, trailingClosure: trailingClosure, additionalTrailingClosures: additionalTrailingClosures, arena: self.arena) } } extension Parser { /// Parse a string literal expression. /// /// Grammar /// ======= /// /// string-literal → static-string-literal | interpolated-string-literal /// /// string-literal-opening-delimiter → extended-string-literal-delimiter? '"' /// string-literal-closing-delimiter → '"' extended-string-literal-delimiter? /// /// static-string-literal → string-literal-opening-delimiter quoted-text? string-literal-closing-delimiter /// static-string-literal → multiline-string-literal-opening-delimiter multiline-quoted-text? multiline-string-literal-closing-delimiter /// /// multiline-string-literal-opening-delimiter → extended-string-literal-delimiter? '"""' /// multiline-string-literal-closing-delimiter → '"""' extended-string-literal-delimiter? /// extended-string-literal-delimiter → '#' extended-string-literal-delimiter? /// /// quoted-text → quoted-text-item quoted-text? /// quoted-text-item → escaped-character /// quoted-text-item → `Any Unicode scalar value except ", \, U+000A, or U+000D` /// /// multiline-quoted-text → multiline-quoted-text-item multiline-quoted-text? /// multiline-quoted-text-item → escaped-character /// multiline-quoted-text-item → `Any Unicode scalar value except \` /// multiline-quoted-text-item → escaped-newline /// /// interpolated-string-literal → string-literal-opening-delimiter interpolated-text? string-literal-closing-delimiter /// interpolated-string-literal → multiline-string-literal-opening-delimiter multiline-interpolated-text? multiline-string-literal-closing-delimiter /// interpolated-text → interpolated-text-item interpolated-text? /// interpolated-text-item → '\(' expression ')' | quoted-text-item /// /// multiline-interpolated-text → multiline-interpolated-text-item multiline-interpolated-text? /// multiline-interpolated-text-item → '\(' expression ')' | multiline-quoted-text-item /// escape-sequence → \ extended-string-literal-delimiter /// escaped-character → escape-sequence '0' | escape-sequence '\' | escape-sequence 't' | escape-sequence 'n' | escape-sequence 'r' | escape-sequence '"' | escape-sequence ''' /// /// escaped-character → escape-sequence 'u' '{' unicode-scalar-digits '}' /// unicode-scalar-digits → Between one and eight hexadecimal digits /// /// escaped-newline → escape-sequence inline-spaces? line-break @_spi(RawSyntax) public mutating func parseStringLiteral() -> RawStringLiteralExprSyntax { var text = self.currentToken.wholeText[self.currentToken.textRange] /// Parse opening raw string delimiter if exist. let openDelimiter = self.parseStringLiteralDelimiter(at: .leading, text: text) if let openDelimiter = openDelimiter { text = text.dropFirst(openDelimiter.tokenText.count) } /// Parse open quote. let openQuote = self.parseStringLiteralQuote( at: openDelimiter != nil ? .leadingRaw : .leading, text: text, wantsMultiline: self.currentToken.isMultilineStringLiteral ) ?? RawTokenSyntax(missing: .stringQuote, arena: arena) if !openQuote.isMissing { text = text.dropFirst(openQuote.tokenText.count) } /// Parse segments. let (segments, closeStart) = self.parseStringLiteralSegments( text, openQuote, openDelimiter?.tokenText ?? "") text = text[closeStart...] /// Parse close quote. let closeQuote = self.parseStringLiteralQuote( at: openDelimiter != nil ? .trailingRaw : .trailing, text: text, wantsMultiline: self.currentToken.isMultilineStringLiteral ) ?? RawTokenSyntax(missing: openQuote.tokenKind, arena: arena) if !closeQuote.isMissing { text = text.dropFirst(closeQuote.tokenText.count) } /// Parse closing raw string delimiter if exist. let closeDelimiter: RawTokenSyntax? if let delimiter = self.parseStringLiteralDelimiter( at: .trailing, text: text ) { closeDelimiter = delimiter } else if let openDelimiter = openDelimiter { closeDelimiter = RawTokenSyntax( missing: .rawStringDelimiter, text: openDelimiter.tokenText, arena: arena ) } else { closeDelimiter = nil } assert((openDelimiter == nil) == (closeDelimiter == nil), "existence of open/close delimiter should match") if let closeDelimiter = closeDelimiter, !closeDelimiter.isMissing { text = text.dropFirst(closeDelimiter.byteLength) } assert(text.isEmpty, "string literal parsing should consume all the literal text") /// Discard the raw string literal token and create the structed string /// literal expression. /// FIXME: We should not instantiate `RawTokenSyntax` and discard it here. _ = self.consumeAnyToken() /// Construct the literal expression. return RawStringLiteralExprSyntax( openDelimiter: openDelimiter, openQuote: openQuote, segments: segments, closeQuote: closeQuote, closeDelimiter: closeDelimiter, arena: self.arena) } // Enumerates the positions that a quote can appear in a string literal. enum QuotePosition { /// The quote appears in leading position. /// /// ```swift /// "Hello World" /// ^ /// ##"Hello World"## /// ^ /// ``` case leading /// The quote appears in trailing position. /// /// ```swift /// "Hello World" /// ^ /// ##"Hello World"## /// ^ /// ``` case trailing /// The quote appears in at the start of a raw string literal. /// /// ```swift /// ##"Hello World"## /// ^ /// ``` case leadingRaw /// The quote appears in at the end of a raw string literal. /// /// ```swift /// ##"Hello World"## /// ^ /// ``` case trailingRaw } /// Create string literal delimiter/quote token syntax for `position`. /// /// `text` will the token text of the token. The `text.base` must be the whole /// text of the original `.stringLiteral` token including trivia. private func makeStringLiteralQuoteToken( _ kind: RawTokenKind, text: Slice<SyntaxText>, at position: QuotePosition ) -> RawTokenSyntax { let wholeText: SyntaxText let textRange: Range<SyntaxText.Index> switch position { case .leadingRaw, .trailingRaw: wholeText = SyntaxText(rebasing: text) textRange = wholeText.startIndex ..< wholeText.endIndex case .leading: wholeText = SyntaxText(rebasing: text.base[..<text.endIndex]) textRange = text.startIndex ..< text.endIndex case .trailing: wholeText = SyntaxText(rebasing: text.base[text.startIndex...]) textRange = wholeText.startIndex ..< wholeText.startIndex + text.count } return RawTokenSyntax( kind: kind, wholeText: wholeText, textRange: textRange, presence: .present, hasLexerError: false, arena: self.arena ) } mutating func parseStringLiteralDelimiter( at position: QuotePosition, text: Slice<SyntaxText> ) -> RawTokenSyntax? { assert(position != .leadingRaw && position != .trailingRaw) var index = text.startIndex while index < text.endIndex && text[index] == UInt8(ascii: "#") { index = text.index(after: index) } guard index > text.startIndex else { return nil } return makeStringLiteralQuoteToken( .rawStringDelimiter, text: text[..<index], at: position) } mutating func parseStringLiteralQuote( at position: QuotePosition, text: Slice<SyntaxText>, wantsMultiline: Bool ) -> RawTokenSyntax? { // Single quote. We only support single line literal. if let first = text.first, first == UInt8(ascii: "'") { let index = text.index(after: text.startIndex) return makeStringLiteralQuoteToken( .singleQuote, text: text[..<index], at: position) } var index = text.startIndex var quoteCount = 0 while index < text.endIndex && text[index] == UInt8(ascii: "\"") { quoteCount += 1 index = text.index(after: index) guard wantsMultiline else { break } } // Empty single line string. Return only the first quote. switch quoteCount { case 0, 1: break case 2: quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) case 3: // position == .leadingRaw implies that we saw a `#` before the quote. // A multiline string literal must always start its contents on a new line. // Thus we are parsing something like #"""#, which is not a multiline string literal but a raw literal containing a single quote. if position == .leadingRaw, index < text.endIndex, text[index] == UInt8(ascii: "#") { quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) } default: // Similar two the above, we are parsing something like #"""""#, which is not a multiline string literal but a raw literal containing three quote. if position == .leadingRaw { quoteCount = 1 index = text.index(text.startIndex, offsetBy: quoteCount) } else if position == .leading { quoteCount = 3 index = text.index(text.startIndex, offsetBy: quoteCount) } } // Single line string literal. if quoteCount == 1 { return makeStringLiteralQuoteToken( .stringQuote, text: text[..<index], at: position) } // Multi line string literal. if quoteCount == 3 { return makeStringLiteralQuoteToken( .multilineStringQuote, text: text[..<index], at: position) } // Otherwise, this is not a literal quote. return nil } /// Foo. /// /// Parameters: /// - text: slice from after the quote to the end of the literal. /// - closer: opening quote token. /// - delimiter: opening custom string delimiter or empty string. mutating func parseStringLiteralSegments( _ text: Slice<SyntaxText>, _ closer: RawTokenSyntax, _ delimiter: SyntaxText ) -> (RawStringLiteralSegmentsSyntax, SyntaxText.Index) { let allowsMultiline = closer.tokenKind == .multilineStringQuote var segments = [RawStringLiteralSegmentsSyntax.Element]() var segment = text var stringLiteralSegmentStart = segment.startIndex while let slashIndex = segment.firstIndex(of: UInt8(ascii: "\\")), stringLiteralSegmentStart < segment.endIndex { let delimiterStart = text.index(after: slashIndex) guard delimiterStart < segment.endIndex && SyntaxText(rebasing: text[delimiterStart...]).hasPrefix(delimiter) else { // If `\` is not followed by the custom delimiter, it's not a segment delimiter. // Restart after the `\`. if delimiterStart == segment.endIndex { segment = text[segment.endIndex...] break } else { segment = text[text.index(after: delimiterStart)...] continue } } let contentStart = text.index(delimiterStart, offsetBy: delimiter.count) guard contentStart < segment.endIndex && text[contentStart] == UInt8(ascii: "(") else { if contentStart == segment.endIndex { segment = text[segment.endIndex...] break } else { // If `\` (or `\#`) is not followed by `(`, it's not a segment delimiter. // Restart after the `(`. segment = text[text.index(after: contentStart)...] continue } } // Collect ".stringSegment" before `\`. let segmentToken = RawTokenSyntax( kind: .stringSegment, text: SyntaxText(rebasing: text[stringLiteralSegmentStart..<slashIndex]), presence: .present, arena: self.arena) segments.append(.stringSegment(RawStringSegmentSyntax(content: segmentToken, arena: self.arena))) let content = SyntaxText(rebasing: text[contentStart...]) let contentSize = content.withBuffer { buf in Lexer.lexToEndOfInterpolatedExpression(buf, allowsMultiline) } let contentEnd = text.index(contentStart, offsetBy: contentSize) do { // `\` let slashToken = RawTokenSyntax( kind: .backslash, text: SyntaxText(rebasing: text[slashIndex..<text.index(after: slashIndex)]), presence: .present, arena: self.arena) // `###` let delim: RawTokenSyntax? if !delimiter.isEmpty { delim = RawTokenSyntax( kind: .rawStringDelimiter, text: SyntaxText(rebasing: text[delimiterStart..<contentStart]), presence: .present, arena: self.arena) } else { delim = nil } // `(...)`. let expressionContent = SyntaxText(rebasing: text[contentStart...contentEnd]) expressionContent.withBuffer { buf in var subparser = Parser(buf, arena: self.arena) let (lunexpected, lparen) = subparser.expect(.leftParen) let args = subparser.parseArgumentListElements(pattern: .none) // If we stopped parsing the expression before the expression segment is // over, eat the remaining tokens into a token list. var runexpectedTokens = [RawSyntax]() let runexpected: RawUnexpectedNodesSyntax? var loopProgress = LoopProgressCondition() while !subparser.at(any: [.eof, .rightParen]) && loopProgress.evaluate(subparser.currentToken) { runexpectedTokens.append(RawSyntax(subparser.consumeAnyToken())) } if !runexpectedTokens.isEmpty { runexpected = RawUnexpectedNodesSyntax(elements: runexpectedTokens, arena: self.arena) } else { runexpected = nil } let rparen = subparser.expectWithoutRecovery(.rightParen) assert(subparser.currentToken.tokenKind == .eof) let trailing: RawUnexpectedNodesSyntax? if subparser.currentToken.byteLength == 0 { trailing = nil } else { trailing = RawUnexpectedNodesSyntax([ subparser.consumeAnyToken() ], arena: self.arena) } segments.append(.expressionSegment(RawExpressionSegmentSyntax( backslash: slashToken, delimiter: delim, lunexpected, leftParen: lparen, expressions: RawTupleExprElementListSyntax(elements: args, arena: self.arena), runexpected, rightParen: rparen, trailing, arena: self.arena))) } } segment = text[text.index(after: contentEnd)...] stringLiteralSegmentStart = segment.startIndex } /// We still have the last "literal" segment. /// Trim the end delimiter. i.e. `"##`. segment = text[stringLiteralSegmentStart...] if (SyntaxText(rebasing: segment).hasSuffix(delimiter)) { // trim `##`. segment = text[stringLiteralSegmentStart..<text.index(segment.endIndex, offsetBy: -delimiter.count)] if (SyntaxText(rebasing: segment).hasSuffix(closer.tokenText)) { // trim `"`. segment = text[stringLiteralSegmentStart..<text.index(segment.endIndex, offsetBy: -closer.tokenText.count)] } else { // If `"` is not found, eat the rest. segment = text[stringLiteralSegmentStart...] } } assert(segments.count % 2 == 0) assert(segments.isEmpty || segments.last!.is(RawExpressionSegmentSyntax.self)) let segmentToken = RawTokenSyntax( kind: .stringSegment, text: SyntaxText(rebasing: segment), presence: .present, arena: self.arena) segments.append(.stringSegment(RawStringSegmentSyntax(content: segmentToken, arena: self.arena))) return (RawStringLiteralSegmentsSyntax(elements: segments, arena: arena), segment.endIndex) } } extension Parser { /// Parse a regular expression literal. /// /// The broad structure of the regular expression is validated by the lexer. /// /// Grammar /// ======= /// /// regular-expression-literal → '\' `Any valid regular expression characters` '\' @_spi(RawSyntax) public mutating func parseRegexLiteral() -> RawRegexLiteralExprSyntax { let (unexpectedBeforeLiteral, literal) = self.expect(.regexLiteral) return RawRegexLiteralExprSyntax( unexpectedBeforeLiteral, regex: literal, arena: self.arena ) } } extension Parser { /// Parse an Objective-C #keypath literal. /// /// Grammar /// ======= /// /// key-path-string-expression → '#keyPath' '(' expression ')' @_spi(RawSyntax) public mutating func parseObjectiveCKeyPathExpression() -> RawObjcKeyPathExprSyntax { let (unexpectedBeforeKeyword, keyword) = self.expect(.poundKeyPathKeyword) // Parse the leading '('. let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) // Parse the sequence of unqualified-names. var elements = [RawObjcNamePieceSyntax]() do { var flags: DeclNameOptions = [] var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { // Parse the next name. let (name, args) = self.parseDeclNameRef(flags) assert(args == nil, "Found arguments but did not pass argument flag?") // After the first component, we can start parsing keywords. flags.formUnion(.keywords) // Parse the next period to continue the path. keepGoing = self.consume(if: .period) elements.append(RawObjcNamePieceSyntax( name: name, dot: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } // Parse the closing ')'. let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawObjcKeyPathExprSyntax( unexpectedBeforeKeyword, keyPath: keyword, unexpectedBeforeLParen, leftParen: lparen, name: RawObjcNameSyntax(elements: elements, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { /// Parse a 'super' reference to the superclass instance of a class. /// /// Grammar /// ======= /// /// primary-expression → 'super' @_spi(RawSyntax) public mutating func parseSuperExpression() -> RawSuperRefExprSyntax { // Parse the 'super' reference. let (unexpectedBeforeSuperKeyword, superKeyword) = self.expect(.superKeyword) return RawSuperRefExprSyntax( unexpectedBeforeSuperKeyword, superKeyword: superKeyword, arena: self.arena ) } } extension Parser { /// Parse a tuple expression. /// /// Grammar /// ======= /// /// tuple-expression → '(' ')' | '(' tuple-element ',' tuple-element-list ')' /// tuple-element-list → tuple-element | tuple-element ',' tuple-element-list @_spi(RawSyntax) public mutating func parseTupleExpression(pattern: PatternContext) -> RawTupleExprSyntax { let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) let elements = self.parseArgumentListElements(pattern: pattern) let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawTupleExprSyntax( unexpectedBeforeLParen, leftParen: lparen, elementList: RawTupleExprElementListSyntax(elements: elements, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { enum CollectionKind { case dictionary(key: RawExprSyntax, unexpectedBeforeColon: RawUnexpectedNodesSyntax?, colon: RawTokenSyntax, value: RawExprSyntax) case array(RawExprSyntax) } /// Parse an element of an array or dictionary literal. /// /// Grammar /// ======= /// /// array-literal-item → expression /// /// dictionary-literal-item → expression ':' expression mutating func parseCollectionElement(_ existing: CollectionKind?) -> CollectionKind { let key = self.parseExpression() switch existing { case .array(_): return .array(key) case nil: guard self.at(.colon) else { return .array(key) } fallthrough case .dictionary: let (unexpectedBeforeColon, colon) = self.expect(.colon) let value = self.parseExpression() return .dictionary(key: key, unexpectedBeforeColon: unexpectedBeforeColon, colon: colon, value: value) } } /// Parse an array or dictionary literal. /// /// Grammar /// ======= /// /// array-literal → '[' array-literal-items? ']' /// array-literal-items → array-literal-item ','? | array-literal-item ',' array-literal-items /// /// dictionary-literal → '[' dictionary-literal-items ']' | '[' ':' ']' /// dictionary-literal-items → dictionary-literal-item ','? | dictionary-literal-item ',' dictionary-literal-items @_spi(RawSyntax) public mutating func parseCollectionLiteral() -> RawExprSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawExprSyntax(RawArrayExprSyntax( remainingTokens, leftSquare: missingToken(.leftSquareBracket), elements: RawArrayElementListSyntax(elements: [], arena: self.arena), rightSquare: missingToken(.rightSquareBracket), arena: self.arena )) } let (unexpectedBeforeLSquare, lsquare) = self.expect(.leftSquareBracket) if let rsquare = self.consume(if: .rightSquareBracket) { return RawExprSyntax(RawArrayExprSyntax( unexpectedBeforeLSquare, leftSquare: lsquare, elements: RawArrayElementListSyntax(elements: [], arena: self.arena), rightSquare: rsquare, arena: self.arena)) } if let (colon, rsquare) = self.consume(if: .colon, followedBy: .rightSquareBracket) { // FIXME: We probably want a separate node for the empty case. return RawExprSyntax(RawDictionaryExprSyntax( unexpectedBeforeLSquare, leftSquare: lsquare, content: .colon(colon), rightSquare: rsquare, arena: self.arena )) } var elementKind: CollectionKind? = nil var elements = [RawSyntax]() do { var collectionLoopCondition = LoopProgressCondition() COLLECTION_LOOP: while collectionLoopCondition.evaluate(currentToken) { elementKind = self.parseCollectionElement(elementKind) // Parse the ',' if exists. let comma = self.consume(if: .comma) switch elementKind! { case .array(let el): let element = RawArrayElementSyntax( expression: el, trailingComma: comma, arena: self.arena ) if element.isEmpty { break COLLECTION_LOOP } else { elements.append(RawSyntax(element)) } case .dictionary(let key, let unexpectedBeforeColon, let colon, let value): let element = RawDictionaryElementSyntax( keyExpression: key, unexpectedBeforeColon, colon: colon, valueExpression: value, trailingComma: comma, arena: self.arena ) if element.isEmpty { break COLLECTION_LOOP } else { elements.append(RawSyntax(element)) } } // If we saw a comma, that's a strong indicator we have more elements // to process. If that's not the case, we have to do some legwork to // determine if we should bail out. guard comma == nil || self.at(any: [.rightSquareBracket, .eof]) else { continue } // If we found EOF or the closing square bracket, bailout. if self.at(any: [.rightSquareBracket, .eof]) { break } // If The next token is at the beginning of a new line and can never start // an element, break. if self.currentToken.isAtStartOfLine && (self.at(any: [.rightBrace, .poundEndifKeyword]) || self.atStartOfDeclaration() || self.atStartOfStatement()) { break } } } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) switch elementKind! { case .dictionary: return RawExprSyntax(RawDictionaryExprSyntax( leftSquare: lsquare, content: .elements(RawDictionaryElementListSyntax(elements: elements.map { $0.as(RawDictionaryElementSyntax.self)! }, arena: self.arena)), unexpectedBeforeRSquare, rightSquare: rsquare, arena: self.arena)) case .array: return RawExprSyntax(RawArrayExprSyntax( leftSquare: lsquare, elements: RawArrayElementListSyntax(elements: elements.map { $0.as(RawArrayElementSyntax.self)! }, arena: self.arena), unexpectedBeforeRSquare, rightSquare: rsquare, arena: self.arena)) } } } extension Parser { @_spi(RawSyntax) public mutating func parseDefaultArgument() -> RawInitializerClauseSyntax { let (unexpectedBeforeEq, eq) = self.expect(.equal) let expr = self.parseExpression() return RawInitializerClauseSyntax( unexpectedBeforeEq, equal: eq, value: expr, arena: self.arena ) } } extension Parser { @_spi(RawSyntax) public mutating func parseAnonymousClosureArgument() -> RawIdentifierExprSyntax { let (unexpectedBeforeIdent, ident) = self.expect(.dollarIdentifier) return RawIdentifierExprSyntax( unexpectedBeforeIdent, identifier: ident, declNameArguments: nil, arena: self.arena ) } } extension Parser { /// Parse a #selector expression. /// /// Grammar /// ======= /// /// selector-expression → '#selector' '(' expression ) /// selector-expression → '#selector' '(' 'getter' ':' expression ')' /// selector-expression → '#selector' '(' 'setter' ':' expression ')' @_spi(RawSyntax) public mutating func parseObjectiveCSelectorLiteral() -> RawObjcSelectorExprSyntax { // Consume '#selector'. let (unexpectedBeforeSelector, selector) = self.expect(.poundSelectorKeyword) // Parse the leading '('. let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) // Parse possible 'getter:' or 'setter:' modifiers, and determine // the kind of selector we're working with. let kindAndColon = self.consume( if: { $0.isContextualKeyword(["getter", "setter"])}, followedBy: { $0.tokenKind == .colon } ) let (kind, colon) = (kindAndColon?.0, kindAndColon?.1) // Parse the subexpression. let subexpr = self.parseExpression() // Parse the closing ')'. let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawObjcSelectorExprSyntax( unexpectedBeforeSelector, poundSelector: selector, unexpectedBeforeLParen, leftParen: lparen, kind: kind, colon: colon, name: subexpr, unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { /// Parse a closure expression. /// /// Grammar /// ======= /// /// closure-expression → '{' attributes? closure-signature? statements? '}' @_spi(RawSyntax) public mutating func parseClosureExpression() -> RawClosureExprSyntax { // Parse the opening left brace. let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace) // Parse the closure-signature, if present. let signature = self.parseClosureSignatureIfPresent() // Parse the body. var elements = [RawCodeBlockItemSyntax]() do { var loopProgress = LoopProgressCondition() while !self.at(.rightBrace), let newItem = self.parseCodeBlockItem(), loopProgress.evaluate(currentToken) { elements.append(newItem) } } // Parse the closing '}'. let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace) return RawClosureExprSyntax( unexpectedBeforeLBrace, leftBrace: lbrace, signature: signature, statements: RawCodeBlockItemListSyntax(elements: elements, arena: arena), unexpectedBeforeRBrace, rightBrace: rbrace, arena: self.arena) } } extension Parser { /// Parse the signature of a closure, if one is present. /// /// Grammar /// ======= /// /// closure-signature → capture-list? closure-parameter-clause 'async'? 'throws'? function-result? 'in' /// closure-signature → capture-list 'in' /// /// closure-parameter-clause → '(' ')' | '(' closure-parameter-list ')' | identifier-list /// /// closure-parameter-list → closure-parameter | closure-parameter , closure-parameter-list /// closure-parameter → closure-parameter-name type-annotation? /// closure-parameter → closure-parameter-name type-annotation '...' /// closure-parameter-name → identifier /// /// capture-list → '[' capture-list-items ']' /// capture-list-items → capture-list-item | capture-list-item , capture-list-items /// capture-list-item → capture-specifier? identifier /// capture-list-item → capture-specifier? identifier '=' expression /// capture-list-item → capture-specifier? self-expression /// /// capture-specifier → 'weak' | 'unowned' | 'unowned(safe)' | 'unowned(unsafe)' @_spi(RawSyntax) public mutating func parseClosureSignatureIfPresent() -> RawClosureSignatureSyntax? { // If we have a leading token that may be part of the closure signature, do a // speculative parse to validate it and look for 'in'. guard self.at(any: [.atSign, .leftParen, .leftSquareBracket, .wildcardKeyword]) || self.at(.identifier) else { // No closure signature. return nil } guard self.lookahead().canParseClosureSignature() else { return nil } let attrs = self.parseAttributeList() let captures: RawClosureCaptureSignatureSyntax? if let lsquare = self.consume(if: .leftSquareBracket) { // At this point, we know we have a closure signature. Parse the capture list // and parameters. var elements = [RawClosureCaptureItemSyntax]() if !self.at(.rightSquareBracket) { var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { // Parse any specifiers on the capture like `weak` or `unowned` let specifier = self.parseClosureCaptureSpecifiers() // The thing being capture specified is an identifier, or as an identifier // followed by an expression. let unexpectedBeforeName: RawUnexpectedNodesSyntax? let name: RawTokenSyntax? let unexpectedBeforeAssignToken: RawUnexpectedNodesSyntax? let assignToken: RawTokenSyntax? let expression: RawExprSyntax if self.peek().tokenKind == .equal { // The name is a new declaration. (unexpectedBeforeName, name) = self.expectIdentifier() (unexpectedBeforeAssignToken, assignToken) = self.expect(.equal) expression = self.parseExpression() } else { // This is the simple case - the identifier is both the name and // the expression to capture. unexpectedBeforeName = nil name = nil unexpectedBeforeAssignToken = nil assignToken = nil expression = RawExprSyntax(self.parseIdentifierExpression()) } keepGoing = self.consume(if: .comma) elements.append(RawClosureCaptureItemSyntax( specifier: specifier, unexpectedBeforeName, name: name, unexpectedBeforeAssignToken, assignToken: assignToken, expression: expression, trailingComma: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } // We were promised a right square bracket, so we're going to get it. var unexpectedNodes = [RawSyntax]() while !self.at(.eof) && !self.at(.rightSquareBracket) && !self.at(.inKeyword) { unexpectedNodes.append(RawSyntax(self.consumeAnyToken())) } let (unexpectedBeforeRSquare, rsquare) = self.expect(.rightSquareBracket) unexpectedNodes.append(contentsOf: unexpectedBeforeRSquare?.elements ?? []) captures = RawClosureCaptureSignatureSyntax( leftSquare: lsquare, items: elements.isEmpty ? nil : RawClosureCaptureItemListSyntax(elements: elements, arena: self.arena), RawUnexpectedNodesSyntax(unexpectedNodes, arena: self.arena), rightSquare: rsquare, arena: self.arena) } else { captures = nil } var input: RawClosureSignatureSyntax.Input? var asyncKeyword: RawTokenSyntax? = nil var throwsTok: RawTokenSyntax? = nil var output: RawReturnClauseSyntax? = nil if !self.at(.inKeyword) { if self.at(.leftParen) { // Parse the closure arguments. input = .input(self.parseParameterClause(for: .closure)) } else { var params = [RawClosureParamSyntax]() var loopProgress = LoopProgressCondition() do { // Parse identifier (',' identifier)* var keepGoing: RawTokenSyntax? = nil repeat { let unexpected: RawUnexpectedNodesSyntax? let name: RawTokenSyntax if let identifier = self.consume(if: .identifier) { unexpected = nil name = identifier } else { (unexpected, name) = self.expect(.wildcardKeyword) } keepGoing = consume(if: .comma) params.append(RawClosureParamSyntax( unexpected, name: name, trailingComma: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } input = .simpleInput(RawClosureParamListSyntax(elements: params, arena: self.arena)) } asyncKeyword = self.parseEffectsSpecifier() throwsTok = self.parseEffectsSpecifier() // Parse the optional explicit return type. if let arrow = self.consume(if: .arrow) { // Parse the type. let returnTy = self.parseType() output = RawReturnClauseSyntax( arrow: arrow, returnType: returnTy, arena: self.arena ) } } // Parse the 'in'. let (unexpectedBeforeInTok, inTok) = self.expect(.inKeyword) return RawClosureSignatureSyntax( attributes: attrs, capture: captures, input: input, asyncKeyword: asyncKeyword, throwsTok: throwsTok, output: output, unexpectedBeforeInTok, inTok: inTok, arena: self.arena) } @_spi(RawSyntax) public mutating func parseClosureCaptureSpecifiers() -> RawTokenListSyntax? { var specifiers = [RawTokenSyntax]() do { // Check for the strength specifier: "weak", "unowned", or // "unowned(safe/unsafe)". if let weakContextualKeyword = self.consumeIfContextualKeyword("weak") { specifiers.append(weakContextualKeyword) } else if let unownedContextualKeyword = self.consumeIfContextualKeyword("unowned") { specifiers.append(unownedContextualKeyword) if let lparen = self.consume(if: .leftParen) { specifiers.append(lparen) if self.currentToken.tokenText == "safe" { specifiers.append(self.expectContextualKeywordWithoutRecovery("safe")) } else { specifiers.append(self.expectContextualKeywordWithoutRecovery("unsafe")) } specifiers.append(self.expectWithoutRecovery(.rightParen)) } } else if self.at(.identifier) || self.at(.selfKeyword) { let next = self.peek() // "x = 42", "x," and "x]" are all strong captures of x. guard next.tokenKind == .equal || next.tokenKind == .comma || next.tokenKind == .rightSquareBracket || next.tokenKind == .period else { return nil } } else { return nil } } // Squash all tokens, if any, as the specifier of the captured item. return RawTokenListSyntax(elements: specifiers, arena: self.arena) } } extension Parser { /// Parse the elements of an argument list. /// /// This is currently the same as parsing a tuple expression. In the future, /// this will be a dedicated argument list type. /// /// Grammar /// ======= /// /// tuple-element → expression | identifier ':' expression @_spi(RawSyntax) public mutating func parseArgumentListElements(pattern: PatternContext) -> [RawTupleExprElementSyntax] { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return [RawTupleExprElementSyntax( remainingTokens, label: nil, colon: nil, expression: RawExprSyntax(RawMissingExprSyntax(arena: self.arena)), trailingComma: nil, arena: self.arena )] } guard !self.at(.rightParen) else { return [] } var result = [RawTupleExprElementSyntax]() var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { let unexpectedBeforeLabel: RawUnexpectedNodesSyntax? let label: RawTokenSyntax? let colon: RawTokenSyntax? if currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon { (unexpectedBeforeLabel, label) = parseArgumentLabel() colon = consumeAnyToken() } else { unexpectedBeforeLabel = nil label = nil colon = nil } // See if we have an operator decl ref '(<op>)'. The operator token in // this case lexes as a binary operator because it neither leads nor // follows a proper subexpression. let expr: RawExprSyntax if self.at(anyIn: BinaryOperator.self) != nil && (self.peek().tokenKind == .comma || self.peek().tokenKind == .rightParen || self.peek().tokenKind == .rightSquareBracket) { let (ident, args) = self.parseDeclNameRef(.operators) expr = RawExprSyntax(RawIdentifierExprSyntax( identifier: ident, declNameArguments: args, arena: self.arena)) } else { expr = self.parseExpression(pattern: pattern) } keepGoing = self.consume(if: .comma) result.append(RawTupleExprElementSyntax( unexpectedBeforeLabel, label: label, colon: colon, expression: expr, trailingComma: keepGoing, arena: self.arena )) } while keepGoing != nil && loopProgress.evaluate(currentToken) return result } } extension Parser { /// Parse the trailing closure(s) following a call expression. /// /// Grammar /// ======= /// /// trailing-closures → closure-expression labeled-trailing-closures? /// labeled-trailing-closures → labeled-trailing-closure labeled-trailing-closures? /// labeled-trailing-closure → identifier ':' closure-expression @_spi(RawSyntax) public mutating func parseTrailingClosures(_ flavor: ExprFlavor) -> (RawClosureExprSyntax, RawMultipleTrailingClosureElementListSyntax?) { // Parse the closure. let closure = self.parseClosureExpression() // Parse labeled trailing closures. var elements = [RawMultipleTrailingClosureElementSyntax]() var loopProgress = LoopProgressCondition() while self.lookahead().isStartOfLabelledTrailingClosure() && loopProgress.evaluate(currentToken) { let (unexpectedBeforeLabel, label) = self.parseArgumentLabel() let (unexpectedBeforeColon, colon) = self.expect(.colon) let closure = self.parseClosureExpression() elements.append(RawMultipleTrailingClosureElementSyntax( unexpectedBeforeLabel, label: label, unexpectedBeforeColon, colon: colon, closure: closure, arena: self.arena )) } let trailing = elements.isEmpty ? nil : RawMultipleTrailingClosureElementListSyntax(elements: elements, arena: self.arena) return (closure, trailing) } } extension Parser.Lookahead { func isStartOfLabelledTrailingClosure() -> Bool { // Fast path: the next two tokens must be a label and a colon. // But 'default:' is ambiguous with switch cases and we disallow it // (unless escaped) even outside of switches. if !self.currentToken.canBeArgumentLabel() || self.at(.defaultKeyword) || self.peek().tokenKind != .colon { return false } // Do some tentative parsing to distinguish `label: { ... }` and // `label: switch x { ... }`. var backtrack = self.lookahead() backtrack.consumeAnyToken() if backtrack.peek().tokenKind == .leftBrace { return true } if backtrack.peek().isEditorPlaceholder { // Editor placeholder can represent entire closures return true } return false } /// Recover invalid uses of trailing closures in a situation /// where the parser requires an expr-basic (which does not allow them). We /// handle this by doing some lookahead in common situations. And later, Sema /// will emit a diagnostic with a fixit to add wrapping parens. func isValidTrailingClosure(_ flavor: Parser.ExprFlavor) -> Bool { assert(self.at(.leftBrace), "Couldn't be a trailing closure") // If this is the start of a get/set accessor, then it isn't a trailing // closure. guard !self.lookahead().isStartOfGetSetAccessor() else { return false } // If this is a normal expression (not an expr-basic) then trailing closures // are allowed, so this is obviously one. // TODO: We could handle try to disambiguate cases like: // let x = foo // {...}() // by looking ahead for the ()'s, but this has been replaced by do{}, so this // probably isn't worthwhile. guard case .basic = flavor else { return true } // If this is an expr-basic, then a trailing closure is not allowed. However, // it is very common for someone to write something like: // // for _ in numbers.filter {$0 > 4} { // // and we want to recover from this very well. We need to perform arbitrary // look-ahead to disambiguate this case, so we only do this in the case where // the token after the { is on the same line as the {. guard !self.peek().isAtStartOfLine else { return false } // Determine if the {} goes with the expression by eating it, and looking // to see if it is immediately followed by a token which indicates we should // consider it part of the preceding expression var backtrack = self.lookahead() backtrack.eat(.leftBrace) var loopProgress = LoopProgressCondition() while !backtrack.at(any: [.eof, .rightBrace, .poundEndifKeyword, .poundElseKeyword, .poundElseifKeyword ]) && loopProgress.evaluate(backtrack.currentToken) { backtrack.skipSingle() } guard backtrack.consume(if: .rightBrace) != nil else { return false } switch backtrack.currentToken.tokenKind { case .leftBrace, .whereKeyword, .comma: return true case .leftSquareBracket, .leftParen, .period, .prefixPeriod, .isKeyword, .asKeyword, .postfixQuestionMark, .infixQuestionMark, .exclamationMark, .colon, .equal, .postfixOperator, .spacedBinaryOperator, .unspacedBinaryOperator: return !backtrack.currentToken.isAtStartOfLine default: return false } } } // MARK: Lookahead extension Parser.Lookahead { // Consume 'async', 'throws', and 'rethrows', but in any order. mutating func consumeEffectsSpecifiers() { var loopProgress = LoopProgressCondition() while let (_, handle) = self.at(anyIn: EffectsSpecifier.self), loopProgress.evaluate(currentToken) { self.eat(handle) } } func canParseClosureSignature() -> Bool { // Consume attributes. var lookahead = self.lookahead() var attributesProgress = LoopProgressCondition() while let _ = lookahead.consume(if: .atSign), attributesProgress.evaluate(lookahead.currentToken) { guard lookahead.at(.identifier) else { break } _ = lookahead.canParseCustomAttribute() } // Skip by a closure capture list if present. if lookahead.consume(if: .leftSquareBracket) != nil { lookahead.skipUntil(.rightSquareBracket, .rightSquareBracket) if lookahead.consume(if: .rightSquareBracket) == nil { return false } } // Parse pattern-tuple func-signature-result? 'in'. if lookahead.consume(if: .leftParen) != nil { // Consume the ')'. // While we don't have '->' or ')', eat balanced tokens. var skipProgress = LoopProgressCondition() while !lookahead.at(any: [.eof, .rightParen]) && skipProgress.evaluate(lookahead.currentToken) { lookahead.skipSingle() } // Consume the ')', if it's there. if lookahead.consume(if: .rightParen) != nil { lookahead.consumeEffectsSpecifiers() // Parse the func-signature-result, if present. if lookahead.consume(if: .arrow) != nil { guard lookahead.canParseType() else { return false } lookahead.consumeEffectsSpecifiers() } } // Okay, we have a closure signature. } else if lookahead.at(.identifier) || lookahead.at(.wildcardKeyword) { // Parse identifier (',' identifier)* lookahead.consumeAnyToken() var parametersProgress = LoopProgressCondition() while lookahead.consume(if: .comma) != nil && parametersProgress.evaluate(lookahead.currentToken) { if lookahead.at(.identifier) || lookahead.at(.wildcardKeyword) { lookahead.consumeAnyToken() continue } return false } lookahead.consumeEffectsSpecifiers() // Parse the func-signature-result, if present. if lookahead.consume(if: .arrow) != nil { guard lookahead.canParseType() else { return false } lookahead.consumeEffectsSpecifiers() } } // Parse the 'in' at the end. guard lookahead.at(.inKeyword) else { return false } // Okay, we have a closure signature. return true } } extension Parser.Lookahead { // Helper function to see if we can parse member reference like suffixes // inside '#if'. fileprivate func isAtStartOfPostfixExprSuffix() -> Bool { guard self.at(any: [.period, .prefixPeriod]) else { return false } if self.at(.integerLiteral) { return true } if self.peek().tokenKind != .identifier, self.peek().tokenKind != .capitalSelfKeyword, self.peek().tokenKind != .selfKeyword, !self.peek().tokenKind.isKeyword { return false } return true } fileprivate func isNextTokenCallPattern() -> Bool { switch self.peek().tokenKind { case .period, .prefixPeriod, .leftParen: return true default: return false } } }
apache-2.0
6b58c9eca438cd33d5a0b50592f8c3a0
34.735492
181
0.64396
4.823254
false
false
false
false
ITzTravelInTime/TINU
TINU/OtherWindowsControllers.swift
1
2757
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa public class DriveDetectInfoWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title += ": Why is my storage device not detected?" } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "DriveDetectionInfo") as! NSWindowController).window) //self.window?.isFullScreenEnaled = false //self.init(windowNibName: "ContactsWindowController") } } public class DownloadAppWindowController: NSWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.isFullScreenEnaled = true self.window?.collectionBehavior.insert(.fullScreenNone) } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "DownloadApp") as! NSWindowController).window) //self.window?.isFullScreenEnaled = false //self.init(windowNibName: "ContactsWindowController") } } public class ContactsWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title += ": Contact us" } convenience init() { //creates an instace of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "Contacts") as! NSWindowController).window) //self.init(windowNibName: "ContactsWindowController") } } public class CreditsWindowController: GenericWindowController { override public func windowDidLoad() { super.windowDidLoad() self.window?.title = "About " + (self.window?.title ?? "TINU") } convenience init() { //creates an istance of the window self.init(window: (UIManager.shared.storyboard.instantiateController(withIdentifier: "Credits") as! NSWindowController).window) //self.init(windowNibName: "ContactsWindowController") } }
gpl-2.0
5acab0f95f3ada9711e812da80541269
31.435294
140
0.770403
4.248074
false
false
false
false
Sajjon/ViewComposer
Source/Classes/ViewAttribute/AttributedValues/TextInputTraitable.swift
1
2800
// // TextInputTraitable.swift // ViewComposer // // Created by Alexander Cyon on 2017-07-03. // // import Foundation protocol TextInputTraitable: class { var autocapitalizationType: UITextAutocapitalizationType { get set } var autocorrectionType: UITextAutocorrectionType { get set } var spellCheckingType: UITextSpellCheckingType { get set } var keyboardType: UIKeyboardType { get set } var keyboardAppearance: UIKeyboardAppearance { get set } var returnKeyType: UIReturnKeyType { get set } var enablesReturnKeyAutomatically: Bool { get set } var isSecureTextEntry: Bool { get set } var textContentTypeProxy: UITextContentType? { get set } } extension UITextField: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } extension UITextView: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } extension UISearchBar: TextInputTraitable { var textContentTypeProxy: UITextContentType? { get { guard #available(iOS 10.0, *) else { return nil } return textContentType } set { guard #available(iOS 10.0, *) else { return } textContentType = newValue } } } internal extension TextInputTraitable { func apply(_ style: ViewStyle) { style.attributes.forEach { switch $0 { case .autocapitalizationType(let type): autocapitalizationType = type case .autocorrectionType(let type): autocorrectionType = type case .spellCheckingType(let type): spellCheckingType = type case .keyboardType(let type): keyboardType = type case .keyboardAppearance(let appearance): keyboardAppearance = appearance case .returnKeyType(let type): returnKeyType = type case .enablesReturnKeyAutomatically(let enables): enablesReturnKeyAutomatically = enables case .isSecureTextEntry(let isSecure): isSecureTextEntry = isSecure case .textContentType(let type): textContentTypeProxy = type default: break } } } }
mit
49458b131f50773017addc621f9b8648
29.434783
72
0.596071
5.857741
false
false
false
false
mluedke2/jsonjam
Pod/Classes/JSONHelper.swift
2
9844
// // JSONHelper.swift // // Created by Baris Sencan on 28/08/2014. // Copyright 2014 Baris Sencan // // Distributed under the permissive zlib license // Get the latest version from here: // // https://github.com/isair/JSONHelper // // 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: // // 1. 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 would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // import Foundation /// A type of dictionary that only uses strings for keys and can contain any /// type of object as a value. public typealias JSONDictionary = [String: AnyObject] /// Operator for use in deserialization operations. infix operator <-- { associativity right precedence 150 } /// Returns nil if given object is of type NSNull. /// /// :param: object Object to convert. /// /// :returns: nil if object is of type NSNull, else returns the object itself. private func convertToNilIfNull(object: AnyObject?) -> AnyObject? { if object is NSNull { return nil } return object } /// MARK: Primitive Type Deserialization // For optionals. public func <-- <T>(inout property: T?, value: AnyObject?) -> T? { var newValue: T? "" if let unwrappedValue: AnyObject = convertToNilIfNull(value) { // We unwrapped the given value successfully, try to convert. if let convertedValue = unwrappedValue as? T { // Convert by just type-casting. newValue = convertedValue } else { // Convert by processing the value first. switch property { case is Int?: if unwrappedValue is String { if let intValue = "\(unwrappedValue)".toInt() { newValue = intValue as? T } } case is NSURL?: newValue = NSURL(string: "\(unwrappedValue)") as? T case is NSDate?: if let timestamp = unwrappedValue as? Int { newValue = NSDate(timeIntervalSince1970: Double(timestamp)) as? T } else if let timestamp = unwrappedValue as? Double { newValue = NSDate(timeIntervalSince1970: timestamp) as? T } else if let timestamp = unwrappedValue as? NSNumber { newValue = NSDate(timeIntervalSince1970: timestamp.doubleValue) as? T } default: break } } } property = newValue return property } // For non-optionals. public func <-- <T>(inout property: T, value: AnyObject?) -> T { var newValue: T? newValue <-- value if let newValue = newValue { property = newValue } return property } // Special handling for value and format pair to NSDate conversion. public func <-- (inout property: NSDate?, valueAndFormat: (AnyObject?, AnyObject?)) -> NSDate? { var newValue: NSDate? if let dateString = convertToNilIfNull(valueAndFormat.0) as? String { if let formatString = convertToNilIfNull(valueAndFormat.1) as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString if let newDate = dateFormatter.dateFromString(dateString) { newValue = newDate } } } property = newValue return property } public func <-- (inout property: NSDate, valueAndFormat: (AnyObject?, AnyObject?)) -> NSDate { var date: NSDate? date <-- valueAndFormat if let date = date { property = date } return property } // MARK: Primitive Array Deserialization public func <-- (inout array: [String]?, value: AnyObject?) -> [String]? { if let stringArray = convertToNilIfNull(value) as? [String] { array = stringArray } else { array = nil } return array } public func <-- (inout array: [String], value: AnyObject?) -> [String] { var newValue: [String]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Int]?, value: AnyObject?) -> [Int]? { if let intArray = convertToNilIfNull(value) as? [Int] { array = intArray } else { array = nil } return array } public func <-- (inout array: [Int], value: AnyObject?) -> [Int] { var newValue: [Int]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Float]?, value: AnyObject?) -> [Float]? { if let floatArray = convertToNilIfNull(value) as? [Float] { array = floatArray } else { array = nil } return array } public func <-- (inout array: [Float], value: AnyObject?) -> [Float] { var newValue: [Float]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Double]?, value: AnyObject?) -> [Double]? { if let doubleArrayDoubleExcitement = convertToNilIfNull(value) as? [Double] { array = doubleArrayDoubleExcitement } else { array = nil } return array } public func <-- (inout array: [Double], value: AnyObject?) -> [Double] { var newValue: [Double]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [Bool]?, value: AnyObject?) -> [Bool]? { if let boolArray = convertToNilIfNull(value) as? [Bool] { array = boolArray } else { array = nil } return array } public func <-- (inout array: [Bool], value: AnyObject?) -> [Bool] { var newValue: [Bool]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSURL]?, value: AnyObject?) -> [NSURL]? { if let stringURLArray = convertToNilIfNull(value) as? [String] { array = [NSURL]() for stringURL in stringURLArray { if let url = NSURL(string: stringURL) { array!.append(url) } } } else { array = nil } return array } public func <-- (inout array: [NSURL], value: AnyObject?) -> [NSURL] { var newValue: [NSURL]? newValue <-- value if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSDate]?, valueAndFormat: (AnyObject?, AnyObject?)) -> [NSDate]? { var newValue: [NSDate]? if let dateStringArray = convertToNilIfNull(valueAndFormat.0) as? [String] { if let formatString = convertToNilIfNull(valueAndFormat.1) as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = formatString newValue = [NSDate]() for dateString in dateStringArray { if let date = dateFormatter.dateFromString(dateString) { newValue!.append(date) } } } } array = newValue return array } public func <-- (inout array: [NSDate], valueAndFormat: (AnyObject?, AnyObject?)) -> [NSDate] { var newValue: [NSDate]? newValue <-- valueAndFormat if let newValue = newValue { array = newValue } return array } public func <-- (inout array: [NSDate]?, value: AnyObject?) -> [NSDate]? { if let timestamps = convertToNilIfNull(value) as? [AnyObject] { array = [NSDate]() for timestamp in timestamps { var date: NSDate? date <-- timestamp if date != nil { array!.append(date!) } } } else { array = nil } return array } public func <-- (inout array: [NSDate], value: AnyObject?) -> [NSDate] { var newValue: [NSDate]? newValue <-- value if let newValue = newValue { array = newValue } return array } // MARK: Custom Object Deserialization public protocol Deserializable { init(data: JSONDictionary) } public func <-- <T: Deserializable>(inout instance: T?, dataObject: AnyObject?) -> T? { if let data = convertToNilIfNull(dataObject) as? JSONDictionary { instance = T(data: data) } else { instance = nil } return instance } public func <-- <T: Deserializable>(inout instance: T, dataObject: AnyObject?) -> T { var newInstance: T? newInstance <-- dataObject if let newInstance = newInstance { instance = newInstance } return instance } // MARK: Custom Object Array Deserialization public func <-- <T: Deserializable>(inout array: [T]?, dataObject: AnyObject?) -> [T]? { if let dataArray = convertToNilIfNull(dataObject) as? [JSONDictionary] { array = [T]() for data in dataArray { array!.append(T(data: data)) } } else { array = nil } return array } public func <-- <T: Deserializable>(inout array: [T], dataObject: AnyObject?) -> [T] { var newArray: [T]? newArray <-- dataObject if let newArray = newArray { array = newArray } return array } // MARK: JSON String Deserialization private func dataStringToObject(dataString: String) -> AnyObject? { var data: NSData = dataString.dataUsingEncoding(NSUTF8StringEncoding)! var error: NSError? return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) } public func <-- <T: Deserializable>(inout instance: T?, dataString: String) -> T? { return instance <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout instance: T, dataString: String) -> T { return instance <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout array: [T]?, dataString: String) -> [T]? { return array <-- dataStringToObject(dataString) } public func <-- <T: Deserializable>(inout array: [T], dataString: String) -> [T] { return array <-- dataStringToObject(dataString) }
mit
0781eb7b159ade53a30e2e1c68c900f7
28.297619
102
0.665278
4.197868
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/NSDate.swift
1
15544
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // @_implementationOnly import CoreFoundation public typealias TimeInterval = Double public var NSTimeIntervalSince1970: Double { return 978307200.0 } #if os(Windows) extension TimeInterval { init(_ ftTime: FILETIME) { self = Double((ftTime.dwHighDateTime << 32) | ftTime.dwLowDateTime) - NSTimeIntervalSince1970; } } #else extension timeval { internal init(_timeIntervalSince1970: TimeInterval) { let (integral, fractional) = modf(_timeIntervalSince1970) self.init(tv_sec: time_t(integral), tv_usec: suseconds_t(1.0e6 * fractional)) } } #endif open class NSDate : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFDate open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Date: return isEqual(to: other) case let other as NSDate: return isEqual(to: Date(timeIntervalSinceReferenceDate: other.timeIntervalSinceReferenceDate)) default: return false } } deinit { _CFDeinit(self) } internal final var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } internal let _base = _CFInfo(typeID: CFDateGetTypeID()) internal let _timeIntervalSinceReferenceDate: TimeInterval open var timeIntervalSinceReferenceDate: TimeInterval { return _timeIntervalSinceReferenceDate } open class var timeIntervalSinceReferenceDate: TimeInterval { return Date().timeIntervalSinceReferenceDate } public convenience override init() { self.init(timeIntervalSinceReferenceDate: CFAbsoluteTimeGetCurrent()) } public required init(timeIntervalSinceReferenceDate ti: TimeInterval) { _timeIntervalSinceReferenceDate = ti } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let ti = aDecoder.decodeDouble(forKey: "NS.time") self.init(timeIntervalSinceReferenceDate: ti) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(_timeIntervalSinceReferenceDate, forKey: "NS.time") } /** A string representation of the date object (read-only). The representation is useful for debugging only. There are a number of options to acquire a formatted string for a date including: date formatters (see [NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and [Data Formatting Guide](//apple_ref/doc/uid/10000029i)), and the `NSDate` methods `descriptionWithLocale:`, `dateWithCalendarFormat:timeZone:`, and `descriptionWithCalendarFormat:timeZone:locale:`. */ open override var description: String { let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, nil, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle) let timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorSystemDefault, 0.0) CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, timeZone) CFDateFormatterSetFormat(dateFormatterRef, "uuuu-MM-dd HH:mm:ss '+0000'"._cfObject) return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject } /** Returns a string representation of the receiver using the given locale. - Parameter locale: An `NSLocale` object. If you pass `nil`, `NSDate` formats the date in the same way as the `description` property. - Returns: A string representation of the receiver, using the given locale, or if the locale argument is `nil`, in the international format `YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone offset in hours and minutes from UTC (for example, "2001-03-24 10:45:32 +0600") */ open func description(with locale: Locale?) -> String { guard let aLocale = locale else { return description } let dateFormatterRef = CFDateFormatterCreate(kCFAllocatorSystemDefault, aLocale._cfObject, kCFDateFormatterFullStyle, kCFDateFormatterFullStyle) CFDateFormatterSetProperty(dateFormatterRef, kCFDateFormatterTimeZoneKey, CFTimeZoneCopySystem()) return CFDateFormatterCreateStringWithDate(kCFAllocatorSystemDefault, dateFormatterRef, _cfObject)._swiftObject } internal override var _cfTypeID: CFTypeID { return CFDateGetTypeID() } } extension NSDate { open func timeIntervalSince(_ anotherDate: Date) -> TimeInterval { return self.timeIntervalSinceReferenceDate - anotherDate.timeIntervalSinceReferenceDate } open var timeIntervalSinceNow: TimeInterval { return timeIntervalSince(Date()) } open var timeIntervalSince1970: TimeInterval { return timeIntervalSinceReferenceDate + NSTimeIntervalSince1970 } open func addingTimeInterval(_ ti: TimeInterval) -> Date { return Date(timeIntervalSinceReferenceDate:_timeIntervalSinceReferenceDate + ti) } open func earlierDate(_ anotherDate: Date) -> Date { if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } else { return anotherDate } } open func laterDate(_ anotherDate: Date) -> Date { if self.timeIntervalSinceReferenceDate < anotherDate.timeIntervalSinceReferenceDate { return anotherDate } else { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } } open func compare(_ other: Date) -> ComparisonResult { let t1 = self.timeIntervalSinceReferenceDate let t2 = other.timeIntervalSinceReferenceDate if t1 < t2 { return .orderedAscending } else if t1 > t2 { return .orderedDescending } else { return .orderedSame } } open func isEqual(to otherDate: Date) -> Bool { return timeIntervalSinceReferenceDate == otherDate.timeIntervalSinceReferenceDate } } extension NSDate { internal static let _distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0) open class var distantFuture: Date { return _distantFuture } internal static let _distantPast = Date(timeIntervalSinceReferenceDate: -63113904000.0) open class var distantPast: Date { return _distantPast } public convenience init(timeIntervalSinceNow secs: TimeInterval) { self.init(timeIntervalSinceReferenceDate: secs + Date().timeIntervalSinceReferenceDate) } public convenience init(timeIntervalSince1970 secs: TimeInterval) { self.init(timeIntervalSinceReferenceDate: secs - NSTimeIntervalSince1970) } public convenience init(timeInterval secsToBeAdded: TimeInterval, since date: Date) { self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + secsToBeAdded) } } extension NSDate: _SwiftBridgeable { typealias SwiftType = Date var _swiftObject: Date { return Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } } extension CFDate : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSDate typealias SwiftType = Date internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Date { return _nsObject._swiftObject } } extension Date : _NSBridgeable { typealias NSType = NSDate typealias CFType = CFDate internal var _nsObject: NSType { return NSDate(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate) } internal var _cfObject: CFType { return _nsObject._cfObject } } open class NSDateInterval : NSObject, NSCopying, NSSecureCoding { /* NSDateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. NSDateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date. */ open private(set) var startDate: Date open var endDate: Date { get { if duration == 0 { return startDate } else { return startDate + duration } } } open private(set) var duration: TimeInterval // This method initializes an NSDateInterval object with start and end dates set to the current date and the duration set to 0. public convenience override init() { self.init(start: Date(), duration: 0) } public required convenience init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let start = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else { coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil)) return nil } guard let end = coder.decodeObject(of: NSDate.self, forKey: "NS.startDate") else { coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: CocoaError.coderValueNotFound.rawValue, userInfo: nil)) return nil } self.init(start: start._swiftObject, end: end._swiftObject) } // This method will throw an exception if the duration is less than 0. public init(start startDate: Date, duration: TimeInterval) { self.startDate = startDate self.duration = duration } // This method will throw an exception if the end date comes before the start date. public convenience init(start startDate: Date, end endDate: Date) { self.init(start: startDate, duration: endDate.timeIntervalSince(startDate)) } open func copy(with zone: NSZone?) -> Any { return NSDateInterval(start: startDate, duration: duration) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(startDate._nsObject, forKey: "NS.startDate") aCoder.encode(endDate._nsObject, forKey: "NS.endDate") } public static var supportsSecureCoding: Bool { return true } /* (ComparisonResult)compare:(NSDateInterval *) prioritizes ordering by start date. If the start dates are equal, then it will order by duration. e.g. Given intervals a and b a. |-----| b. |-----| [a compare:b] would return NSOrderAscending because a's startDate is earlier in time than b's start date. In the event that the start dates are equal, the compare method will attempt to order by duration. e.g. Given intervals c and d c. |-----| d. |---| [c compare:d] would result in NSOrderDescending because c is longer than d. If both the start dates and the durations are equal, then the intervals are considered equal and NSOrderedSame is returned as the result. */ open func compare(_ dateInterval: DateInterval) -> ComparisonResult { let result = startDate.compare(dateInterval.start) if result == .orderedSame { if self.duration < dateInterval.duration { return .orderedAscending } if self.duration > dateInterval.duration { return .orderedDescending } return .orderedSame } return result } open func isEqual(to dateInterval: DateInterval) -> Bool { return startDate == dateInterval.start && duration == dateInterval.duration } open func intersects(_ dateInterval: DateInterval) -> Bool { return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(startDate) || dateInterval.contains(endDate) } /* This method returns an NSDateInterval object that represents the interval where the given date interval and the current instance intersect. In the event that there is no intersection, the method returns nil. */ open func intersection(with dateInterval: DateInterval) -> DateInterval? { if !intersects(dateInterval) { return nil } if isEqual(to: dateInterval) { return DateInterval(start: startDate, duration: duration) } let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate let timeIntervalForSelfEnd = startDate.timeIntervalSinceReferenceDate let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate let resultStartDate : Date if timeIntervalForGivenStart >= timeIntervalForSelfStart { resultStartDate = dateInterval.start } else { // self starts after given resultStartDate = startDate } let resultEndDate : Date if timeIntervalForGivenEnd >= timeIntervalForSelfEnd { resultEndDate = endDate } else { // given ends before self resultEndDate = dateInterval.end } return DateInterval(start: resultStartDate, end: resultEndDate) } open func contains(_ date: Date) -> Bool { let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate let timeIntervalForSelfStart = startDate.timeIntervalSinceReferenceDate let timeIntervalforSelfEnd = endDate.timeIntervalSinceReferenceDate if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) { return true } return false } } extension NSDate : _StructTypeBridgeable { public typealias _StructType = Date public func _bridgeToSwift() -> Date { return Date._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateInterval : _StructTypeBridgeable { public typealias _StructType = DateInterval public func _bridgeToSwift() -> DateInterval { return DateInterval._unconditionallyBridgeFromObjectiveC(self) } } extension NSDateInterval : _SwiftBridgeable { var _swiftObject: DateInterval { return _bridgeToSwift() } }
apache-2.0
2fe5da75b4f8461aef810effb1604d62
35.060325
332
0.680286
5.493814
false
false
false
false
huonw/swift
test/stdlib/StringOrderRelation.swift
41
559
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var StringOrderRelationTestSuite = TestSuite("StringOrderRelation") StringOrderRelationTestSuite.test("StringOrderRelation/ASCII/NullByte") { let baseString = "a" let nullbyteString = "a\0" expectTrue(baseString < nullbyteString) expectTrue(baseString <= nullbyteString) expectFalse(baseString > nullbyteString) expectFalse(baseString >= nullbyteString) expectFalse(baseString == nullbyteString) expectTrue(baseString != nullbyteString) } runAllTests()
apache-2.0
89db3c8851390b3e6ef2d824c67cddcc
25.619048
73
0.785331
4.658333
false
true
false
false
900116/GodEyeClear
Classes/Model/LeakRecordModel.swift
1
1337
// // LeakRecordModel.swift // Pods // // Created by zixun on 17/1/12. // // import Foundation import Realm import RealmSwift final class LeakRecordModel: Object { dynamic open var clazz: String! dynamic open var address: String! init(obj:NSObject) { super.init() self.clazz = NSStringFromClass(obj.classForCoder) self.address = String(format:"%p", obj) } init(clazz:String, address: String) { super.init() self.clazz = clazz self.address = address } required init() { super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm:realm,schema:schema) } required init(value: Any, schema: RLMSchema) { super.init(value:value,schema:schema) } } extension LeakRecordModel : RecordORMProtocol { static var type: RecordType { return RecordType.leak } func attributeString() -> NSAttributedString { let result = NSMutableAttributedString() result.append(self.headerString()) return result } private func headerString() -> NSAttributedString { return self.headerString(with: "Leak", content: "[\(self.clazz): \(self.address)]", color: UIColor(hex: 0xB754C4)) } }
mit
837469c10e803b9ef104e2621d13be66
21.283333
122
0.608078
4.355049
false
false
false
false
ORT-Interactive-GmbH/OnlineL10n
OnlineL10n/UI/CountryCell.swift
1
762
// // CountryCell.swift // SwiftLocalization // // Created by Sebastian Westemeyer on 28.04.16. // Copyright © 2016 ORT Interactive. All rights reserved. // import Foundation public let CountryCellStoryboardId = "CountryCell" class CountryCell: UITableViewCell { @IBOutlet weak var imageViewFlag: UIImageView! @IBOutlet weak var labelName: UILabel! @IBOutlet weak var constraintImageWidth: NSLayoutConstraint! func display(flag: Data?) { if (flag == nil) { imageViewFlag.isHidden = true constraintImageWidth.constant = 0.0 } else { imageViewFlag.isHidden = false constraintImageWidth.constant = 40.0 imageViewFlag.image = UIImage(data: flag!) } } }
mit
1af4a1b15ddec3b2a5de4a8315817040
26.178571
64
0.660972
4.502959
false
false
false
false
ORT-Interactive-GmbH/OnlineL10n
OnlineL10n/UI/UIExtensions.swift
1
2648
// // UIExtensions.swift // OnlineL18N // // Created by Sebastian Westemeyer on 27.04.16. // Copyright © 2016 ORT Interactive. All rights reserved. // import Foundation import UIKit @objc extension UILabel { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } } @objc extension UITextField { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } public func subscribeToLanguage(manager: LocalizationProvider, placeholder: String) { manager.subscribeToChange(object: self, key: placeholder, block: { (x: Any?) in self.placeholder = x as? String }) self.placeholder = manager.value(key: placeholder) } } @objc extension UITextView { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.text = x as? String }) self.text = manager.value(key: key) } } @objc extension UIButton { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.setTitle(x as? String, for: .normal) }) self.setTitle(manager.value(key: key), for: .normal) } } @objc extension UISegmentedControl { public func subscribeToLanguage(manager: LocalizationProvider, key: String, index: Int) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.setTitle(x as? String, forSegmentAt: index) }) self.setTitle(manager.value(key: key), forSegmentAt: index) } } @objc extension UIViewController { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.title = x as? String }) self.title = manager.value(key: key) } } @objc extension UIBarButtonItem { public func subscribeToLanguage(manager: LocalizationProvider, key: String) { manager.subscribeToChange(object: self, key: key, block: { (x: Any?) in self.title = x as? String }) self.title = manager.value(key: key) } }
mit
03f6929ddbe97bff97ba9af5d77e7b4e
32.0875
93
0.642236
4.135938
false
false
false
false
johnfairh/TMLPersistentContainer
Sources/ModelVersionGraph.swift
1
3202
// // ModelVersionGraph.swift // TMLPersistentContainer // // Distributed under the ISC license, see LICENSE. // import Foundation import CoreData /// Manage the graph of model versions and generate routes through it. /// Class is a container + facade onto the nodes + edges classes, and /// does type-translation to the graph solver. /// @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) struct ModelVersionGraph: LogMessageEmitter { let logMessageHandler: LogMessage.Handler? let nodes: ModelVersionNodes let edges: ModelVersionEdges } @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) extension ModelVersionGraph { /// Initialize a new, empty graph init(logMessageHandler: LogMessage.Handler?) { self.logMessageHandler = logMessageHandler nodes = ModelVersionNodes(logMessageHandler: logMessageHandler) edges = ModelVersionEdges(logMessageHandler: logMessageHandler) } /// Create a new graph func filtered(order: ModelVersionOrder, allowInferredMappings: Bool) -> ModelVersionGraph { let newGraph = ModelVersionGraph(logMessageHandler: logMessageHandler, nodes: nodes.filtered(order: order), edges: edges.filtered(order: order, allowInferredMappings: allowInferredMappings)) newGraph.logAll(.info, "Filtered graph under order \(order) with allowInferredMappings \(allowInferredMappings):") return newGraph } /// Analyze the model and mapping model files and build the migration graph between them func discover(from bundles: [Bundle]) { log(.info, "Starting model discovery from bundles \(bundles)") nodes.discover(from: bundles) edges.discover(from: bundles, between: nodes.nodes) logAll(.info, "Model graph discovery complete.") } /// Log the summary contents of the graph func logAll(_ level: LogLevel, _ message: String) { log(level, message) log(level, "Model graph nodes: \(self.nodes.nodes)") log(level, "Model graph edges: \(self.edges.edges)") } /// Log the details of discovered node metadata func logNodeMetadata(_ level: LogLevel) { nodes.logMetadata(level) } /// Find the starting point in the graph func nodeForStoreMetadata(_ storeMetadata: PersistentStoreMetadata, configuration: String?) -> ModelVersionNode? { return nodes.nodeForStoreMetadata(storeMetadata, configuration: configuration) } /// Find the ending point in the graph func nodeForObjectModel(_ objectModel: NSManagedObjectModel) -> ModelVersionNode? { return nodes.nodeForObjectModel(objectModel) } /// Find the best path through the versions or throw if there is none func findPath(source: ModelVersionNode, destination: ModelVersionNode) throws -> [ModelVersionEdge] { precondition(source != destination, "Logic error - no migration required") let graph = Graph(nodeCount: nodes.nodes.count, edges: edges.edges, logMessageHandler: logMessageHandler) return try graph.findPath(source: source.name, destination: destination.name) } }
isc
5d0b7f8860fce40012ea96107e777b7c
39.025
123
0.695191
4.743704
false
false
false
false
carabina/DDMathParser
MathParser/Functions+Defaults.swift
2
39055
// // StandardFunctions.swift // DDMathParser // // Created by Dave DeLong on 8/20/15. // // import Foundation public extension Function { private static let largestIntegerFactorial: Int = { var n = Int.max var i = 2 while i < n { n /= i i++ } return i - 1 }() // MARK: - Angle mode helpers internal static func _dtor(d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .Degrees else { return d } return d / 180 * M_PI } internal static func _rtod(d: Double, evaluator: Evaluator) -> Double { guard evaluator.angleMeasurementMode == .Degrees else { return d } return d / M_PI * 180 } public static let standardFunctions: Array<Function> = [ add, subtract, multiply, divide, mod, negate, factorial, factorial2, pow, sqrt, cuberoot, nthroot, random, abs, percent, log, ln, log2, exp, and, or, not, xor, lshift, rshift, sum, product, count, min, max, average, median, stddev, ceil, floor, sin, cos, tan, asin, acos, atan, atan2, csc, sec, cotan, acsc, asec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, csch, sech, cotanh, acsch, asech, acotanh, versin, vercosin, coversin, covercosin, haversin, havercosin, hacoversin, hacovercosin, exsec, excsc, crd, dtor, rtod, phi, pi, pi_2, pi_4, tau, sqrt2, e, log2e, log10e, ln2, ln10, l_and, l_or, l_not, l_eq, l_neq, l_lt, l_gt, l_ltoe, l_gtoe, l_if ] // MARK: - Basic functions public static let add = Function(name: "add", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 + arg2 }) public static let subtract = Function(name: "subtract", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 - arg2 }) public static let multiply = Function(names: ["multiply", "implicitmultiply"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return arg1 * arg2 }) public static let divide = Function(name: "divide", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) guard arg2 != 0 else { throw EvaluationError.DivideByZero } return arg1 / arg2 }) public static let mod = Function(names: ["mod", "modulo"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return fmod(arg1, arg2) }) public static let negate = Function(name: "negate", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return -arg1 }) public static let factorial = Function(name: "factorial", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1.factorial() }) public static let factorial2 = Function(name: "factorial2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 >= 1 else { throw EvaluationError.InvalidArguments } guard arg1 == Darwin.floor(arg1) else { throw EvaluationError.InvalidArguments } if arg1 % 2 == 0 { let k = arg1 / 2 return Darwin.pow(2, k) * k.factorial() } else { let k = (arg1 + 1) / 2 let numerator = (2*k).factorial() let denominator = Darwin.pow(2, k) * k.factorial() guard denominator != 0 else { throw EvaluationError.DivideByZero } return numerator / denominator } }) public static let pow = Function(name: "pow", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Darwin.pow(arg1, arg2) }) public static let sqrt = Function(name: "sqrt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let value = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sqrt(value) }) public static let cuberoot = Function(name: "cuberoot", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.pow(arg1, 1.0/3.0) }) public static let nthroot = Function(name: "nthroot", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) guard arg2 != 0 else { throw EvaluationError.DivideByZero } if arg1 < 0 && arg2 % 2 == 1 { // for negative numbers with an odd root, the result will be negative let root = Darwin.pow(-arg1, 1/arg2) return -root } else { return Darwin.pow(arg1, 1/arg2) } }) public static let random = Function(name: "random", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count <= 2 else { throw EvaluationError.InvalidArguments } var argValues = Array<Double>() for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) argValues.append(argValue) } let lowerBound = argValues.count > 0 ? argValues[0] : DBL_MIN let upperBound = argValues.count > 1 ? argValues[1] : DBL_MAX guard lowerBound < upperBound else { throw EvaluationError.InvalidArguments } let range = upperBound - lowerBound return (drand48() % range) + lowerBound }) public static let log = Function(name: "log", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log10(arg1) }) public static let ln = Function(name: "ln", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log(arg1) }) public static let log2 = Function(name: "log2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.log2(arg1) }) public static let exp = Function(name: "exp", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.exp(arg1) }) public static let abs = Function(name: "abs", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Swift.abs(arg1) }) public static let percent = Function(name: "percent", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let percentArgument = args[0] let percentValue = try evaluator.evaluate(percentArgument, substitutions: substitutions) let percent = percentValue / 100 let percentExpression = percentArgument.parent let percentContext = percentExpression?.parent guard let contextKind = percentContext?.kind else { return percent } guard case let .Function(f, contextArgs) = contextKind else { return percent } // must be XXXX + n% or XXXX - n% guard let builtIn = BuiltInOperator(rawValue: f) where builtIn == .Add || builtIn == .Minus else { return percent } // cannot be n% + XXXX or n% - XXXX guard contextArgs[1] === percentExpression else { return percent } let context = try evaluator.evaluate(contextArgs[0], substitutions: substitutions) return context * percent }) // MARK: - Bitwise functions public static let and = Function(name: "and", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) & Int(arg2)) }) public static let or = Function(name: "or", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) | Int(arg2)) }) public static let not = Function(name: "not", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Double(~Int(arg1)) }) public static let xor = Function(name: "xor", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) ^ Int(arg2)) }) public static let rshift = Function(name: "rshift", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) >> Int(arg2)) }) public static let lshift = Function(name: "lshift", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Double(Int(arg1) << Int(arg2)) }) // MARK: - Aggregate functions public static let average = Function(names: ["average", "avg", "mean"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } let value = try sum.evaluator(args, substitutions, evaluator) return value / Double(args.count) }) public static let sum = Function(names: ["sum", "∑"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = 0.0 for arg in args { value += try evaluator.evaluate(arg, substitutions: substitutions) } return value }) public static let product = Function(names: ["product", "∏"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = 1.0 for arg in args { value *= try evaluator.evaluate(arg, substitutions: substitutions) } return value }) public static let count = Function(name: "count", evaluator: { (args, substitutions, evaluator) throws -> Double in return Double(args.count) }) public static let min = Function(name: "min", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = DBL_MAX for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) value = Swift.min(value, argValue) } return value }) public static let max = Function(name: "max", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count > 0 else { throw EvaluationError.InvalidArguments } var value = DBL_MIN for arg in args { let argValue = try evaluator.evaluate(arg, substitutions: substitutions) value = Swift.max(value, argValue) } return value }) public static let median = Function(name: "median", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count >= 2 else { throw EvaluationError.InvalidArguments } var evaluated = Array<Double>() for arg in args { evaluated.append(try evaluator.evaluate(arg, substitutions: substitutions)) } if evaluated.count % 2 == 1 { let index = evaluated.count / 2 return evaluated[index] } else { let highIndex = evaluated.count / 2 let lowIndex = highIndex - 1 return Double((evaluated[highIndex] + evaluated[lowIndex]) / 2) } }) public static let stddev = Function(name: "stddev", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count >= 2 else { throw EvaluationError.InvalidArguments } let avg = try average.evaluator(args, substitutions, evaluator) var stddev = 0.0 for arg in args { let value = try evaluator.evaluate(arg, substitutions: substitutions) let diff = avg - value stddev += (diff * diff) } return Darwin.sqrt(stddev / Double(args.count)) }) public static let ceil = Function(name: "ceil", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.ceil(arg1) }) public static let floor = Function(names: ["floor", "trunc"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.floor(arg1) }) // MARK: - Trigonometric functions public static let sin = Function(name: "sin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let cos = Function(name: "cos", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let tan = Function(name: "tan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.tan(Function._dtor(arg1, evaluator: evaluator)) }) public static let asin = Function(name: "asin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.asin(arg1), evaluator: evaluator) }) public static let acos = Function(name: "acos", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.acos(arg1), evaluator: evaluator) }) public static let atan = Function(name: "atan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Function._rtod(Darwin.atan(arg1), evaluator: evaluator) }) public static let atan2 = Function(name: "atan2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return Function._rtod(Darwin.atan2(arg1, arg2), evaluator: evaluator) }) public static let csc = Function(name: "csc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let sec = Function(name: "sec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let cotan = Function(name: "cotan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.tan(Function._dtor(arg1, evaluator: evaluator)) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let acsc = Function(name: "acsc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.asin(1.0 / arg1), evaluator: evaluator) }) public static let asec = Function(name: "asec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.acos(1.0 / arg1), evaluator: evaluator) }) public static let acotan = Function(name: "acotan", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Function._rtod(Darwin.atan(1.0 / arg1), evaluator: evaluator) }) // MARK: - Hyperbolic trigonometric functions public static let sinh = Function(name: "sinh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.sinh(arg1) }) public static let cosh = Function(name: "cosh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.cosh(arg1) }) public static let tanh = Function(name: "tanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.tanh(arg1) }) public static let asinh = Function(name: "asinh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.asinh(arg1) }) public static let acosh = Function(name: "acosh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.acosh(arg1) }) public static let atanh = Function(name: "atanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return Darwin.atanh(arg1) }) public static let csch = Function(name: "csch", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.sinh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let sech = Function(name: "sech", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.cosh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let cotanh = Function(name: "cotanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg = Darwin.tanh(arg1) guard sinArg != 0 else { throw EvaluationError.DivideByZero } return 1.0 / sinArg }) public static let acsch = Function(name: "acsch", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.asinh(1.0 / arg1) }) public static let asech = Function(name: "asech", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.acosh(1.0 / arg1) }) public static let acotanh = Function(name: "acotanh", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) guard arg1 != 0 else { throw EvaluationError.DivideByZero } return Darwin.atanh(1.0 / arg1) }) // MARK: - Geometric functions public static let versin = Function(names: ["versin", "vers", "ver"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 - Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let vercosin = Function(names: ["vercosin", "vercos"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 + Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) }) public static let coversin = Function(names: ["coversin", "cvs"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 - Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let covercosin = Function(name: "covercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return 1.0 + Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) }) public static let haversin = Function(name: "haversin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try versin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let havercosin = Function(name: "havercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try vercosin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let hacoversin = Function(name: "hacoversin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try coversin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let hacovercosin = Function(name: "hacovercosin", evaluator: { (args, substitutions, evaluator) throws -> Double in return try covercosin.evaluator(args, substitutions, evaluator) / 2.0 }) public static let exsec = Function(name: "exsec", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let cosArg1 = Darwin.cos(Function._dtor(arg1, evaluator: evaluator)) guard cosArg1 != 0 else { throw EvaluationError.DivideByZero } return (1.0/cosArg1) - 1.0 }) public static let excsc = Function(name: "excsc", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: evaluator)) guard sinArg1 != 0 else { throw EvaluationError.DivideByZero } return (1.0/sinArg1) - 1.0 }) public static let crd = Function(names: ["crd", "chord"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let sinArg1 = Darwin.sin(Function._dtor(arg1, evaluator: evaluator) / 2.0) return 2 * sinArg1 }) public static let dtor = Function(name: "dtor", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1 / 180.0 * M_PI }) public static let rtod = Function(name: "rtod", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return arg1 / M_PI * 180 }) // MARK: - Constant functions public static let phi = Function(names: ["phi", "ϕ"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return 1.6180339887498948 }) public static let pi = Function(names: ["pi", "π", "tau_2"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI }) public static let pi_2 = Function(names: ["pi_2", "tau_4"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI_2 }) public static let pi_4 = Function(names: ["pi_4", "tau_8"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_PI_4 }) public static let tau = Function(names: ["tau", "τ"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return 2 * M_PI }) public static let sqrt2 = Function(name: "sqrt2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_SQRT2 }) public static let e = Function(name: "e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_E }) public static let log2e = Function(name: "log2e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LOG2E }) public static let log10e = Function(name: "log10e", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LOG10E }) public static let ln2 = Function(name: "ln2", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LN2 }) public static let ln10 = Function(name: "ln10", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 0 else { throw EvaluationError.InvalidArguments } return M_LN10 }) // MARK: - Logical Functions public static let l_and = Function(name: "l_and", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != 0 && arg2 != 0) ? 1.0 : 0.0 }) public static let l_or = Function(name: "l_or", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != 0 || arg2 != 0) ? 1.0 : 0.0 }) public static let l_not = Function(name: "l_not", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 1 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) return (arg1 == 0) ? 1.0 : 0.0 }) public static let l_eq = Function(name: "l_eq", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 == arg2) ? 1.0 : 0.0 }) public static let l_neq = Function(name: "l_neq", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 != arg2) ? 1.0 : 0.0 }) public static let l_lt = Function(name: "l_lt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 < arg2) ? 1.0 : 0.0 }) public static let l_gt = Function(name: "l_gt", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 > arg2) ? 1.0 : 0.0 }) public static let l_ltoe = Function(name: "l_ltoe", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 <= arg2) ? 1.0 : 0.0 }) public static let l_gtoe = Function(name: "l_gtoe", evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 2 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) let arg2 = try evaluator.evaluate(args[1], substitutions: substitutions) return (arg1 == arg2) ? 1.0 : 0.0 }) public static let l_if = Function(names: ["l_if", "if"], evaluator: { (args, substitutions, evaluator) throws -> Double in guard args.count == 3 else { throw EvaluationError.InvalidArguments } let arg1 = try evaluator.evaluate(args[0], substitutions: substitutions) if arg1 != 0 { return try evaluator.evaluate(args[1], substitutions: substitutions) } else { return try evaluator.evaluate(args[2], substitutions: substitutions) } }) }
mit
dd75cf097e6f14a44de7dc76d7d4d38b
45.43044
148
0.639725
4.549458
false
false
false
false
pcperini/Thrust
Thrust/Source/Range+ThrustExtensions.swift
1
2240
// // Range+ThrustExtensions.swift // Thrust // // Created by Patrick Perini on 9/13/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation extension Range { // MARK: Properties /// Returns an array containing each element in the range. var all: [T] { return self.map({ $0 }) } // MARK: Accessors /** Returns whether the given value is within the range. :param: element A value. :returns: True if the element is greater than or equal to the range's start index, and less than the range's end index; and false otherwise. */ func contains(element: T) -> Bool { return self.all.contains(element) } /** Returns an intersection of this range and the given range. :example: (0 ..< 10).intersection(5 ..< 15) == 5 ..< 10 :param: range A range to intersect with this range. :returns: An intersection of this range and the given range. */ func intersection<T: Comparable>(range: Range<T>) -> Range<T> { var maxStartIndex: T = max(self.startIndex as T, range.startIndex) as T var minEndIndex: T = min(self.endIndex as T, range.endIndex) as T return Range<T>(start: maxStartIndex, end: minEndIndex) } /** Returns whether the given range intersects this range. :param: range A range to intersect with this range. :returns: true, if the intersection of the ranges is not empty, false otherwise. */ func intersects<T: Comparable>(range: Range<T>) -> Bool { var intersection = self.intersection(range) return !intersection.isEmpty } /** Returns an union of this range and the given range. :example: (0 ..< 10).union(5 ..< 15) == 0 ..< 15 :param: range A range to union with this range. :returns: A union of this range and the given range. */ func union<T: Comparable>(range: Range<T>) -> Range<T> { var minStartIndex: T = min(self.startIndex as T, range.startIndex) as T var maxEndIndex: T = max(self.endIndex as T, range.endIndex) as T return Range<T>(start: minStartIndex, end: maxEndIndex) } }
mit
622e12b304abe5cf01810ea059ddcd3b
27.367089
144
0.613393
4.102564
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Sink.swift
6
1821
// // Sink.swift // RxSwift // // Created by Krunoslav Zaher on 2/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class Sink<Observer: ObserverType> : Disposable { fileprivate let _observer: Observer fileprivate let _cancel: Cancelable private let _disposed = AtomicInt(0) #if DEBUG private let _synchronizationTracker = SynchronizationTracker() #endif init(observer: Observer, cancel: Cancelable) { #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif self._observer = observer self._cancel = cancel } final func forwardOn(_ event: Event<Observer.Element>) { #if DEBUG self._synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self._synchronizationTracker.unregister() } #endif if isFlagSet(self._disposed, 1) { return } self._observer.on(event) } final func forwarder() -> SinkForward<Observer> { return SinkForward(forward: self) } final var disposed: Bool { return isFlagSet(self._disposed, 1) } func dispose() { fetchOr(self._disposed, 1) self._cancel.dispose() } deinit { #if TRACE_RESOURCES _ = Resources.decrementTotal() #endif } } final class SinkForward<Observer: ObserverType>: ObserverType { typealias Element = Observer.Element private let _forward: Sink<Observer> init(forward: Sink<Observer>) { self._forward = forward } final func on(_ event: Event<Element>) { switch event { case .next: self._forward._observer.on(event) case .error, .completed: self._forward._observer.on(event) self._forward._cancel.dispose() } } }
mit
2bab8677de8c8b5a07513134d6315634
23.266667
88
0.614286
4.385542
false
false
false
false
teaxus/TSAppEninge
StandardProject/StandardProject/AppDelegate.swift
1
3273
// // AppDelegate.swift // StandardProject // // Created by teaxus on 16/5/9. // Copyright © 2016年 teaxus. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. TSAppEngineInit()//初始化框架 SystemInfo.delegate = SystemDelegate() // 设置字体 字体颜色以及大小 UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:UIFont.systemFont(ofSize: 20.0)] self.window = UIWindow(frame: UIScreen.main.bounds) UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) self.window!.makeKeyAndVisible() UINavigationBar.appearance().shadowImage = UIImage.ImageWithColor(color: UIColor.clear) UINavigationBar.appearance().barStyle = .black /************** 引导页 或者进入登陆页*/ //读取上一次程序的登录状态 let login_status = SystemInfo.IsLogin SystemInfo.IsLogin = login_status //因为这个程序是使用游客模式 self.window?.rootViewController = StandardProjectTabBarViewController() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
4ed4aa23e8779b37003cf282bec3f2f8
48.46875
285
0.716045
5.623446
false
false
false
false
dmrschmidt/DSWaveformImage
Sources/DSWaveformImage/TempiFFT.swift
1
11959
// // TempiFFT.swift // TempiBeatDetection // // Created by John Scalo on 1/12/16. // Copyright © 2016 John Scalo. See accompanying License.txt for terms. /* A functional FFT built atop Apple's Accelerate framework for optimum performance on any device. In addition to simply performing the FFT and providing access to the resulting data, TempiFFT provides the ability to map the FFT spectrum data into logical bands, either linear or logarithmic, for further analysis. E.g. let fft = TempiFFT(withSize: frameSize, sampleRate: 44100) // Setting a window type reduces errors fft.windowType = TempiFFTWindowType.hanning // Perform the FFT fft.fftForward(samples) // Map FFT data to logical bands. This gives 4 bands per octave across 7 octaves = 28 bands. fft.calculateLogarithmicBands(minFrequency: 100, maxFrequency: 11025, bandsPerOctave: 4) // Process some data for i in 0..<fft.numberOfBands { let f = fft.frequencyAtBand(i) let m = fft.magnitudeAtBand(i) } Note that TempiFFT expects a mono signal (i.e. numChannels == 1) which is ideal for performance. */ import Foundation import Accelerate @objc enum TempiFFTWindowType: NSInteger { case none case hanning case hamming } @objc class TempiFFT : NSObject { /// The length of the sample buffer we'll be analyzing. private(set) var size: Int /// The sample rate provided at init time. private(set) var sampleRate: Float /// The Nyquist frequency is ```sampleRate``` / 2 var nyquistFrequency: Float { get { return sampleRate / 2.0 } } // After performing the FFT, contains size/2 magnitudes, one for each frequency band. private var magnitudes: [Float] = [] /// After calling calculateLinearBands() or calculateLogarithmicBands(), contains a magnitude for each band. private(set) var bandMagnitudes: [Float]! /// After calling calculateLinearBands() or calculateLogarithmicBands(), contains the average frequency for each band private(set) var bandFrequencies: [Float]! /// The average bandwidth throughout the spectrum (nyquist / magnitudes.count) var bandwidth: Float { get { return self.nyquistFrequency / Float(self.magnitudes.count) } } /// The number of calculated bands (must call calculateLinearBands() or calculateLogarithmicBands() first). private(set) var numberOfBands: Int = 0 /// The minimum and maximum frequencies in the calculated band spectrum (must call calculateLinearBands() or calculateLogarithmicBands() first). private(set) var bandMinFreq, bandMaxFreq: Float! /// Supplying a window type (hanning or hamming) smooths the edges of the incoming waveform and reduces output errors from the FFT function (aka "spectral leakage" - ewww). var windowType = TempiFFTWindowType.none private var halfSize:Int private var log2Size:Int private var window:[Float] = [] private var fftSetup:FFTSetup private var hasPerformedFFT: Bool = false private var complexBuffer: DSPSplitComplex! /// Instantiate the FFT. /// - Parameter withSize: The length of the sample buffer we'll be analyzing. Must be a power of 2. The resulting ```magnitudes``` are of length ```inSize/2```. /// - Parameter sampleRate: Sampling rate of the provided audio data. init(withSize inSize:Int, sampleRate inSampleRate: Float) { let sizeFloat: Float = Float(inSize) self.sampleRate = inSampleRate // Check if the size is a power of two let lg2 = logbf(sizeFloat) assert(remainderf(sizeFloat, powf(2.0, lg2)) == 0, "size must be a power of 2") self.size = inSize self.halfSize = inSize / 2 // create fft setup self.log2Size = Int(log2f(sizeFloat)) self.fftSetup = vDSP_create_fftsetup(UInt(log2Size), FFTRadix(FFT_RADIX2))! // Init the complexBuffer var real = [Float](repeating: 0.0, count: self.halfSize) var imaginary = [Float](repeating: 0.0, count: self.halfSize) super.init() real.withUnsafeMutableBufferPointer { realBP in imaginary.withUnsafeMutableBufferPointer { imaginaryBP in self.complexBuffer = DSPSplitComplex(realp: realBP.baseAddress!, imagp: imaginaryBP.baseAddress!) } } } deinit { // destroy the fft setup object vDSP_destroy_fftsetup(fftSetup) } /// Perform a forward FFT on the provided single-channel audio data. When complete, the instance can be queried for information about the analysis or the magnitudes can be accessed directly. /// - Parameter inMonoBuffer: Audio data in mono format func fftForward(_ inMonoBuffer:[Float]) { var analysisBuffer = inMonoBuffer // If we have a window, apply it now. Since 99.9% of the time the window array will be exactly the same, an optimization would be to create it once and cache it, possibly caching it by size. if self.windowType != .none { if self.window.isEmpty { self.window = [Float](repeating: 0.0, count: size) switch self.windowType { case .hamming: vDSP_hamm_window(&self.window, UInt(size), 0) case .hanning: vDSP_hann_window(&self.window, UInt(size), Int32(vDSP_HANN_NORM)) default: break } } // Apply the window vDSP_vmul(inMonoBuffer, 1, self.window, 1, &analysisBuffer, 1, UInt(inMonoBuffer.count)) } // vDSP_ctoz converts an interleaved vector into a complex split vector. i.e. moves the even indexed samples into frame.buffer.realp and the odd indexed samples into frame.buffer.imagp. // var imaginary = [Float](repeating: 0.0, count: analysisBuffer.count) // var splitComplex = DSPSplitComplex(realp: &analysisBuffer, imagp: &imaginary) // let length = vDSP_Length(self.log2Size) // vDSP_fft_zip(self.fftSetup, &splitComplex, 1, length, FFTDirection(FFT_FORWARD)) // Doing the job of vDSP_ctoz 😒. (See below.) var reals = [Float]() var imags = [Float]() for (idx, element) in analysisBuffer.enumerated() { if idx % 2 == 0 { reals.append(element) } else { imags.append(element) } } reals.withUnsafeMutableBufferPointer { realsBP in imags.withUnsafeMutableBufferPointer { imagsBP in self.complexBuffer = DSPSplitComplex(realp: realsBP.baseAddress!, imagp: imagsBP.baseAddress!) } } // This compiles without error but doesn't actually work. It results in garbage values being stored to the complexBuffer's real and imag parts. Why? The above workaround is undoubtedly tons slower so it would be good to get vDSP_ctoz working again. // withUnsafePointer(to: &analysisBuffer, { $0.withMemoryRebound(to: DSPComplex.self, capacity: analysisBuffer.count) { // vDSP_ctoz($0, 2, &(self.complexBuffer!), 1, UInt(self.halfSize)) // } // }) // Verifying garbage values. // let rFloats = [Float](UnsafeBufferPointer(start: self.complexBuffer.realp, count: self.halfSize)) // let iFloats = [Float](UnsafeBufferPointer(start: self.complexBuffer.imagp, count: self.halfSize)) // Perform a forward FFT vDSP_fft_zrip(self.fftSetup, &(self.complexBuffer!), 1, UInt(self.log2Size), Int32(FFT_FORWARD)) // Store and square (for better visualization & conversion to db) the magnitudes self.magnitudes = [Float](repeating: 0.0, count: self.halfSize) vDSP_zvmags(&(self.complexBuffer!), 1, &self.magnitudes, 1, UInt(self.halfSize)) self.hasPerformedFFT = true } /// Applies logical banding on top of the spectrum data. The bands are spaced linearly throughout the spectrum. func calculateLinearBands(minFrequency: Float, maxFrequency: Float, numberOfBands: Int) { assert(hasPerformedFFT, "*** Perform the FFT first.") let actualMaxFrequency = min(self.nyquistFrequency, maxFrequency) self.numberOfBands = numberOfBands self.bandMagnitudes = [Float](repeating: 0.0, count: numberOfBands) self.bandFrequencies = [Float](repeating: 0.0, count: numberOfBands) let magLowerRange = magIndexForFreq(minFrequency) let magUpperRange = magIndexForFreq(actualMaxFrequency) let ratio: Float = Float(magUpperRange - magLowerRange) / Float(numberOfBands) for i in 0..<numberOfBands { let magsStartIdx: Int = Int(floorf(Float(i) * ratio)) + magLowerRange let magsEndIdx: Int = Int(floorf(Float(i + 1) * ratio)) + magLowerRange var magsAvg: Float if magsEndIdx == magsStartIdx { // Can happen when numberOfBands < # of magnitudes. No need to average anything. magsAvg = self.magnitudes[magsStartIdx] } else { magsAvg = fastAverage(self.magnitudes, magsStartIdx, magsEndIdx) } self.bandMagnitudes[i] = magsAvg self.bandFrequencies[i] = self.averageFrequencyInRange(magsStartIdx, magsEndIdx) } self.bandMinFreq = self.bandFrequencies[0] self.bandMaxFreq = self.bandFrequencies.last } private func magIndexForFreq(_ freq: Float) -> Int { return Int(Float(self.magnitudes.count) * freq / self.nyquistFrequency) } // On arrays of 1024 elements, this is ~35x faster than an iterational algorithm. Thanks Accelerate.framework! @inline(__always) private func fastAverage(_ array:[Float], _ startIdx: Int, _ stopIdx: Int) -> Float { var mean: Float = 0 array.withUnsafeBufferPointer { arrayBP in vDSP_meanv(arrayBP.baseAddress! + startIdx, 1, &mean, UInt(stopIdx - startIdx)) } return mean } @inline(__always) private func averageFrequencyInRange(_ startIndex: Int, _ endIndex: Int) -> Float { return (self.bandwidth * Float(startIndex) + self.bandwidth * Float(endIndex)) / 2 } /// Get the magnitude for the specified frequency band. /// - Parameter inBand: The frequency band you want a magnitude for. func magnitudeAtBand(_ inBand: Int) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first") return bandMagnitudes[inBand] } /// Get the magnitude of the requested frequency in the spectrum. /// - Parameter inFrequency: The requested frequency. Must be less than the Nyquist frequency (```sampleRate/2```). /// - Returns: A magnitude. func magnitudeAtFrequency(_ inFrequency: Float) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") let index = Int(floorf(inFrequency / self.bandwidth )) return self.magnitudes[index] } /// Get the middle frequency of the Nth band. /// - Parameter inBand: An index where 0 <= inBand < size / 2. /// - Returns: The middle frequency of the provided band. func frequencyAtBand(_ inBand: Int) -> Float { assert(hasPerformedFFT, "*** Perform the FFT first.") assert(bandMagnitudes != nil, "*** Call calculateLinearBands() or calculateLogarithmicBands() first") return self.bandFrequencies[inBand] } /// A convenience function that converts a linear magnitude (like those stored in ```magnitudes```) to db (which is log 10). class func toDB(_ inMagnitude: Float) -> Float { // ceil to 128db in order to avoid log10'ing 0 let magnitude = max(inMagnitude, 0.000000000001) return 10 * log10f(magnitude) } }
mit
4e804851a5b3b1230c0262fe90b05409
42.003597
315
0.657884
4.437639
false
false
false
false
fgengine/quickly
Quickly/Views/Shape/QShapeView.swift
1
5210
// // Quickly // open class QShapeView : QView { public var model: Model? { didSet { if let model = self.model { if let fillColor = model.fillColor { self.shapeLayer.fillColor = fillColor.cgColor } else { self.shapeLayer.fillColor = nil } self.shapeLayer.fillRule = CAShapeLayerFillRule(rawValue: model.fillRule.string) if let strokeColor = model.strokeColor { self.shapeLayer.strokeColor = strokeColor.cgColor } else { self.shapeLayer.strokeColor = nil } self.shapeLayer.strokeStart = model.strokeStart self.shapeLayer.strokeEnd = model.strokeEnd self.shapeLayer.lineWidth = model.lineWidth self.shapeLayer.miterLimit = model.miterLimit self.shapeLayer.lineCap = CAShapeLayerLineCap(rawValue: model.lineCap.string) self.shapeLayer.lineJoin = CAShapeLayerLineJoin(rawValue: model.lineJoin.string) self.shapeLayer.lineDashPhase = model.lineDashPhase if let lineDashPattern = model.lineDashPattern { self.shapeLayer.lineDashPattern = lineDashPattern.compactMap({ (value: UInt) -> NSNumber? in return NSNumber(value: value) }) } else { self.shapeLayer.lineDashPattern = nil } } self.invalidateIntrinsicContentSize() self.setNeedsLayout() } } public var shapeLayer: CAShapeLayer { get { return self.layer as! CAShapeLayer } } open override class var layerClass: AnyClass { get { return CAShapeLayer.self } } open override var intrinsicContentSize: CGSize { get { return self.sizeThatFits(self.bounds.size) } } open override func sizeThatFits(_ size: CGSize) -> CGSize { guard let model = self.model else { return CGSize.zero } return model.size } open override func sizeToFit() { super.sizeToFit() self.frame.size = self.sizeThatFits(self.bounds.size) } open override func layoutSubviews() { if let model = self.model { if let path = model.prepare(self.bounds) { self.shapeLayer.path = path.cgPath } else { self.shapeLayer.path = nil } } else { self.shapeLayer.path = nil } } } extension QShapeView { public enum FillRule { case nonZero case evenOdd public var string: String { get { switch self { case .nonZero: return CAShapeLayerFillRule.nonZero.rawValue case .evenOdd: return CAShapeLayerFillRule.evenOdd.rawValue } } } } public enum LineCap { case butt case round case square public var string: String { get { switch self { case .butt: return CAShapeLayerLineCap.butt.rawValue case .round: return CAShapeLayerLineCap.round.rawValue case .square: return CAShapeLayerLineCap.square.rawValue } } } } public enum LineJoid { case miter case round case bevel public var string: String { get { switch self { case .miter: return CAShapeLayerLineJoin.miter.rawValue case .round: return CAShapeLayerLineJoin.round.rawValue case .bevel: return CAShapeLayerLineJoin.bevel.rawValue } } } } open class Model { open var fillColor: UIColor? open var fillRule: FillRule open var strokeColor: UIColor? open var strokeStart: CGFloat open var strokeEnd: CGFloat open var lineWidth: CGFloat open var miterLimit: CGFloat open var lineCap: LineCap open var lineJoin: LineJoid open var lineDashPhase: CGFloat open var lineDashPattern: [UInt]? open var size: CGSize public init(size: CGSize) { self.fillColor = nil self.fillRule = .nonZero self.strokeColor = nil self.strokeStart = 0 self.strokeEnd = 1 self.lineWidth = 1 self.miterLimit = 10 self.lineCap = .butt self.lineJoin = .miter self.lineDashPhase = 0 self.lineDashPattern = nil self.size = size } open func make() -> UIBezierPath? { return nil } open func prepare(_ bounds: CGRect) -> UIBezierPath? { guard let path = self.make() else { return nil } path.apply(CGAffineTransform(translationX: (bounds.width / 2), y: (bounds.height / 2))) return path } } }
mit
345d0c1389d2cff7d06278fbde61a693
30.011905
112
0.534165
5.62028
false
false
false
false
audiokit/AudioKit
Sources/AudioKit/Operations/Operation.swift
2
7620
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ /// A computed parameter differs from a regular parameter in that it only exists within an operation /// (unlike float, doubles, and ints which have a value outside of an operation) public protocol ComputedParameter: OperationParameter {} /// An Operation is a computed parameter that can be passed to other operations in the same operation node open class Operation: ComputedParameter { // MARK: - Dependency Management fileprivate var inputs = [OperationParameter]() internal var savedLocation = -1 fileprivate var dependencies = [Operation]() internal var recursiveDependencies: [Operation] { var all = [Operation]() var uniq = [Operation]() var added = Set<String>() for dep in dependencies { all += dep.recursiveDependencies all.append(dep) } for elem in all { if !added.contains(elem.inlineSporth) { uniq.append(elem) added.insert(elem.inlineSporth) } } return uniq } // MARK: - String Representations fileprivate var valueText = "" internal var setupSporth = "" fileprivate var module = "" internal var inlineSporth: String { if valueText != "" { return valueText } var opString = "" for input in inputs { if type(of: input) == Operation.self { if let operation = input as? Operation { if operation.savedLocation >= 0 { opString += "\(operation.savedLocation) \"ak\" tget " } else { opString += operation.inlineSporth } } } else { opString += "\(input) " } } opString += "\(module) " return opString } func getSetup() -> String { return setupSporth == "" ? "" : setupSporth + " " } /// Final sporth string when this operation is the last operation in the stack internal var sporth: String { let rd = recursiveDependencies var str = "" if rd.isNotEmpty { str = #""ak" ""# str += rd.compactMap { _ in "0" }.joined(separator: " ") str += #"" gen_vals "# var counter = 0 for op in rd { op.savedLocation = counter str += op.getSetup() str += op.inlineSporth + "\(op.savedLocation) \"ak\" tset " counter += 1 } } str += getSetup() str += inlineSporth return str } /// Redefining description to return the operation string open var description: String { return inlineSporth } // MARK: - Inputs /// Left input to any stereo operation public static var leftInput = Operation("(14 p) ") /// Right input to any stereo operation public static var rightInput = Operation("(15 p) ") /// Dummy trigger public static var trigger = Operation("(14 p) ") // MARK: - Functions /// An= array of 14 parameters which may be sent to operations public static var parameters: [Operation] = [Operation("(0 p) "), Operation("(1 p) "), Operation("(2 p) "), Operation("(3 p) "), Operation("(4 p) "), Operation("(5 p) "), Operation("(6 p) "), Operation("(7 p) "), Operation("(8 p) "), Operation("(9 p) "), Operation("(10 p) "), Operation("(11 p) "), Operation("(12 p) "), Operation("(13 p) ")] /// Convert the operation to a mono operation public func toMono() -> Operation { return self } /// Performs absolute value on the operation public func abs() -> Operation { return Operation(module: "abs", inputs: self) } /// Performs floor calculation on the operation public func floor() -> Operation { return Operation(module: "floor", inputs: self) } /// Returns the fractional part of the operation (as opposed to the integer part) public func fract() -> Operation { return Operation(module: "frac", inputs: self) } /// Performs natural logarithm on the operation public func log() -> Operation { return Operation(module: "log", inputs: self) } /// Performs Base 10 logarithm on the operation public func log10() -> Operation { return Operation(module: "log10", inputs: self) } /// Rounds the operation to the nearest integer public func round() -> Operation { return Operation(module: "round", inputs: self) } /// Returns a frequency for a given MIDI note number public func midiNoteToFrequency() -> Operation { return Operation(module: "mtof", inputs: self) } // MARK: - Initialization /// Initialize the operation as a constant value /// /// - parameter value: Constant value as an operation /// public init(_ value: Double) { self.valueText = "\(value)" } init(global: String) { self.valueText = global } /// Initialize the operation with a Sporth string /// /// - parameter operationString: Valid Sporth string (proceed with caution /// public init(_ operationString: String) { self.valueText = operationString //self.tableIndex = -1 //Operation.nextTableIndex //Operation.nextTableIndex += 1 //Operation.operationArray.append(self) } /// Initialize the operation /// /// - parameter module: Sporth unit generator /// - parameter setup: Any setup Sporth code that this operation may require /// - parameter inputs: All the parameters of the operation /// public init(module: String, setup: String = "", inputs: OperationParameter...) { self.module = module self.setupSporth = setup self.inputs = inputs for input in inputs { if type(of: input) == Operation.self { if let forcedInput = input as? Operation { dependencies.append(forcedInput) } } } } } // MARK: - Global Functions /// Performs absolute value on the operation /// /// - parameter parameter: ComputedParameter to operate on /// public func abs(_ parameter: Operation) -> Operation { return parameter.abs() } /// Performs floor calculation on the operation /// /// - parameter operation: ComputedParameter to operate on /// public func floor(_ operation: Operation) -> Operation { return operation.floor() } /// Returns the fractional part of the operation (as opposed to the integer part) /// /// - parameter operation: ComputedParameter to operate on /// public func fract(_ operation: Operation) -> Operation { return operation.fract() } /// Performs natural logarithm on the operation /// /// - parameter operation: ComputedParameter to operate on /// public func log(_ operation: Operation) -> Operation { return operation.log() } /// Performs Base 10 logarithm on the operation /// /// - parmeter operation: ComputedParameter to operate on /// public func log10(_ operation: Operation) -> Operation { return operation.log10() } /// Rounds the operation to the nearest integer /// /// - parameter operation: ComputedParameter to operate on /// public func round(_ operation: Operation) -> Operation { return operation.round() }
mit
9c2a641183f2c3db2fdd862553d633a4
28.083969
106
0.589633
4.847328
false
false
false
false
qvacua/vimr
NvimView/Support/MinimalNvimViewDemo/Document.swift
1
2116
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import NvimView import PureLayout import RxSwift class Document: NSDocument, NSWindowDelegate { private var nvimView = NvimView(forAutoLayout: ()) private let disposeBag = DisposeBag() override init() { super.init() self.nvimView.font = NSFont(name: "Fira Code", size: 13) ?? NSFont.userFixedPitchFont(ofSize: 13)! self.nvimView.usesLigatures = true self.nvimView.drawsParallel = true self.nvimView .events .observe(on: MainScheduler.instance) .subscribe(onNext: { event in switch event { case .neoVimStopped: self.close() default: break } }) .disposed(by: self.disposeBag) } func quitWithoutSaving() { try? self.nvimView.quitNeoVimWithoutSaving().wait() self.nvimView.waitTillNvimExits() } func windowShouldClose(_: NSWindow) -> Bool { self.quitWithoutSaving() return false } override func windowControllerDidLoadNib(_ windowController: NSWindowController) { super.windowControllerDidLoadNib(windowController) let window = windowController.window! window.delegate = self let view = window.contentView! let nvimView = self.nvimView // We know that we use custom tabs. let tabBar = nvimView.tabBar! view.addSubview(tabBar) view.addSubview(nvimView) tabBar.autoPinEdge(toSuperviewEdge: .left) tabBar.autoPinEdge(toSuperviewEdge: .top) tabBar.autoPinEdge(toSuperviewEdge: .right) nvimView.autoPinEdge(.top, to: .bottom, of: tabBar) nvimView.autoPinEdge(toSuperviewEdge: .left) nvimView.autoPinEdge(toSuperviewEdge: .right) nvimView.autoPinEdge(toSuperviewEdge: .bottom) } override var windowNibName: NSNib.Name? { NSNib.Name("Document") } override func data(ofType _: String) throws -> Data { throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } override func read(from _: Data, ofType _: String) throws { throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } }
mit
13d588396e53ac80cb3b1078f4c585da
25.78481
84
0.696125
4.408333
false
false
false
false
NoodleOfDeath/PastaParser
runtime/swift/GrammarKit/Classes/model/grammar/token/Grammar.Token.swift
1
4758
// // The MIT License (MIT) // // Copyright © 2020 NoodleOfDeath. All rights reserved. // NoodleOfDeath // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Grammar { /// Simple data structure representing a token read by a lexer grammatical scanner. open class Token: IO.Token { enum CodingKeys: String, CodingKey { case rules } // MARK: - CustomStringConvertible Properties override open var description: String { return String(format: "%@ (%d, %d)[%d]: \"%@\"", rules.keys.joined(separator: "/"), range.location, range.max, range.length, value) } open func descriptionWith(format: StringFormattingOption) -> String { return String(format: "%@ (%d, %d)[%d]: \"%@\" ", rules.keys.joined(separator: "/"), range.location, range.max, range.length, value.format(using: format)) } // MARK: - Instance Properties /// Rules associated with this token. open var rules = [String: GrammarRule]() // MARK: - Constructor Methods /// Constructs a new token instance with an initial rule, value, and range. /// /// - Parameters: /// - value: of the new token. /// - range: of the new token. /// - rules: of the new token. public init(value: String, range: NSRange, rules: [GrammarRule] = []) { super.init(value: value, range: range) add(rules: rules) } /// Constructs a new token instance with an initial rul, value, start, /// and length. /// /// Alias for `.init(rule: rule, value: value, /// range: NSMakeRange(start, length))` /// /// - Parameters: /// - rules: of the new token. /// - value: of the new token. /// - start: of the new token. /// - length: of the new token. public convenience init(value: String, start: Int, length: Int, rules: [GrammarRule] = []) { self.init(value: value, range: NSMakeRange(start, length), rules: rules) } // MARK: - Decodable Constructor Methods public required init(from decoder: Decoder) throws { try super.init(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) rules = try values.decode([String: GrammarRule].self, forKey: .rules) } // MARK: - Encodable Methods open func encode(with encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(rules, forKey: .rules) } // MARK: - Instance Methods open func add(rule: GrammarRule) { rules[rule.id] = rule } open func add(rules: [GrammarRule]) { rules.forEach({ add(rule: $0 )}) } open func matches(_ rule: GrammarRule) -> Bool { return matches(rule.id) } open func matches(_ id: String) -> Bool { return rules.keys.contains(id) } } } extension IO.TokenStream where Atom: Grammar.Token { open func reduce(over range: Range<Int>) -> String { return reduce(over: range, "", { (a, b) -> String in "\(a)\(b.value)" }) } open func reduce(over range: NSRange) -> String { return reduce(over: range.bridgedRange) } }
mit
fef6ac28ff174735641a728053b67493
33.471014
100
0.574942
4.618447
false
false
false
false
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Extensions/Integer.swift
1
2115
// // Integer.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 26/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import Foundation import UIKit extension Array { func randomValue() -> NSObject { let randomNum:UInt32 = arc4random_uniform(UInt32(self.count)) return self[Int(randomNum)] as! NSObject } } extension UIImageView { func downloadedFrom( actInd: UIActivityIndicatorView, url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { contentMode = mode actInd.startAnimating() URLSession.shared.dataTask(with: url) { (data, response, error) in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { return } DispatchQueue.main.async() { () -> Void in self.image = image actInd.stopAnimating() } }.resume() } func downloadedFrom( actInd: UIActivityIndicatorView, link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } downloadedFrom( actInd: actInd, url: url, contentMode: mode) } } extension String { func StringTimetoTime( )-> Date { let today = Date() let myCalendar = NSCalendar(calendarIdentifier: .gregorian)! var todayComponents = myCalendar.components([.year, .month, .day, .hour, .minute, .second], from: today) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let strDate = dateFormatter.date(from: self)! let strDateComp = myCalendar.components([.hour, .minute], from: strDate) todayComponents.hour = strDateComp.hour todayComponents.minute = strDateComp.minute return myCalendar.date(from: todayComponents)! } }
mit
b8aa2b66e48a59209f9812dc129f96ae
32.03125
129
0.62157
4.793651
false
false
false
false
rentpath/Atlas
AtlasTests/TestModels/User.swift
1
2242
// // User.swift // Atlas // // Created by Jeremy Fox on 3/30/16. // Copyright © 2016 RentPath. All rights reserved. // import Foundation import Atlas struct User { let firstName: String? let lastName: String? let email: String let phone: Int? let avatarURL: String? let isActive: Bool let memberSince: Date? let address: Address? let photos: [Photo]? let floorPlans: [FloorPlan]? } extension User: AtlasMap { func toJSON() -> JSON? { return nil } init?(json: JSON) throws { do { let map = try Atlas(json) firstName = try map.object(forOptional: "first_name") lastName = try map.object(forOptional: "last_name") email = try map.object(for: "email") phone = try map.object(forOptional: "phone") avatarURL = try map.object(forOptional: "avatar") isActive = try map.object(for: "is_active") memberSince = try map.date(for: "member_since", to: .rfc3339) address = try map.object(forOptional: "address") photos = try map.array(forOptional: "photos") floorPlans = try map.array(forOptional: "floorplans") } catch let error { throw error } } } ////////////////////////////////// struct UserNoKey { let firstName: String? let lastName: String? let email: String let phone: Int? let avatarURL: String? let isActive: Bool let memberSince: Date? } extension UserNoKey: AtlasMap { func toJSON() -> JSON? { return nil } init?(json: JSON) throws { do { let map = try Atlas(json) firstName = try map.object(forOptional: "first_name") lastName = try map.object(forOptional: "last_name") email = try map.object(for: "foo") // foo is not a valid key in user json, this is for a test phone = try map.object(forOptional: "phone") avatarURL = try map.object(forOptional: "avatar") isActive = try map.object(for: "is_active") memberSince = try map.date(for: "member_since", to: .rfc3339) } catch let error { throw error } } }
mit
dcf5435b6431903fbc03dd0e5d1691f7
24.179775
105
0.56805
3.973404
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/LocationPoints/HLLocationPoints.swift
1
5440
import CoreLocation class HLCityAndNearbyPoint: HDKLocationPoint { let city: HDKCity init(name: String, location: CLLocation, city: HDKCity) { self.city = city super.init(name: name, location: location, category: HDKLocationPointCategory.kCityCenter) } required init(from other: Any) { guard let other = other as? HLCityAndNearbyPoint else { fatalError() } city = other.city super.init(from: other) } required init?(coder aDecoder: NSCoder) { guard let city = aDecoder.decodeObject(forKey: "city") as? HDKCity else { return nil } self.city = city super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(city, forKey: "city") } override var actionCardDescription: String { return String(format: NSLS("HL_LOC_ACTION_CARD_DISTANCE_CITY_AND_NEARBY"), city.name ?? "") } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? HLCityAndNearbyPoint else { return false } if city != other.city { return false } return super.isEqual(object) } } class HLCustomLocationPoint: HDKLocationPoint { override init(name: String, location: CLLocation) { super.init(name: name, location: location, category: HDKLocationPointCategory.kCustomLocation) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_CUSTOM_SEARCH_POINT_TITLE") } } class HLUserLocationPoint: HDKLocationPoint { init(location: CLLocation) { super.init(name: NSLS("HL_LOC_FILTERS_POINT_MY_LOCATION_TEXT"), location: location, category: HDKLocationPointCategory.kUserLocation) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_USER_TITLE") } } class HLGenericCategoryLocationPoint: HDKLocationPoint { init(category: String) { super.init(name: HLGenericCategoryLocationPoint.name(for: category), location: CLLocation(latitude: 0, longitude: 0), category: category) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { switch category { case HDKLocationPointCategory.kBeach: return NSLS("HL_LOC_ACTION_CARD_DISTANCE_BEACH_TITLE") case HDKLocationPointCategory.kSkilift: return NSLS("HL_LOC_ACTION_CARD_DISTANCE_SKILIFT_TITLE") default: assertionFailure() return "" } } private static func name(for category: String) -> String { switch category { case HDKLocationPointCategory.kBeach: return NSLS("HL_LOC_FILTERS_POINT_ANY_BEACH_TEXT") case HDKLocationPointCategory.kSkilift: return NSLS("HL_LOC_FILTERS_POINT_ANY_SKILIFT_TEXT") case HDKLocationPointCategory.kMetroStation: return NSLS("HL_LOC_FILTERS_POINT_ANY_METRO_TEXT") default: return "" } } } @objcMembers class HLCityLocationPoint: HDKLocationPoint { let cityName: String? init(city: HDKCity) { let location = CLLocation(latitude: city.latitude, longitude: city.longitude) cityName = city.name super.init(name: NSLS("HL_LOC_FILTERS_POINT_CITY_CENTER_TEXT"), location: location, category: HDKLocationPointCategory.kCityCenter) } required init(from other: Any) { guard let other = other as? HLCityLocationPoint else { fatalError() } cityName = other.cityName super.init(from: other) } required init?(coder aDecoder: NSCoder) { cityName = aDecoder.decodeObject(forKey: "cityName") as? String super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(cityName, forKey: "cityName") } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_CENTER_TITLE") } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? HLCityLocationPoint else { return false } if cityName != other.cityName { return false } return super.isEqual(object) } } class HLAirportLocationPoint: HDKLocationPoint { override init(name: String, location: CLLocation) { super.init(name: name, location: location, category: HDKLocationPointCategory.kAirport) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return String(format: "%@%@", NSLS("HL_LOC_ACTION_CARD_DISTANCE_FROM_TITLE"), name) } }
mit
9c4c0a9f8978bf95083f7f201ed72388
28.726776
141
0.631434
4.419171
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/TransactionResponse/ViewModel/TransactionResponseViewData.swift
1
1731
import UIKit struct TransactionResponseViewData { var section : [TransactionResponseViewDataSection] } struct TransactionResponseViewDataSection { var title : String var item : [TransactionResponseViewDataItem] } struct TransactionResponseViewDataItem { var refID : String = "" var cellID : String = "" var title : String? var detail : String? var icon : UIImage? var accessory : UITableViewCellAccessoryType = .none var sizing : Sizing = .default enum Sizing { case auto, fixed, `default` var tableRowHeight: CGFloat { switch (self) { case .auto: return UITableViewAutomaticDimension case .fixed: return 36.0 case .default: return 55.0 } } } } extension TransactionResponseViewDataItem : ViewDataItem {} extension TransactionResponseViewData : Equatable {} func == (lhs: TransactionResponseViewData, rhs: TransactionResponseViewData) -> Bool { return (lhs.section == rhs.section) } extension TransactionResponseViewDataSection : Equatable {} func == (lhs: TransactionResponseViewDataSection, rhs: TransactionResponseViewDataSection) -> Bool { return (lhs.title == rhs.title && lhs.item == rhs.item) } extension TransactionResponseViewDataItem : Equatable {} func == (lhs: TransactionResponseViewDataItem, rhs: TransactionResponseViewDataItem) -> Bool { return (lhs.refID == rhs.refID && lhs.cellID == rhs.cellID && lhs.title == rhs.title && lhs.detail == rhs.detail) } protocol TransactionResponseViewDataItemConfigurable : class { func configure(transactionResponseViewDataItem item: TransactionResponseViewDataItem) }
apache-2.0
2ffc9a767711a1685834aa62d44f915a
29.368421
100
0.690352
5.076246
false
false
false
false
tardieu/swift
benchmark/single-source/StrComplexWalk.swift
10
1870
//===--- StrComplexWalk.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils @inline(never) public func run_StrComplexWalk(_ N: Int) { var s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्" let ref_result = 379 for _ in 1...2000*N { var count = 0 for _ in s.unicodeScalars { count += 1 } CheckResults(count == ref_result, "Incorrect results in StrComplexWalk: \(count) != \(ref_result)") } }
apache-2.0
f6c69c6811eb838f4990a532ba84fe84
44.185185
391
0.572131
2.067797
false
false
false
false
boluomeng/Charts
ChartsDemo-OSX/ChartsDemo-OSX/Demos/BarDemoViewController.swift
1
2281
// // BarDemoViewController.swift // ChartsDemo-OSX // // 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 Cocoa import Charts open class BarDemoViewController: NSViewController { @IBOutlet var barChartView: BarChartView! override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let xs = Array(1..<10).map { return Double($0) } let ys1 = xs.map { i in return sin(Double(i / 2.0 / 3.141 * 1.5)) } let ys2 = xs.map { i in return cos(Double(i / 2.0 / 3.141)) } let yse1 = ys1.enumerated().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let yse2 = ys2.enumerated().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let data = BarChartData(xVals: xs as [NSObject]) let ds1 = BarChartDataSet(yVals: yse1, label: "Hello") ds1.colors = [NSUIColor.red] data.addDataSet(ds1) let ds2 = BarChartDataSet(yVals: yse2, label: "World") ds2.colors = [NSUIColor.blue] data.addDataSet(ds2) self.barChartView.data = data self.barChartView.gridBackgroundColor = NSUIColor.white self.barChartView.descriptionText = "Barchart Demo" } @IBAction func save(_ sender: AnyObject) { let panel = NSSavePanel() panel.allowedFileTypes = ["png"] panel.beginSheetModal(for: self.view.window!) { (result) -> Void in if result == NSFileHandlingPanelOKButton { if let path = panel.url?.path { do { _ = try self.barChartView.saveToPath(path, format: .png, compressionQuality: 1.0) } catch { print("Saving encounter errors") } } } } } override open func viewWillAppear() { self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) } }
apache-2.0
45ccc647311594b5bac25e105e27279c
30.680556
105
0.558965
4.455078
false
false
false
false
michaelgwelch/pandemic
Pandemic/GameBoardCity.swift
1
5516
// // GameBoardCity.swift // Pandemic // // Created by Michael Welch on 3/11/16. // Copyright © 2016 Michael Welch. All rights reserved. // import Foundation public class GameBoardCityFactory { public let algiers = { () in GameBoardCity(city: City.algiers) } public let atlanta = { () in GameBoardCity(city: City.atlanta) } public let baghdad = { () in GameBoardCity(city: City.baghdad) } public let bangkok = { () in GameBoardCity(city: City.bangkok) } public let beijing = { () in GameBoardCity(city: City.beijing) } public let bogotá = { () in GameBoardCity(city: City.bogotá) } public let buenosaires = { () in GameBoardCity(city: City.buenosaires) } public let cairo = { () in GameBoardCity(city: City.cairo) } public let chennai = { () in GameBoardCity(city: City.chennai) } public let chicago = { () in GameBoardCity(city: City.chicago) } public let delhi = { () in GameBoardCity(city: City.delhi) } public let essen = { () in GameBoardCity(city: City.essen) } public let hochiminhcity = { () in GameBoardCity(city: City.hochiminhcity) } public let hongkong = { () in GameBoardCity(city: City.hongkong) } public let istanbul = { () in GameBoardCity(city: City.istanbul) } public let jakarta = { () in GameBoardCity(city: City.jakarta) } public let johannesburg = { () in GameBoardCity(city: City.johannesburg) } public let karachi = { () in GameBoardCity(city: City.karachi) } public let khartoum = { () in GameBoardCity(city: City.khartoum) } public let kinshasa = { () in GameBoardCity(city: City.kinshasa) } public let kolkata = { () in GameBoardCity(city: City.kolkata) } public let lagos = { () in GameBoardCity(city: City.lagos) } public let lima = { () in GameBoardCity(city: City.lima) } public let london = { () in GameBoardCity(city: City.london) } public let losangeles = { () in GameBoardCity(city: City.losangeles) } public let madrid = { () in GameBoardCity(city: City.madrid) } public let manila = { () in GameBoardCity(city: City.manila) } public let mexicocity = { () in GameBoardCity(city: City.mexicocity) } public let miami = { () in GameBoardCity(city: City.miami) } public let milan = { () in GameBoardCity(city: City.milan) } public let montreal = { () in GameBoardCity(city: City.montreal) } public let moscow = { () in GameBoardCity(city: City.moscow) } public let mumbai = { () in GameBoardCity(city: City.mumbai) } public let newyork = { () in GameBoardCity(city: City.newyork) } public let osaka = { () in GameBoardCity(city: City.osaka) } public let paris = { () in GameBoardCity(city: City.paris) } public let riyadh = { () in GameBoardCity(city: City.riyadh) } public let sanfrancisco = { () in GameBoardCity(city: City.sanfrancisco) } public let santiago = { () in GameBoardCity(city: City.santiago) } public let sãopaulo = { () in GameBoardCity(city: City.sãopaulo) } public let seoul = { () in GameBoardCity(city: City.seoul) } public let shanghai = { () in GameBoardCity(city: City.shanghai) } public let stpetersburg = { () in GameBoardCity(city: City.stpetersburg) } public let sydney = { () in GameBoardCity(city: City.sydney) } public let taipei = { () in GameBoardCity(city: City.taipei) } public let tehran = { () in GameBoardCity(city: City.tehran) } public let tokyo = { () in GameBoardCity(city: City.tokyo) } public let washington = { () in GameBoardCity(city: City.washington) } } public class GameBoardCity : Equatable { private let city:City let counters:[Color:DiseaseCounter] convenience init(city:City) { self.init(city:city, initialCount:0) } init(city:City, initialCount:Int) { self.city = city var counters = [Color:DiseaseCounter]() counters[.Red] = DiseaseCounter() counters[.Yellow] = DiseaseCounter() counters[.Black] = DiseaseCounter() counters[.Blue] = DiseaseCounter() let counter = DiseaseCounter(initialValue: initialCount) switch city.color { case .Yellow: counters[.Yellow] = counter case .Red: counters[.Red] = counter case .Blue: counters[.Blue] = counter case .Black: counters[.Black] = counter } self.counters = counters } func infect() { counters[city.color]!.increment() } func isOutbreakingInColor(color:Color) -> Bool { return counters[color]!.error } func diseaseCountForColor(color:Color) -> Int { return counters[color]!.value } func treatColor(color:Color) { counters[color]!.decrement() } func treatAllColor(color:Color) { counters[color]!.reset() } /** Clears the outbreak flag. */ func clearOutbreak() { Color.colors.forEach { counters[$0]!.clearError() } } class func outbreakingCity(city:City) -> GameBoardCity { let city = GameBoardCity(city: city, initialCount: 3) city.infect() return city } } extension GameBoardCity : CustomStringConvertible { public var description:String { return self.city.name } } extension GameBoardCity : CityInfo { public var name:String { return city.name } public var color:Color { return city.color } } public func ==(lhs:GameBoardCity, rhs:GameBoardCity) -> Bool { return lhs === rhs }
mit
c973d2846abeae011bd219f9de37fa58
35.746667
80
0.643622
3.738806
false
false
false
false
JiriTrecak/Warp
Source/WRPExtensions.swift
3
7495
// // WRPExtensions.swift // // Copyright (c) 2016 Jiri Trecak (http://jiritrecak.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Imports import Foundation // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extension - NSDictionary extension NSMutableDictionary { /** * Set an object for the property identified by a given key path to a given value. * * @param object The object for the property identified by _keyPath_. * @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.” */ func setObject(_ object : AnyObject!, forKeyPath : String) { self.setObject(object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true); } /** * Set an object for the property identified by a given key path to a given value, with optional parameters to control creation and replacement of intermediate objects. * * @param object The object for the property identified by _keyPath_. * @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.” * @param createIntermediates Intermediate dictionaries defined within the key path that do not currently exist in the receiver are created. * @param replaceIntermediates Intermediate objects encountered in the key path that are not a direct subclass of `NSDictionary` are replaced. */ func setObject(_ object : AnyObject, onObject : AnyObject, forKeyPath : String, createIntermediates: Bool, replaceIntermediates: Bool) { // Path delimiter = . let pathDelimiter : String = "." // There is no keypath, just assign object if forKeyPath.range(of: pathDelimiter) == nil { onObject.set(object, forKey: forKeyPath); } // Create path components separated by delimiter (. by default) and get key for root object let pathComponents : Array<String> = forKeyPath.components(separatedBy: pathDelimiter); let rootKey : String = pathComponents[0]; let replacementDictionary : NSMutableDictionary = NSMutableDictionary(); // Store current state for further replacement var previousObject : AnyObject? = onObject; var previousReplacement : NSMutableDictionary = replacementDictionary; var reachedDictionaryLeaf : Bool = false; // Traverse through path from root to deepest level for path : String in pathComponents { let currentObject : AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.object(forKey: path) as AnyObject?; // Check if object already exists. If not, create new level, if allowed, or end if currentObject == nil { reachedDictionaryLeaf = true; if createIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary(); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; } else { return; } // If it does and it is dictionary, create mutable copy and assign new node there } else if currentObject is NSDictionary { let newNode : NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [AnyHashable: Any]); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; // It exists but it is not NSDictionary, so we replace it, if allowed, or end } else { reachedDictionaryLeaf = true; if replaceIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary(); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; } else { return; } } // Replace previous object with the new one previousObject = currentObject; } // Replace root object with newly created n-level dictionary replacementDictionary.setValue(object, forKeyPath: forKeyPath); onObject.set(replacementDictionary.object(forKey: rootKey), forKey: rootKey); } } extension NSRange { init(location:Int, length:Int) { self.location = location self.length = length } init(_ location:Int, _ length:Int) { self.location = location self.length = length } init(range:Range <Int>) { self.location = range.lowerBound self.length = range.upperBound - range.lowerBound } init(_ range:Range <Int>) { self.location = range.lowerBound self.length = range.upperBound - range.lowerBound } var startIndex:Int { get { return location } } var endIndex:Int { get { return location + length } } var asRange:CountableRange<Int> { get { return location..<location + length } } var isEmpty:Bool { get { return length == 0 } } func contains(_ index:Int) -> Bool { return index >= location && index < endIndex } func clamp(_ index:Int) -> Int { return max(self.startIndex, min(self.endIndex - 1, index)) } func intersects(_ range:NSRange) -> Bool { return NSIntersectionRange(self, range).isEmpty == false } func intersection(_ range:NSRange) -> NSRange { return NSIntersectionRange(self, range) } func union(_ range:NSRange) -> NSRange { return NSUnionRange(self, range) } }
mit
cdb1d9f082bc51513b8f7dab4b2199b7
37.158163
182
0.600615
5.376707
false
false
false
false
tinrobots/Mechanica
Sources/UIKit/UIImage+Utils.swift
1
11026
#if canImport(UIKit) && (os(iOS) || os(tvOS) || watchOS) import UIKit extension UIImage { /// **Mechanica** /// /// Returns an image with a background `color`, `size` and `scale`. /// - Parameters: /// - color: The background UIColor. /// - size: The image size (default is 1x1). /// - scaleFactor: The scale factor to apply; if you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen. /// - Note: The size of the rectangle is beeing rounded from UIKit. public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1), scale scaleFactor: CGFloat = 0.0) { let rect = CGRect(origin: .zero, size: size) let format = UIGraphicsImageRendererFormat() format.scale = scaleFactor let renderer = UIGraphicsImageRenderer(size: size, format: format) let image = renderer.image { (context) in color.setFill() context.fill(rect) } guard let cgImage = image.cgImage else { return nil } self.init(cgImage: cgImage) /// left only for reference /* UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } color.setFill() UIRectFill(rect) guard let cgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: cgImage) */ } } // MARK: - Scaling extension UIImage { /// **Mechanica** /// /// Returns a new version of the image scaled to the specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scale scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - Returns: A `new` scaled UIImage. /// - Note: The opaqueness is the same of the initial images. public func scaled(to size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { return scaled(to: size, opaque: isOpaque, scale: scale) } /// **Mechanica** /// /// Returns a new version of the image scaled to the specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scale scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// - opaque: Specifying `false` means that the image will include an alpha channel. /// /// - Returns: A `new` scaled UIImage. public func scaled(to size: CGSize, opaque: Bool = false, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "An image with zero width or height cannot be scaled properly.") UIGraphicsBeginImageContextWithOptions(size, opaque, scaleFactor) draw(in: CGRect(origin: .zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// **Mechanica** /// /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - Returns: A new image object. public func aspectScaled(toFit size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) let format = UIGraphicsImageRendererFormat() format.scale = scaleFactor let renderer = UIGraphicsImageRenderer(size: size, format: format) let scaledImage = renderer.image { _ in draw(in: CGRect(origin: origin, size: scaledSize)) } return scaledImage } /// **Mechanica** /// /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func aspectScaled(toFill size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "An image with zero width or height cannot be scaled properly.") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, isOpaque, scaleFactor) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounding extension UIImage { /// **Mechanica** /// /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// - parameter scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func rounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false, scale scaleFactor: CGFloat = 0.0) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scaleFactor) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// **Mechanica** /// /// Returns a new version of the image rounded into a circle. /// /// - parameter scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func roundedIntoCircle(scale scaleFactor: CGFloat = 0.0) -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = aspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, scaleFactor) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// **Mechanica** /// /// Returns a new decoded version of the image. /// /// It allows a bitmap representation to be decoded in the background rather than on the main thread. /// /// - Parameters: /// - scale: The scale factor to assume when interpreting the image data (defaults to `self.scale`); the decoded image will have its size divided by this scale parameter. /// - allowedMaxSize: The allowed max size, if the image is too large the decoding operation will return nil. /// - returns: A new decoded `UIImage` object. public func decoded(scale: CGFloat? = .none, allowedMaxSize: Int = 4096 * 4096) -> UIImage? { // Do not attempt to render animated images guard images == nil else { return nil } // Do not attempt to render if not backed by a CGImage guard let image = cgImage?.copy() else { return nil } let width = image.width let height = image.height let bitsPerComponent = image.bitsPerComponent // Do not attempt to render if too large or has more than 8-bit components guard width * height <= allowedMaxSize && bitsPerComponent <= 8 else { return nil } //TODO: remove this condition? let bytesPerRow: Int = 0 let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo = image.bitmapInfo // Fix alpha channel issues if necessary let alpha = (bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { bitmapInfo.remove(.alphaInfoMask) bitmapInfo = CGBitmapInfo(rawValue: bitmapInfo.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { bitmapInfo.remove(.alphaInfoMask) bitmapInfo = CGBitmapInfo(rawValue: bitmapInfo.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } // Render the image let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue ) context?.draw(image, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height))) // Make sure the inflation was successful guard let renderedImage = context?.makeImage() else { return nil } let imageScale = scale ?? self.scale return UIImage(cgImage: renderedImage, scale: imageScale, orientation: imageOrientation) } } #endif
mit
51c3720d9ecbfaf5c05da992123ca193
37.954064
174
0.67988
4.59142
false
false
false
false
imchenglibin/XTPopupView
XTPopupView/Window.swift
1
702
// // Window.swift // XTPopupView // // Created by imchenlibin on 16/1/29. // Copyright © 2016年 xt. All rights reserved. // import UIKit public class Window: UIWindow { public static let sharedWindow:Window = { let window = Window(frame: UIScreen.mainScreen().bounds) window.rootViewController = UIViewController() window.rootViewController!.view.backgroundColor = UIColor(white: 0.5, alpha: 0.5) window.hidden = true window.windowLevel = UIWindowLevelStatusBar + 1 window.makeKeyAndVisible() return window }() public func mainView() -> UIView { return Window.sharedWindow.rootViewController!.view; } }
mit
c1550669647a84b788a67e5996a08787
25.884615
89
0.658083
4.36875
false
false
false
false
Palleas/Batman
Batman/Domain/ProjectsController.swift
1
2226
import Foundation import Result import ReactiveSwift import Unbox final class ProjectsController { enum ProjectsError: Error, AutoEquatable { case noCache case fetchingError(Client.ClientError) } private let client: Client let selectedProject = MutableProperty<Project?>(nil) private let projectsPath: URL init(client: Client, cacheDirectory: URL) { self.client = client self.projectsPath = cacheDirectory.appendingPathComponent("projects.json") } typealias Projects = SignalProducer<[Project], ProjectsError> func fetch() -> Projects { return fetchFromCache().flatMapError { error in guard error == ProjectsError.noCache else { return SignalProducer(error: error) } return self.fetchFromRemote() } } func fetchFromCache() -> Projects { return SignalProducer<Data, ProjectsError> { sink, _ in guard FileManager.default.fileExists(atPath: self.projectsPath.path) else { sink.send(error: .noCache) return } do { // TODO: Expiration date sink.send(value: try Data(contentsOf: self.projectsPath)) sink.sendCompleted() } catch { sink.send(error: .noCache) } } .attemptMap { return decodeArray(from: $0).mapError { _ in ProjectsError.noCache } } } func fetchFromRemote() -> Projects { return self.client.projects() .mapError(ProjectsError.fetchingError) .flatMap(.latest, self.save) } func save(projects: [Project]) -> SignalProducer<[Project], NoError> { return SignalProducer { sink, _ in defer { // Sending projects anyway sink.send(value: projects) sink.sendCompleted() } do { let encoded = try projects.encode() try encoded.write(to: self.projectsPath) print("Cached to \(self.projectsPath)") } catch { print("Unable to cache projects") } } } }
mit
3e0625549606a2ef05eee8f6e4497d51
27.909091
96
0.566936
5.262411
false
false
false
false
thdtjsdn/realm-cocoa
RealmSwift-swift2.0/Tests/ObjectTests.swift
4
12871
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift import Foundation class ObjectTests: TestCase { // init() Tests are in ObjectCreationTests.swift // init(value:) tests are in ObjectCreationTests.swift func testRealm() { let standalone = SwiftStringObject() XCTAssertNil(standalone.realm) let realm = try! Realm() var persisted: SwiftStringObject! realm.write { persisted = realm.create(SwiftStringObject.self, value: [:]) XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) } XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) dispatchSyncNewThread { autoreleasepool { XCTAssertNotEqual(try! Realm(), persisted.realm!) } } } func testObjectSchema() { let object = SwiftObject() let schema = object.objectSchema XCTAssert(schema as AnyObject is ObjectSchema) XCTAssert(schema.properties as AnyObject is [Property]) XCTAssertEqual(schema.className, "SwiftObject") XCTAssertEqual(schema.properties.map { $0.name }, ["boolCol", "intCol", "floatCol", "doubleCol", "stringCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]) } func testInvalidated() { let object = SwiftObject() XCTAssertFalse(object.invalidated) let realm = try! Realm() realm.write { realm.add(object) XCTAssertFalse(object.invalidated) } realm.write { realm.deleteAll() XCTAssertTrue(object.invalidated) } XCTAssertTrue(object.invalidated) } func testDescription() { let object = SwiftObject() XCTAssertEqual(object.description, "SwiftObject {\n\tboolCol = 0;\n\tintCol = 123;\n\tfloatCol = 1.23;\n\tdoubleCol = 12.3;\n\tstringCol = a;\n\tbinaryCol = <61 — 1 total bytes>;\n\tdateCol = 1970-01-01 00:00:01 +0000;\n\tobjectCol = SwiftBoolObject {\n\t\tboolCol = 0;\n\t};\n\tarrayCol = List<SwiftBoolObject> (\n\t\n\t);\n}") let recursiveObject = SwiftRecursiveObject() recursiveObject.objects.append(recursiveObject) XCTAssertEqual(recursiveObject.description, "SwiftRecursiveObject {\n\tobjects = List<SwiftRecursiveObject> (\n\t\t[0] SwiftRecursiveObject {\n\t\t\tobjects = List<SwiftRecursiveObject> (\n\t\t\t\t[0] SwiftRecursiveObject {\n\t\t\t\t\tobjects = <Maximum depth exceeded>;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}") } func testPrimaryKey() { XCTAssertNil(Object.primaryKey(), "primary key should default to nil") XCTAssertNil(SwiftStringObject.primaryKey()) XCTAssertNil(SwiftStringObject().objectSchema.primaryKeyProperty) XCTAssertEqual(SwiftPrimaryStringObject.primaryKey()!, "stringCol") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { XCTAssertEqual(Object.ignoredProperties(), [], "ignored properties should default to []") XCTAssertEqual(SwiftIgnoredPropertiesObject.ignoredProperties().count, 2) XCTAssertNil(SwiftIgnoredPropertiesObject().objectSchema["runtimeProperty"]) } func testIndexedProperties() { XCTAssertEqual(Object.indexedProperties(), [], "indexed properties should default to []") XCTAssertEqual(SwiftIndexedPropertiesObject.indexedProperties().count, 1) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.indexed) } func testLinkingObjects() { let realm = try! Realm() let object = SwiftEmployeeObject() assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees")) realm.write { realm.add(object) self.assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "noSuchCol")) XCTAssertEqual(0, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) for _ in 0..<10 { realm.create(SwiftCompanyObject.self, value: [[object]]) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } func testValueForKey() { let test: (SwiftObject) -> () = { object in XCTAssertEqual(object.valueForKey("boolCol") as! Bool!, false) XCTAssertEqual(object.valueForKey("intCol") as! Int!, 123) XCTAssertEqual(object.valueForKey("floatCol") as! Float!, 1.23 as Float) XCTAssertEqual(object.valueForKey("doubleCol") as! Double!, 12.3) XCTAssertEqual(object.valueForKey("stringCol") as! String!, "a") XCTAssertEqual(object.valueForKey("binaryCol") as! NSData, "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) XCTAssertEqual(object.valueForKey("dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 1)) XCTAssertEqual((object.valueForKey("objectCol")! as! SwiftBoolObject).boolCol, false) XCTAssert(object.valueForKey("arrayCol")! is List<SwiftBoolObject>) } test(SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) test(persistedObject) } } func setAndTestAllTypes(setter: (SwiftObject, AnyObject?, String) -> (), getter: (SwiftObject, String) -> (AnyObject?), object: SwiftObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool!, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int!, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float!, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double!, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String!, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 333)) let boolObject = SwiftBoolObject(value: [true]) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! SwiftBoolObject, boolObject) XCTAssertEqual((getter(object, "objectCol")! as! SwiftBoolObject).boolCol, true) let list = List<SwiftBoolObject>() list.append(boolObject) setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) } func dynamicSetAndTestAllTypes(setter: (DynamicObject, AnyObject?, String) -> (), getter: (DynamicObject, String) -> (AnyObject?), object: DynamicObject, boolObject: DynamicObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate, NSDate(timeIntervalSince1970: 333)) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! DynamicObject, boolObject) XCTAssertEqual((getter(object, "objectCol") as! DynamicObject)["boolCol"] as! NSNumber, true as NSNumber) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) let list = getter(object, "arrayCol") as! List<DynamicObject> list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) } /// Yields a read-write migration `SwiftObject` to the given block private func withMigrationObject(block: ((MigrationObject, Migration) -> ())) { autoreleasepool { let realm = self.realmWithTestPath() realm.write { _ = realm.create(SwiftObject) } } autoreleasepool { var enumerated = false setSchemaVersion(1, realmPath: self.testRealmPath()) { migration, _ in migration.enumerate(SwiftObject.className()) { oldObject, newObject in if let newObject = newObject { block(newObject, migration) enumerated = true } } } self.realmWithTestPath() XCTAssert(enumerated) } } func testSetValueForKey() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object.setValue(value, forKey: key) return } let getter : (Object, String) -> (AnyObject?) = { object, key in object.valueForKey(key) } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } func testSubscript() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object[key] = value return } let getter : (Object, String) -> (AnyObject?) = { object, key in object[key] } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } }
apache-2.0
c1589ce737c253dc0eb3ba499105b047
43.839721
336
0.641075
4.796496
false
true
false
false
xsunsmile/zentivity
zentivity/AppDelegate.swift
1
5413
// // AppDelegate.swift // zentivity // // Created by Andrew Wen on 3/5/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard = UIStoryboard(name: "Main", bundle: nil) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Parse setup User.registerSubclass() Photo.registerSubclass() Event.registerSubclass() Comment.registerSubclass() Parse.setApplicationId("LEwfLcFvUwXtT8A7y2dJMlHL7FLiEybY8x5kOaZP", clientKey: "YRAwfZdssZrBJtNGqE0wIEyiAaBoARiCih5hrNau") NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleGoogleLogin:", name: "userDidLoginNotification", object: nil) return true } func loginToParseWithUserInfo(userInfo: NSDictionary) { let email = userInfo["email"] as! String let name = userInfo["name"] as! String let image = userInfo["imageUrl"] as! String let aboutMe = userInfo["aboutMe"] as! String PFCloud.callFunctionInBackground("getUserSessionToken", withParameters: ["username" : email]) { (sessionToken, error) -> Void in if let sessionToken = sessionToken as? String { PFUser.becomeInBackground(sessionToken, block: { (user, error) -> Void in if error == nil { // Found user with sessionToken println("Logged in user with session token") User.currentUser()!.name = name User.currentUser()!.imageUrl = image User.currentUser()!.aboutMe = aboutMe User.currentUser()!.saveInBackgroundWithBlock({ (success, error) -> Void in // Nothing now }) self.showEventsVC() } else { // Could not find user with sessionToken // SUPER FAIL! println("SUPER FAIL!") } }) } else { // Could not find user email var user = User() user.username = email user.password = "1" user.name = name user.imageUrl = image user.aboutMe = aboutMe ParseClient.setUpUserWithCompletion(user, completion: { (user, error) -> () in if error == nil { // User signed up/logged in // Set up some views.. self.showEventsVC() } else { // User failed to sign up and log in println("Failed to sign up and log in user") println(error) } }) } } } func handleGoogleLogin(notification: NSNotification) { loginToParseWithUserInfo(notification.userInfo!) } func showEventsVC() { let scence = "MenuViewController" let vc = storyboard.instantiateViewControllerWithIdentifier(scence) as! UIViewController window?.rootViewController = vc } 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 { println("redirect to url: \(url)") return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation: annotation) } }
apache-2.0
c9154c8786cbfe91508087e66dce9df5
45.264957
285
0.614631
5.563207
false
false
false
false
ShenghaiWang/FolioReaderKit
Source/EPUBCore/FRSpine.swift
3
973
// // FRSpine.swift // FolioReaderKit // // Created by Heberti Almeida on 06/05/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit struct Spine { var linear: Bool! var resource: FRResource! init(resource: FRResource, linear: Bool = true) { self.resource = resource self.linear = linear } } class FRSpine: NSObject { var pageProgressionDirection: String? var spineReferences = [Spine]() var isRtl: Bool { if let pageProgressionDirection = pageProgressionDirection , pageProgressionDirection == "rtl" { return true } return false } func nextChapter(_ href: String) -> FRResource? { var found = false; for item in spineReferences { if(found){ return item.resource } if(item.resource.href == href) { found = true } } return nil } }
bsd-3-clause
f73939e1dd53ea7406676c8ceff4ad1a
20.622222
104
0.568345
4.363229
false
false
false
false
bannzai/xcp
xcp/XCP/XCProject.swift
1
11595
// // // XCProject.swift // xcp // // Created by kingkong999yhirose on 2016/09/20. // Copyright © 2016年 kingkong999yhirose. All rights reserved. // import Foundation open class XCProject { public typealias JSON = [String: Any] public typealias KeyAndValue = [(key: String, value: Any)] open let projectName: String open let fullJson: JSON open let allPBX = AllPBX() open let project: PBX.Project open let pbxUrl: URL open fileprivate(set) var environments: [String: String] = [:] public init(for pbxUrl: URL) throws { guard let propertyList = try? Data(contentsOf: pbxUrl) else { throw XCProjectError.notExistsProjectFile } var format: PropertyListSerialization.PropertyListFormat = PropertyListSerialization.PropertyListFormat.binary let properties = try PropertyListSerialization.propertyList(from: propertyList, options: PropertyListSerialization.MutabilityOptions(), format: &format) guard let json = properties as? JSON else { throw XCProjectError.wrongFormatFile } func generateObjects(with objectsJson: [String: JSON], allPBX: AllPBX) -> [PBX.Object] { return objectsJson .flatMap { (hashId, objectDictionary) in guard let isa = objectDictionary["isa"] as? String else { fatalError( assertionMessage(description: "not exists isa key: \(hashId), value: \(objectDictionary)", "you should check for project.pbxproj that is correct." ) ) } let pbxType = ObjectType.type(with: isa) let pbxObject = pbxType.init( id: hashId, dictionary: objectDictionary, isa: isa, allPBX: allPBX ) allPBX.dictionary[hashId] = pbxObject return pbxObject } } func generateProject(with objectsJson: [String: JSON], allPBX: AllPBX) -> PBX.Project { guard let id = json["rootObject"] as? String, let projectJson = objectsJson[id] else { fatalError( assertionMessage(description: "unexpected for json: \(json)", "and objectsJson: \(objectsJson)" ) ) } return PBX.Project( id: id, dictionary: projectJson, isa: ObjectType.PBXProject.rawValue, allPBX: allPBX ) } self.pbxUrl = pbxUrl guard let projectName = pbxUrl.pathComponents[pbxUrl.pathComponents.count - 2].components(separatedBy: ".").first else { fatalError("No Xcode project found, please specify one") } self.projectName = projectName fullJson = json let objectsJson = json["objects"] as! [String: JSON] generateObjects(with: objectsJson, allPBX: allPBX) project = generateProject(with: objectsJson, allPBX: allPBX) allPBX.createFullFilePaths(with: project) } // MARK: - enviroment open func append(with enviroment: [String: String]) { environments += enviroment } open func isExists(for environment: Environment) -> Bool { return environments[environment.rawValue] != nil } fileprivate func environment(for key: String) -> Environment { guard let value = environments[key], let environment = Environment(rawValue: value) else { fatalError( assertionMessage(description: "unknown key: \(key)", "process environments: \(environments)" ) ) } return environment } fileprivate func url(from environment: Environment) -> URL { guard let path = environments[environment.rawValue] else { fatalError(assertionMessage(description: "can not cast environment: \(environment)")) } return URL(fileURLWithPath: path) } open func path(from component: PathComponent) -> URL { switch component { case .simple(let fullPath): return URL(fileURLWithPath: fullPath) case .environmentPath(let environtment, let relativePath): let _url = url(from: environtment) .appendingPathComponent(relativePath) return _url } } } extension XCProject { private func generateHashId() -> String { let all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".characters.map { String($0) } var result: String = "" for _ in 0..<24 { result += all[Int(arc4random_uniform(UInt32(all.count)))] } return result } public func appendFilePath( with projectRootPath: String, filePath: String, targetName: String ) { let pathComponents = filePath.components(separatedBy: "/").filter { !$0.isEmpty } let groupPathNames = Array(pathComponents.dropLast()) guard let fileName = pathComponents.last else { fatalError(assertionMessage(description: "unexpected get file name for append")) } let fileRefId = generateHashId() let fileRef: PBX.FileReference do { // file ref let isa = ObjectType.PBXFileReference.rawValue let json: XCProject.JSON = [ "isa": isa, "fileEncoding": 4, "lastKnownFileType": LastKnownFileType(fileName: fileName).value, "path": fileName, "sourceTree": "<group>" ] fileRef = PBX.FileReference( id: fileRefId, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[fileRefId] = fileRef } do { // groups allPBX.createFullFilePaths(with: project) let groupEachPaths = allPBX .dictionary .values .flatMap { $0 as? PBX.Group } .flatMap { group -> (PBX.Group, String) in let path = (projectRootPath + group.fullPath) .components(separatedBy: "/") .filter { !$0.isEmpty } .joined(separator: "/") return (group, path) } func appendGroupIfNeeded(with childId: String, groupPathNames: [String]) { if groupPathNames.isEmpty { return } let groupPath = groupPathNames.joined(separator: "/") let alreadyExistsGroup = groupEachPaths .filter { (group, path) -> Bool in return path == groupPath } .first if let group = alreadyExistsGroup?.0 { let reference: PBX.Reference = allPBX.dictionary[childId] as! PBX.Reference group.children.append(reference) return } else { guard let pathName = groupPathNames.last else { fatalError("unexpected not exists last value") } let isa = ObjectType.PBXGroup.rawValue let json: XCProject.JSON = [ "isa": isa, "children": [ childId ], "path": pathName, "sourceTree": "<group>" ] let uuid = generateHashId() let group = PBX.Group( id: uuid, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[uuid] = group appendGroupIfNeeded(with: uuid, groupPathNames: Array(groupPathNames.dropLast())) } } appendGroupIfNeeded(with: fileRefId, groupPathNames: groupPathNames) } let buildFileId = generateHashId() func buildFile() -> PBX.BuildFile { // build file let isa = ObjectType.PBXBuildFile.rawValue let json: XCProject.JSON = [ "isa": isa, "fileRef": fileRefId, ] let buildFile = PBX.BuildFile( id: buildFileId, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[buildFileId] = buildFile return buildFile } let buildedFile = buildFile() let sourceBuildPhaseId = generateHashId() func sourceBuildPhase() { // source build phase guard let target = allPBX .dictionary .values .flatMap ({ $0 as? PBX.NativeTarget }) .filter ({ $0.name == targetName }) .first else { fatalError(assertionMessage(description: "Unexpected target name \(targetName)")) } let sourcesBuildPhase = target.buildPhases.flatMap { $0 as? PBX.SourcesBuildPhase }.first guard sourcesBuildPhase == nil else { // already exists sourcesBuildPhase?.files.append(buildedFile) return } let isa = ObjectType.PBXSourcesBuildPhase.rawValue let json: XCProject.JSON = [ "isa": isa, "buildActionMask": Int32.max, "files": [ buildFileId ], "runOnlyForDeploymentPostprocessing": 0 ] allPBX.dictionary[sourceBuildPhaseId] = PBX.SourcesBuildPhase( id: sourceBuildPhaseId, dictionary: json, isa: isa, allPBX: allPBX ) } sourceBuildPhase() } } extension XCProject { func write() throws { let serialization = XCPSerialization(project: self) let writeContent = try serialization.generateWriteContent() func w(with code: String, fileURL: URL) throws { try code.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } let writeUrl = pbxUrl try w(with: writeContent, fileURL: writeUrl) } }
mit
1fa468515a8bafad4d526510e718c17e
34.021148
160
0.485248
5.914286
false
false
false
false
yrchen/edx-app-ios
Source/ProfileImageView.swift
1
2611
// // ProfileImageView.swift // edX // // Created by Michael Katz on 9/17/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit @IBDesignable class ProfileImageView: UIImageView { var borderWidth: CGFloat = 1.0 var borderColor: UIColor? private func setup() { var borderStyle = OEXStyles.sharedStyles().profileImageViewBorder(borderWidth) if borderColor != nil { borderStyle = BorderStyle(cornerRadius: borderStyle.cornerRadius, width: borderStyle.width, color: borderColor) } applyBorderStyle(borderStyle) backgroundColor = OEXStyles.sharedStyles().profileImageBorderColor() } convenience init() { self.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init (frame: CGRect) { super.init(frame: frame) let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "avatarPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) setup() } override func layoutSubviews() { super.layoutSubviews() setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "avatarPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } func blurimate() -> Removable { let blur = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: blur) let vib = UIVibrancyEffect(forBlurEffect: blur) let vibView = UIVisualEffectView(effect: vib) let spinner = SpinnerView(size: .Medium, color: .White) vibView.contentView.addSubview(spinner) spinner.snp_makeConstraints {make in make.center.equalTo(spinner.superview!) } spinner.startAnimating() insertSubview(blurView, atIndex: 0) blurView.contentView.addSubview(vibView) vibView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(vibView.superview!) } blurView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self) } return BlockRemovable() { UIView.animateWithDuration(0.4, animations: { spinner.stopAnimating() }) { _ in blurView.removeFromSuperview() } } } }
apache-2.0
a4161ddc14795a99079be0db0ae74091
29.717647
123
0.622367
5.129666
false
false
false
false
rdm0423/Hydrate
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
3
95620
// // IQKeyboardManager.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-15 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics import UIKit ///--------------------- /// MARK: IQToolbar tags ///--------------------- /** Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html */ public class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate { /** Default tag for toolbar with Done button -1002. */ private static let kIQDoneButtonToolbarTag = -1002 /** Default tag for toolbar with Previous/Next buttons -1005. */ private static let kIQPreviousNextButtonToolbarTag = -1005 ///--------------------------- /// MARK: UIKeyboard handling ///--------------------------- /** Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method). */ public var enable = false { didSet { //If not enable, enable it. if enable == true && oldValue == false { //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. if _kbShowNotification != nil { keyboardWillShow(_kbShowNotification) } _IQShowLog("enabled") } else if enable == false && oldValue == true { //If not disable, desable it. keyboardWillHide(nil) _IQShowLog("disabled") } } } /** To set keyboard distance from textField. can't be less than zero. Default is 10.0. */ public var keyboardDistanceFromTextField: CGFloat { set { _privateKeyboardDistanceFromTextField = max(0, newValue) _IQShowLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)") } get { return _privateKeyboardDistanceFromTextField } } /** Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */ public var preventShowingBottomBlankSpace = true /** Returns the default singleton instance. */ public class func sharedManager() -> IQKeyboardManager { struct Static { //Singleton instance. Initializing keyboard manger. static let kbManager = IQKeyboardManager() } /** @return Returns the default singleton instance. */ return Static.kbManager } ///------------------------- /// MARK: IQToolbar handling ///------------------------- /** Automatic add the IQToolbar functionality. Default is YES. */ public var enableAutoToolbar = true { didSet { enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired() let enableToolbar = enableAutoToolbar ? "Yes" : "NO" _IQShowLog("enableAutoToolbar: \(enableToolbar)") } } /** AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */ public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews /** If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */ public var shouldToolbarUsesTextFieldTintColor = false /** If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */ public var shouldShowTextFieldPlaceholder = true /** Placeholder Font. Default is nil. */ public var placeholderFont: UIFont? ///-------------------------- /// MARK: UITextView handling ///-------------------------- /** Adjust textView's frame when it is too big in height. Default is NO. */ public var canAdjustTextView = false /** Adjust textView's contentInset to fix a bug. for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string Default is YES. */ public var shouldFixTextViewClip = true ///--------------------------------------- /// MARK: UIKeyboard appearance overriding ///--------------------------------------- /** Override the keyboardAppearance for all textField/textView. Default is NO. */ public var overrideKeyboardAppearance = false /** If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */ public var keyboardAppearance = UIKeyboardAppearance.Default ///----------------------------------------------------------- /// MARK: UITextField/UITextView Next/Previous/Resign handling ///----------------------------------------------------------- /** Resigns Keyboard on touching outside of UITextField/View. Default is NO. */ public var shouldResignOnTouchOutside = false { didSet { _tapGesture.enabled = shouldResignOnTouchOutside let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO" _IQShowLog("shouldResignOnTouchOutside: \(shouldResign)") } } /** Resigns currently first responder field. */ public func resignFirstResponder()-> Bool { if let textFieldRetain = _textFieldView { //Resigning first responder let isResignFirstResponder = textFieldRetain.resignFirstResponder() // If it refuses then becoming it as first responder again. (Bug ID: #96) if isResignFirstResponder == false { //If it refuses to resign then becoming it first responder again for getting notifications callback. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())") } return isResignFirstResponder } return false } /** Returns YES if can navigate to previous responder textField/textView, otherwise NO. */ public var canGoPrevious: Bool { get { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index > 0 { return true } } } } return false } } /** Returns YES if can navigate to next responder textField/textView, otherwise NO. */ public var canGoNext: Bool { get { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index < textFields.count-1 { return true } } } } return false } } /** Navigate to previous responder textField/textView. */ public func goPrevious()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object becomeFirstResponder. if index > 0 { let nextTextField = textFields[index-1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** Navigate to next responder textField/textView. */ public func goNext()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not last textField. then it's next object becomeFirstResponder. if index < textFields.count-1 { let nextTextField = textFields[index+1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** previousAction. */ internal func previousAction (segmentedControl : AnyObject?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if canGoPrevious == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goPrevious() if isAcceptAsFirstResponder && textFieldRetain.previousInvocation.target != nil && textFieldRetain.previousInvocation.selector != nil { UIApplication.sharedApplication().sendAction(textFieldRetain.previousInvocation.selector!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } } /** nextAction. */ internal func nextAction (segmentedControl : AnyObject?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if canGoNext == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goNext() if isAcceptAsFirstResponder && textFieldRetain.nextInvocation.target != nil && textFieldRetain.nextInvocation.selector != nil { UIApplication.sharedApplication().sendAction(textFieldRetain.nextInvocation.selector!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } } /** doneAction. Resigning current textField. */ internal func doneAction (barButton : IQBarButtonItem?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if let textFieldRetain = _textFieldView { //Resign textFieldView. let isResignedFirstResponder = resignFirstResponder() if isResignedFirstResponder && textFieldRetain.doneInvocation.target != nil && textFieldRetain.doneInvocation.selector != nil{ UIApplication.sharedApplication().sendAction(textFieldRetain.doneInvocation.selector!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } /** Resigning on tap gesture. (Enhancement ID: #14)*/ internal func tapRecognized(gesture: UITapGestureRecognizer) { if gesture.state == UIGestureRecognizerState.Ended { //Resigning currently responder textField. resignFirstResponder() } } /** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */ public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */ public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145) return (touch.view is UIControl || touch.view is UINavigationBar) ? false : true } ///---------------------------- /// MARK: UIScrollView handling ///---------------------------- /** Restore scrollViewContentOffset when resigning from scrollView. Default is NO. */ public var shouldRestoreScrollViewContentOffset = false ///----------------------- /// MARK: UISound handling ///----------------------- /** If YES, then it plays inputClick sound on next/previous/done click. */ public var shouldPlayInputClicks = false ///--------------------------- /// MARK: UIAnimation handling ///--------------------------- /** If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES. @warning Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently. */ public var shouldAdoptDefaultKeyboardAnimation = true /** If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view. */ public var layoutIfNeededOnUpdate = false ///------------------------------------ /// MARK: Class Level disabling methods ///------------------------------------ /** Disable adjusting view in disabledClass @param disabledClass Class in which library should not adjust view to show textField. */ public func disableInViewControllerClass(disabledClass : AnyClass) { _disabledClasses.insert(NSStringFromClass(disabledClass)) } /** Re-enable adjusting textField in disabledClass @param disabledClass Class in which library should re-enable adjust view to show textField. */ public func removeDisableInViewControllerClass(disabledClass : AnyClass) { _disabledClasses.remove(NSStringFromClass(disabledClass)) } /** Returns YES if ViewController class is disabled for library, otherwise returns NO. @param disabledClass Class which is to check for it's disability. */ public func isDisableInViewControllerClass(disabledClass : AnyClass) -> Bool { return _disabledClasses.contains(NSStringFromClass(disabledClass)) } /** Disable automatic toolbar creation in in toolbarDisabledClass @param toolbarDisabledClass Class in which library should not add toolbar over textField. */ public func disableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) { _disabledToolbarClasses.insert(NSStringFromClass(toolbarDisabledClass)) } /** Re-enable automatic toolbar creation in in toolbarDisabledClass @param toolbarDisabledClass Class in which library should re-enable automatic toolbar creation over textField. */ public func removeDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) { _disabledToolbarClasses.remove(NSStringFromClass(toolbarDisabledClass)) } /** Returns YES if toolbar is disabled in ViewController class, otherwise returns NO. @param toolbarDisabledClass Class which is to check for toolbar disability. */ public func isDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) -> Bool { return _disabledToolbarClasses.contains(NSStringFromClass(toolbarDisabledClass)) } /** Consider provided customView class as superView of all inner textField for calculating next/previous button logic. @param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should consider all inner textField as siblings and add next/previous accordingly. */ public func considerToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) { _toolbarPreviousNextConsideredClass.insert(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /** Remove Consideration for provided customView class as superView of all inner textField for calculating next/previous button logic. @param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should remove consideration for all inner textField as superView. */ public func removeConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) { _toolbarPreviousNextConsideredClass.remove(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /** Returns YES if inner hierarchy is considered for previous/next in class, otherwise returns NO. @param toolbarPreviousNextConsideredClass Class which is to check for previous next consideration */ public func isConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) -> Bool { return _toolbarPreviousNextConsideredClass.contains(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /**************************************************************************************/ ///------------------------ /// MARK: Private variables ///------------------------ /*******************************************/ /** To save UITextField/UITextView object voa textField/textView notifications. */ private weak var _textFieldView: UIView? /** used with canAdjustTextView boolean. */ private var _textFieldViewIntialFrame = CGRectZero /** To save rootViewController.view.frame. */ private var _topViewBeginRect = CGRectZero /** To save rootViewController */ private weak var _rootViewController: UIViewController? /** To save topBottomLayoutConstraint original constant */ private var _layoutGuideConstraintInitialConstant: CGFloat = 0.25 /*******************************************/ /** Variable to save lastScrollView that was scrolled. */ private weak var _lastScrollView: UIScrollView? /** LastScrollView's initial contentOffset. */ private var _startingContentOffset = CGPointZero /** LastScrollView's initial scrollIndicatorInsets. */ private var _startingScrollIndicatorInsets = UIEdgeInsetsZero /** LastScrollView's initial contentInsets. */ private var _startingContentInsets = UIEdgeInsetsZero /*******************************************/ /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ private var _kbShowNotification: NSNotification? /** To save keyboard size. */ private var _kbSize = CGSizeZero /** To save keyboard animation duration. */ private var _animationDuration = 0.25 /** To mimic the keyboard animation */ private var _animationCurve = UIViewAnimationOptions.CurveEaseOut /*******************************************/ /** TapGesture to resign keyboard on view's touch. */ private var _tapGesture: UITapGestureRecognizer! /*******************************************/ /** Default toolbar tintColor to be used within the project. Default is black. */ private var _defaultToolbarTintColor = UIColor.blackColor() /*******************************************/ /** Set of restricted classes for library */ private var _disabledClasses = Set<String>() /** Set of restricted classes for adding toolbar */ private var _disabledToolbarClasses = Set<String>() /** Set of permitted classes to add all inner textField as siblings */ private var _toolbarPreviousNextConsideredClass = Set<String>() /*******************************************/ private struct flags { /** used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/ var isTextFieldViewFrameChanged = false /** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */ var isKeyboardShowing = false } /** Private flags to use within the project */ private var _keyboardManagerFlags = flags(isTextFieldViewFrameChanged: false, isKeyboardShowing: false) /** To use with keyboardDistanceFromTextField. */ private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0 /**************************************************************************************/ ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- /* Singleton Object Initialization. */ override init() { super.init() // Registering for keyboard notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil) // Registering for textField notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil) // Registering for textView notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil) // Registering for orientation changes notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil) //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) _tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:") _tapGesture.delegate = self _tapGesture.enabled = shouldResignOnTouchOutside disableInViewControllerClass(UITableViewController) considerToolbarPreviousNextInViewClass(UITableView) considerToolbarPreviousNextInViewClass(UICollectionView) } /** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */ /** It doesn't work on Swift 1.2 */ // override class func load() { // super.load() // // //Enabling IQKeyboardManager. // IQKeyboardManager.sharedManager().enable = true // } deinit { // Disable the keyboard manager. enable = false //Removing notification observers on dealloc. NSNotificationCenter.defaultCenter().removeObserver(self) } /** Getting keyWindow. */ private func keyWindow() -> UIWindow? { if let keyWindow = _textFieldView?.window { return keyWindow } else { struct Static { /** @abstract Save keyWindow object for reuse. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */ static var keyWindow : UIWindow? } /* (Bug ID: #23, #25, #73) */ let originalKeyWindow = UIApplication.sharedApplication().keyWindow //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) { Static.keyWindow = originalKeyWindow } //Return KeyWindow return Static.keyWindow } } ///----------------------- /// MARK: Helper Functions ///----------------------- /* Helper function to manipulate RootViewController's frame with animation. */ private func setRootViewFrame(var frame: CGRect) { // Getting topMost ViewController. var controller = _textFieldView?.topMostController() if controller == nil { controller = keyWindow()?.topMostController() } if let unwrappedController = controller { //frame size needs to be adjusted on iOS8 due to orientation structure changes. if #available(iOS 8.0, *) { frame.size = unwrappedController.view.frame.size } //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in // Setting it's new frame unwrappedController.view.frame = frame self._IQShowLog("Set \(controller?._IQDescription()) frame to : \(frame)") //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) unwrappedController.view.setNeedsLayout() unwrappedController.view.layoutIfNeeded() } }) { (animated:Bool) -> Void in} } else { // If can't get rootViewController then printing warning to user. _IQShowLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager") } } /* Adjusting RootViewController's frame according to interface orientation. */ private func adjustFrame() { // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) if _textFieldView == nil { return } let textFieldView = _textFieldView! _IQShowLog("****** \(__FUNCTION__) %@ started ******") // Boolean to know keyboard is showing/hiding _keyboardManagerFlags.isKeyboardShowing = true // Getting KeyWindow object. let optionalWindow = keyWindow() // Getting RootViewController. (Bug ID: #1, #4) var optionalRootController = _textFieldView?.topMostController() if optionalRootController == nil { optionalRootController = keyWindow()?.topMostController() } // Converting Rectangle according to window bounds. let optionalTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: optionalWindow) if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil { return } let rootController = optionalRootController! let window = optionalWindow! let textFieldViewRect = optionalTextFieldViewRect! //If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66) let interfaceOrientation : UIInterfaceOrientation if #available(iOS 8.0, *) { interfaceOrientation = UIInterfaceOrientation.Portrait } else { interfaceOrientation = rootController.interfaceOrientation } // Getting RootViewRect. var rootViewRect = rootController.view.frame //Getting statusBarFrame var topLayoutGuide : CGFloat = 0 //Maintain keyboardDistanceFromTextField let newKeyboardDistanceFromTextField = (textFieldView.keyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : textFieldView.keyboardDistanceFromTextField var kbSize = _kbSize let statusBarFrame = UIApplication.sharedApplication().statusBarFrame // (Bug ID: #250) var layoutGuidePosition = IQLayoutGuidePosition.None if let viewController = textFieldView.viewController() { if let constraint = viewController.IQLayoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint { layoutGuidePosition = .Top } else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint { layoutGuidePosition = .Bottom } } } } switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: topLayoutGuide = CGRectGetWidth(statusBarFrame) kbSize.width += newKeyboardDistanceFromTextField case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: topLayoutGuide = CGRectGetHeight(statusBarFrame) kbSize.height += newKeyboardDistanceFromTextField default: break } var move : CGFloat = 0.0 // Move positive = textField is hidden. // Move negative = textField is showing. // Checking if there is bottomLayoutGuide attached (Bug ID: #250) if layoutGuidePosition == .Bottom { // Calculating move position. switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: move = CGRectGetMaxX(textFieldViewRect)-(CGRectGetWidth(window.frame)-kbSize.width) case UIInterfaceOrientation.LandscapeRight: move = kbSize.width-CGRectGetMinX(textFieldViewRect) case UIInterfaceOrientation.Portrait: move = CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height) case UIInterfaceOrientation.PortraitUpsideDown: move = kbSize.height-CGRectGetMinY(textFieldViewRect) default: break } } else { // Calculating move position. Common for both normal and special cases. switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: move = min(CGRectGetMinX(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxX(textFieldViewRect)-(CGRectGetWidth(window.frame)-kbSize.width)) case UIInterfaceOrientation.LandscapeRight: move = min(CGRectGetWidth(window.frame)-CGRectGetMaxX(textFieldViewRect)-(topLayoutGuide+5), kbSize.width-CGRectGetMinX(textFieldViewRect)) case UIInterfaceOrientation.Portrait: move = min(CGRectGetMinY(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height)) case UIInterfaceOrientation.PortraitUpsideDown: move = min(CGRectGetHeight(window.frame)-CGRectGetMaxY(textFieldViewRect)-(topLayoutGuide+5), kbSize.height-CGRectGetMinY(textFieldViewRect)) default: break } } _IQShowLog("Need to move: \(move)") // Getting it's superScrollView. // (Enhancement ID: #21, #24) let superScrollView = textFieldView.superviewOfClassType(UIScrollView) as? UIScrollView //If there was a lastScrollView. // (Bug ID: #34) if let lastScrollView = _lastScrollView { //If we can't find current superScrollView, then setting lastScrollView to it's original form. if superScrollView == nil { _IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _startingContentInsets = UIEdgeInsetsZero _startingScrollIndicatorInsets = UIEdgeInsetsZero _startingContentOffset = CGPointZero _lastScrollView = nil } else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. _IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _lastScrollView = superScrollView _startingContentInsets = superScrollView!.contentInset _startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets _startingContentOffset = superScrollView!.contentOffset _IQShowLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead } else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. _lastScrollView = unwrappedSuperScrollView _startingContentInsets = unwrappedSuperScrollView.contentInset _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets _startingContentOffset = unwrappedSuperScrollView.contentOffset _IQShowLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } // Special case for ScrollView. // If we found lastScrollView then setting it's contentOffset to show textField. if let lastScrollView = _lastScrollView { //Saving var lastView = textFieldView var superScrollView = _lastScrollView while let scrollView = superScrollView { //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 { //Getting lastViewRect. if let lastViewRect = lastView.superview?.convertRect(lastView.frame, toView: scrollView) { //Calculating the expected Y offset from move and scrollView's contentOffset. var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move) //Rearranging the expected Y offset according to the view. shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92) if textFieldView is UITextView == true && scrollView.superviewOfClassType(UIScrollView) == nil && shouldOffsetY >= 0 { var maintainTopLayout : CGFloat = 0 if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame { maintainTopLayout = CGRectGetMaxY(navigationBarFrame) } maintainTopLayout += 10.0 //For good UI // Converting Rectangle according to window bounds. if let currentTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: window) { var expectedFixDistance = shouldOffsetY //Calculating expected fix distance which needs to be managed from navigation bar switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: expectedFixDistance = CGRectGetMinX(currentTextFieldViewRect) - maintainTopLayout case UIInterfaceOrientation.LandscapeRight: expectedFixDistance = (CGRectGetWidth(window.frame)-CGRectGetMaxX(currentTextFieldViewRect)) - maintainTopLayout case UIInterfaceOrientation.Portrait: expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - maintainTopLayout case UIInterfaceOrientation.PortraitUpsideDown: expectedFixDistance = (CGRectGetHeight(window.frame)-CGRectGetMaxY(currentTextFieldViewRect)) - maintainTopLayout default: break } //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance) //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic. move = 0 } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self._IQShowLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset") self._IQShowLog("Remaining Move: \(move)") scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, shouldOffsetY) }) { (animated:Bool) -> Void in } } // Getting next lastView & superScrollView. lastView = scrollView superScrollView = lastView.superviewOfClassType(UIScrollView) as? UIScrollView } else { break } } //Updating contentInset if let lastScrollViewRect = lastScrollView.superview?.convertRect(lastScrollView.frame, toView: window) { var bottom : CGFloat = 0.0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: bottom = kbSize.width-(CGRectGetWidth(window.frame)-CGRectGetMaxX(lastScrollViewRect)) case UIInterfaceOrientation.LandscapeRight: bottom = kbSize.width-CGRectGetMinX(lastScrollViewRect) case UIInterfaceOrientation.Portrait: bottom = kbSize.height-(CGRectGetHeight(window.frame)-CGRectGetMaxY(lastScrollViewRect)) case UIInterfaceOrientation.PortraitUpsideDown: bottom = kbSize.height-CGRectGetMinY(lastScrollViewRect) default: break } // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view. var movedInsets = lastScrollView.contentInset movedInsets.bottom = max(_startingContentInsets.bottom, bottom) _IQShowLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)") //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = movedInsets var newInset = lastScrollView.scrollIndicatorInsets newInset.bottom = movedInsets.bottom - 10 lastScrollView.scrollIndicatorInsets = newInset }) { (animated:Bool) -> Void in } //Maintaining contentSize if lastScrollView.contentSize.height < lastScrollView.frame.size.height { var contentSize = lastScrollView.contentSize contentSize.height = lastScrollView.frame.size.height lastScrollView.contentSize = contentSize } _IQShowLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)") } } //Going ahead. No else if. if layoutGuidePosition == .Top { let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint! let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move) UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } else if layoutGuidePosition == .Bottom { let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint! let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move) UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } else { //Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen) //_canAdjustTextView If we have permission to adjust the textView, then let's do it on behalf of user (Enhancement ID: #15) //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //_isTextFieldViewFrameChanged If frame is not change by library in past (Bug ID: #92) if canAdjustTextView == true && _lastScrollView == nil && textFieldView is UITextView == true && _keyboardManagerFlags.isTextFieldViewFrameChanged == false { var textViewHeight = CGRectGetHeight(textFieldView.frame) switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: textViewHeight = min(textViewHeight, (CGRectGetWidth(window.frame)-kbSize.width-(topLayoutGuide+5))) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: textViewHeight = min(textViewHeight, (CGRectGetHeight(window.frame)-kbSize.height-(topLayoutGuide+5))) default: break } UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in self._IQShowLog("\(textFieldView._IQDescription()) Old Frame : \(textFieldView.frame)") var textFieldViewRect = textFieldView.frame textFieldViewRect.size.height = textViewHeight textFieldView.frame = textFieldViewRect self._keyboardManagerFlags.isTextFieldViewFrameChanged = true self._IQShowLog("\(textFieldView._IQDescription()) New Frame : \(textFieldView.frame)") }, completion: { (finished) -> Void in }) } // Special case for iPad modalPresentationStyle. if rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet { _IQShowLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)") // +Positive or zero. if move >= 0 { // We should only manipulate y. rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { var minimumY: CGFloat = 0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: minimumY = CGRectGetWidth(window.frame)-rootViewRect.size.height-topLayoutGuide-(kbSize.width-newKeyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: minimumY = (CGRectGetHeight(window.frame)-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField) default: break } rootViewRect.origin.y = max(CGRectGetMinY(rootViewRect), minimumY) } _IQShowLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } else { // -Negative // Calculating disturbed distance. Pull Request #3 let disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect) // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { // We should only manipulate y. rootViewRect.origin.y -= max(move, disturbDistance) _IQShowLog("Moving Downward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } } } else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case) // +Positive or zero. if move >= 0 { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= move case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += move case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= move case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += move default: break } // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x = max(rootViewRect.origin.x, min(0, -kbSize.width+newKeyboardDistanceFromTextField)) case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x = min(rootViewRect.origin.x, +kbSize.width-newKeyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait: rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField)) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y = min(rootViewRect.origin.y, +kbSize.height-newKeyboardDistanceFromTextField) default: break } } _IQShowLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } else { // -Negative var disturbDistance : CGFloat = 0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: disturbDistance = CGRectGetMinX(rootViewRect)-CGRectGetMinX(_topViewBeginRect) case UIInterfaceOrientation.LandscapeRight: disturbDistance = CGRectGetMinX(_topViewBeginRect)-CGRectGetMinX(rootViewRect) case UIInterfaceOrientation.Portrait: disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect) case UIInterfaceOrientation.PortraitUpsideDown: disturbDistance = CGRectGetMinY(_topViewBeginRect)-CGRectGetMinY(rootViewRect) default: break } // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= max(move, disturbDistance) case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += max(move, disturbDistance) case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= max(move, disturbDistance) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += max(move, disturbDistance) default: break } _IQShowLog("Moving Downward") // Setting adjusted rootViewRect // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------------------- /// MARK: UIKeyboard Notifications ///------------------------------- /* UIKeyboardWillShowNotification. */ internal func keyboardWillShow(notification : NSNotification?) -> Void { _kbShowNotification = notification if enable == false { return } _IQShowLog("****** \(__FUNCTION__) started ******") //Due to orientation callback we need to resave it's original frame. // (Bug ID: #46) //Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92) if _keyboardManagerFlags.isTextFieldViewFrameChanged == false && _textFieldView != nil { if let textFieldView = _textFieldView { _textFieldViewIntialFrame = textFieldView.frame _IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)") } } // (Bug ID: #5) if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == true { // keyboard is not showing(At the beginning only). We should save rootViewRect. _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame _IQShowLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRectZero } } let oldKBSize = _kbSize if let info = notification?.userInfo { if shouldAdoptDefaultKeyboardAnimation { // Getting keyboard animation. if let curve = info[UIKeyboardAnimationCurveUserInfoKey]?.unsignedLongValue { _animationCurve = UIViewAnimationOptions(rawValue: curve) } } else { _animationCurve = UIViewAnimationOptions.CurveEaseOut } // Getting keyboard animation duration if let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue { //Saving animation duration if duration != 0.0 { _animationDuration = duration } } // Getting UIKeyboardSize. if let kbFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue { _kbSize = kbFrame.size _IQShowLog("UIKeyboard Size : \(_kbSize)") } } // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostController() } //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. if CGSizeEqualToSize(_kbSize, oldKBSize) == false { //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { //Getting textField viewController if let textFieldViewController = _textFieldView?.viewController() { var shouldIgnore = false for disabledClassString in _disabledClasses { if let disabledClass = NSClassFromString(disabledClassString) { //If viewController is kind of disabled viewController class, then ignoring to adjust view. if textFieldViewController.isKindOfClass(disabledClass) { shouldIgnore = true break } } } //If shouldn't ignore. if shouldIgnore == false { // keyboard is already showing. adjust frame. adjustFrame() } } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ internal func keyboardWillHide(notification : NSNotification?) -> Void { //If it's not a fake notification generated by [self setEnable:NO]. if notification != nil { _kbShowNotification = nil } //If not enabled then do nothing. if enable == false { return } _IQShowLog("****** \(__FUNCTION__) started ******") //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) // if (_textFieldView == nil) return // Boolean to know keyboard is showing/hiding _keyboardManagerFlags.isKeyboardShowing = false let info : [NSObject : AnyObject]? = notification?.userInfo // Getting keyboard animation duration if let duration = info?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue { if duration != 0 { // Setitng keyboard animation duration _animationDuration = duration } } //Restoring the contentOffset of the lastScrollView if let lastScrollView = _lastScrollView { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets if self.shouldRestoreScrollViewContentOffset == true { lastScrollView.contentOffset = self._startingContentOffset } self._IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)") // TODO: restore scrollView state // This is temporary solution. Have to implement the save and restore scrollView state var superScrollView = lastScrollView while let scrollView = superScrollView.superviewOfClassType(UIScrollView) as? UIScrollView { let contentSize = CGSizeMake(max(scrollView.contentSize.width, CGRectGetWidth(scrollView.frame)), max(scrollView.contentSize.height, CGRectGetHeight(scrollView.frame))) let minimumY = contentSize.height - CGRectGetHeight(scrollView.frame) if minimumY < scrollView.contentOffset.y { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, minimumY) self._IQShowLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)") } superScrollView = scrollView } }) { (finished) -> Void in } } // Setting rootViewController frame to it's original position. // (Bug ID: #18) if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == false { if let rootViewController = _rootViewController { //frame size needs to be adjusted on iOS8 due to orientation API changes. if #available(iOS 8.0, *) { _topViewBeginRect.size = rootViewController.view.frame.size } //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in var hasDoneTweakLayoutGuide = false if let viewController = self._textFieldView?.viewController() { if let constraint = viewController.IQLayoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide || itemLayoutGuide === viewController.bottomLayoutGuide) { constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() hasDoneTweakLayoutGuide = true } } } } if hasDoneTweakLayoutGuide == false { self._IQShowLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)") // Setting it's new frame rootViewController.view.frame = self._topViewBeginRect //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } } }) { (finished) -> Void in } _rootViewController = nil } } //Reset all values _lastScrollView = nil _kbSize = CGSizeZero _startingContentInsets = UIEdgeInsetsZero _startingScrollIndicatorInsets = UIEdgeInsetsZero _startingContentOffset = CGPointZero // topViewBeginRect = CGRectZero //Commented due to #82 _IQShowLog("****** \(__FUNCTION__) ended ******") } internal func keyboardDidHide(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") _topViewBeginRect = CGRectZero _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------------------------------- /// MARK: UITextField/UITextView Notifications ///------------------------------------------- /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */ internal func textFieldViewDidBeginEditing(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") // Getting object _textFieldView = notification.object as? UIView if overrideKeyboardAppearance == true { if let textFieldView = _textFieldView as? UITextField { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } else if let textFieldView = _textFieldView as? UITextView { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } } // Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. //Added _isTextFieldViewFrameChanged check. (Bug ID: #92) if _keyboardManagerFlags.isTextFieldViewFrameChanged == false { if let textFieldView = _textFieldView { _textFieldViewIntialFrame = textFieldView.frame _IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)") } } //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required. if enableAutoToolbar == true { _IQShowLog("adding UIToolbars if required") //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it. if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil { UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.addToolbarIfRequired() }, completion: { (finished) -> Void in //RestoringTextView before reloading inputViews if (self._keyboardManagerFlags.isTextFieldViewFrameChanged) { self._keyboardManagerFlags.isTextFieldViewFrameChanged = false if let textFieldView = self._textFieldView { textFieldView.frame = self._textFieldViewIntialFrame } } //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews. self._textFieldView?.reloadInputViews() }) } else { //Adding toolbar addToolbarIfRequired() } } if enable == false { _IQShowLog("****** \(__FUNCTION__) ended ******") return } _textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14) if _keyboardManagerFlags.isKeyboardShowing == false { // (Bug ID: #5) // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constant = _textFieldView?.viewController()?.IQLayoutGuideConstraint?.constant { _layoutGuideConstraintInitialConstant = constant } _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let rootViewController = _rootViewController { _topViewBeginRect = rootViewController.view.frame _IQShowLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)") } } //If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76) //See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { //Getting textField viewController if let textFieldViewController = _textFieldView?.viewController() { var shouldIgnore = false for disabledClassString in _disabledClasses { if let disabledClass = NSClassFromString(disabledClassString) { //If viewController is kind of disabled viewController class, then ignoring to adjust view. if textFieldViewController.isKindOfClass(disabledClass) { shouldIgnore = true break } } } //If shouldn't ignore. if shouldIgnore == false { // keyboard is already showing. adjust frame. adjustFrame() } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */ internal func textFieldViewDidEndEditing(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") //Removing gesture recognizer (Enhancement ID: #14) _textFieldView?.window?.removeGestureRecognizer(_tapGesture) // We check if there's a change in original frame or not. if _keyboardManagerFlags.isTextFieldViewFrameChanged == true { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self._keyboardManagerFlags.isTextFieldViewFrameChanged = false self._IQShowLog("Restoring \(self._textFieldView?._IQDescription()) frame to : \(self._textFieldViewIntialFrame)") self._textFieldView?.frame = self._textFieldViewIntialFrame }, completion: { (finished) -> Void in }) } //Setting object to nil _textFieldView = nil _IQShowLog("****** \(__FUNCTION__) ended ******") } /** UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */ internal func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18) if shouldFixTextViewClip { let textView = notification.object as! UITextView let line = textView.caretRectForPosition((textView.selectedTextRange?.start)!) let overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top) //Added overflow conditions (Bug ID: 95) if overflow > 0.0 && overflow < CGFloat(FLT_MAX) { // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it) // Scroll caret to visible area var offset = textView.contentOffset offset.y += overflow + 7 // leave 7 pixels margin // Cannot animate with setContentOffset:animated: or caret will not appear UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in textView.contentOffset = offset }, completion: { (finished) -> Void in }) } } } ///------------------------------------------ /// MARK: Interface Orientation Notifications ///------------------------------------------ /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/ internal func willChangeStatusBarOrientation(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") //If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView) if _keyboardManagerFlags.isTextFieldViewFrameChanged == true { if let textFieldView = _textFieldView { //Due to orientation callback we need to set it's original position. UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in self._keyboardManagerFlags.isTextFieldViewFrameChanged = false self._IQShowLog("Restoring \(textFieldView._IQDescription()) frame to : \(self._textFieldViewIntialFrame)") //Setting textField to it's initial frame textFieldView.frame = self._textFieldViewIntialFrame }, completion: { (finished) -> Void in }) } } _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------ /// MARK: AutoToolbar ///------------------ /** Get all UITextField/UITextView siblings of textFieldView. */ private func responderViews()-> [UIView]? { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. for disabledClassString in _toolbarPreviousNextConsideredClass { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = _textFieldView?.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22) if superConsideredView != nil { return superConsideredView?.deepResponderViews() } else { //Otherwise fetching all the siblings if let textFields = _textFieldView?.responderSiblings() { //Sorting textFields according to behaviour switch toolbarManageBehaviour { //If autoToolbar behaviour is bySubviews, then returning it. case IQAutoToolbarManageBehaviour.BySubviews: return textFields //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag() //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition() } } else { return nil } } } /** Add toolbar if it is required to add on textFields and it's siblings. */ private func addToolbarIfRequired() { if let textFieldViewController = _textFieldView?.viewController() { for disabledClassString in _disabledToolbarClasses { if let disabledClass = NSClassFromString(disabledClassString) { if textFieldViewController.isKindOfClass(disabledClass) { removeToolbarIfRequired() return } } } } // Getting all the sibling textFields. if let siblings = responderViews() { // If only one object is found, then adding only Done button. if siblings.count == 1 { let textField = siblings[0] //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78) } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false { //Updating placeholder font to toolbar. //(Bug ID: #148) if let _textField = textField as? UITextField { if toolbar.title == nil || toolbar.title != _textField.placeholder { toolbar.title = _textField.placeholder } } else if let _textView = textField as? IQTextView { if toolbar.title == nil || toolbar.title != _textView.placeholder { toolbar.title = _textView.placeholder } } else { toolbar.title = nil } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } } } else if siblings.count != 0 { // If more than 1 textField is found. then adding previous/next/done buttons on it. for textField in siblings { //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78) } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false { //Updating placeholder font to toolbar. //(Bug ID: #148) if let _textField = textField as? UITextField { if toolbar.title == nil || toolbar.title != _textField.placeholder { toolbar.title = _textField.placeholder } } else if let _textView = textField as? IQTextView { if toolbar.title == nil || toolbar.title != _textView.placeholder { toolbar.title = _textView.placeholder } } else { toolbar.title = nil } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) // If firstTextField, then previous should not be enabled. if siblings[0] == textField { textField.setEnablePrevious(false, isNextEnabled: true) } else if siblings.last == textField { // If lastTextField then next should not be enaled. textField.setEnablePrevious(true, isNextEnabled: false) } else { textField.setEnablePrevious(true, isNextEnabled: true) } } } } } } /** Remove any toolbar if it is IQToolbar. */ private func removeToolbarIfRequired() { // (Bug ID: #18) // Getting all the sibling textFields. if let siblings = responderViews() { for view in siblings { if let toolbar = view.inputAccessoryView as? IQToolbar { //setInputAccessoryView: check (Bug ID: #307) if view.respondsToSelector(Selector("setInputAccessoryView:")) && (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { if let textField = view as? UITextField { textField.inputAccessoryView = nil } else if let textView = view as? UITextView { textView.inputAccessoryView = nil } } } } } } private func _IQShowLog(logString: String) { #if IQKEYBOARDMANAGER_DEBUG println("IQKeyboardManager: " + logString) #endif } }
mit
4fc39d8a852c23ba467c5e43b11c8666
47.636826
370
0.569996
7.151832
false
false
false
false
JGiola/swift
test/Distributed/Inputs/FakeCodableForDistributedTests.swift
9
13904
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// Fake encoder intended to serialize into a string representation easy to /// assert on. public final class FakeEncoder { public func encode<T: Encodable>(_ value: T) throws -> String { let stringsEncoding = StringsEncoding() try value.encode(to: stringsEncoding) return dotStringsFormat(from: stringsEncoding.data.strings) } private func dotStringsFormat(from strings: [String: String]) -> String { let dotStrings = strings.map { k, v -> String in if k.isEmpty { return "\(v);" } else { return "\(k): \(v);" } } return dotStrings.joined(separator: " ") } } fileprivate struct StringsEncoding: Encoder { fileprivate final class Storage { private(set) var strings: [String: String] = [:] func encode(key codingKey: [CodingKey], value: String) { let key = codingKey.map { $0.stringValue } .joined(separator: ".") strings[key] = value } } fileprivate var data: Storage init(to encoded: Storage = Storage()) { self.data = encoded } var codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey: Any] = [:] func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { var container = StringsKeyedEncoding<Key>(to: data) container.codingPath = codingPath return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath return container } func singleValueContainer() -> SingleValueEncodingContainer { var container = StringsSingleValueEncoding(to: data) container.codingPath = codingPath return container } } fileprivate struct StringsKeyedEncoding<Key: CodingKey>: KeyedEncodingContainerProtocol { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] mutating func encodeNil(forKey key: Key) throws { data.encode(key: codingPath + [key], value: "nil") } mutating func encode(_ value: Bool, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: String, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value) } mutating func encode(_ value: Double, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Float, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int8, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int16, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int32, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int64, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt8, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt16, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt32, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt64, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath.append(key) try value.encode(to: stringsEncoding) } mutating func nestedContainer<NestedKey: CodingKey>( keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { var container = StringsKeyedEncoding<NestedKey>(to: data) container.codingPath = codingPath + [key] return KeyedEncodingContainer(container) } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath + [key] return container } mutating func superEncoder() -> Encoder { let superKey = Key(stringValue: "super")! return superEncoder(forKey: superKey) } mutating func superEncoder(forKey key: Key) -> Encoder { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath + [key] return stringsEncoding } } fileprivate struct StringsUnkeyedEncoding: UnkeyedEncodingContainer { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] private(set) var count: Int = 0 private mutating func nextIndexedKey() -> CodingKey { let nextCodingKey = IndexedCodingKey(intValue: count)! count += 1 return nextCodingKey } private struct IndexedCodingKey: CodingKey { let intValue: Int? let stringValue: String init?(intValue: Int) { self.intValue = intValue self.stringValue = intValue.description } init?(stringValue: String) { return nil } } mutating func encodeNil() throws { data.encode(key: codingPath + [nextIndexedKey()], value: "nil") } mutating func encode(_ value: Bool) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: String) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value) } mutating func encode(_ value: Double) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Float) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int8) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int16) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int32) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int64) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt8) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt16) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt32) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt64) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode<T: Encodable>(_ value: T) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath + [nextIndexedKey()] try value.encode(to: stringsEncoding) } mutating func nestedContainer<NestedKey: CodingKey>( keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { var container = StringsKeyedEncoding<NestedKey>(to: data) container.codingPath = codingPath + [nextIndexedKey()] return KeyedEncodingContainer(container) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath + [nextIndexedKey()] return container } mutating func superEncoder() -> Encoder { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath.append(nextIndexedKey()) return stringsEncoding } } fileprivate struct StringsSingleValueEncoding: SingleValueEncodingContainer { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] mutating func encodeNil() throws { data.encode(key: codingPath, value: "nil") } mutating func encode(_ value: Bool) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: String) throws { data.encode(key: codingPath, value: value) } mutating func encode(_ value: Double) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Float) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int8) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int16) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int32) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int64) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt8) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt16) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt32) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt64) throws { data.encode(key: codingPath, value: value.description) } mutating func encode<T: Encodable>(_ value: T) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath try value.encode(to: stringsEncoding) } } public final class FakeDecoder: Decoder { public var codingPath: [CodingKey] = [] public var userInfo: [CodingUserInfoKey: Any] = [:] var string: String = "" public func decode<T>(_ string: String, as type: T.Type) throws -> T where T: Decodable { self.string = string return try type.init(from: self) } public func container<Key>( keyedBy type: Key.Type ) throws -> KeyedDecodingContainer<Key> { fatalError("\(#function) not implemented") } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("\(#function) not implemented") } public func singleValueContainer() throws -> SingleValueDecodingContainer { return FakeSingleValueDecodingContainer(string: self.string) } } public final class FakeSingleValueDecodingContainer: SingleValueDecodingContainer { public var codingPath: [CodingKey] { [] } let string: String init(string: String) { self.string = string } public func decodeNil() -> Bool { fatalError("\(#function) not implemented") } public func decode(_ type: Bool.Type) throws -> Bool { fatalError("\(#function) not implemented") } public func decode(_ type: String.Type) throws -> String { String(self.string.split(separator: ";").first!) } public func decode(_ type: Double.Type) throws -> Double { fatalError("\(#function) not implemented") } public func decode(_ type: Float.Type) throws -> Float { fatalError("\(#function) not implemented") } public func decode(_ type: Int.Type) throws -> Int { fatalError("\(#function) not implemented") } public func decode(_ type: Int8.Type) throws -> Int8 { fatalError("\(#function) not implemented") } public func decode(_ type: Int16.Type) throws -> Int16 { fatalError("\(#function) not implemented") } public func decode(_ type: Int32.Type) throws -> Int32 { fatalError("\(#function) not implemented") } public func decode(_ type: Int64.Type) throws -> Int64 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt.Type) throws -> UInt { fatalError("\(#function) not implemented") } public func decode(_ type: UInt8.Type) throws -> UInt8 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt16.Type) throws -> UInt16 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt32.Type) throws -> UInt32 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt64.Type) throws -> UInt64 { fatalError("\(#function) not implemented") } public func decode<T>(_ type: T.Type) throws -> T where T : Decodable { fatalError("\(#function) not implemented") } }
apache-2.0
cd907cf390c2217157e03f7e452217ab
29.625551
91
0.68376
4.343643
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/TabSettings.swift
1
2129
// // TabSettings.swift // Justaway // // Created by Shinichiro Aska on 10/19/15. // Copyright © 2015 Shinichiro Aska. All rights reserved. // import Foundation import EventBox import KeyClip class Tab { struct Constants { static let type = "type" static let userID = "user_id" static let arguments = "arguments" } enum `Type`: String { case HomeTimline case UserTimline case Mentions case Notifications case Favorites case Searches case Lists case Messages } let type: Type let userID: String let arguments: NSDictionary init(type: Type, userID: String, arguments: NSDictionary) { self.type = type self.userID = userID self.arguments = arguments } init(_ dictionary: NSDictionary) { self.type = Type(rawValue: (dictionary[Constants.type] as? String) ?? "")! self.userID = (dictionary[Constants.userID] as? String) ?? "" self.arguments = (dictionary[Constants.arguments] as? NSDictionary) ?? NSDictionary() } init(userID: String, keyword: String) { self.type = .Searches self.userID = userID self.arguments = ["keyword": keyword] } init(userID: String, user: TwitterUser) { self.type = .UserTimline self.userID = userID self.arguments = ["user": user.dictionaryValue] } init(userID: String, list: TwitterList) { self.type = .Lists self.userID = userID self.arguments = ["list": list.dictionaryValue] } var keyword: String { return self.arguments["keyword"] as? String ?? "-" } var user: TwitterUser { return TwitterUser(self.arguments["user"] as? [String: AnyObject] ?? [:]) } var list: TwitterList { return TwitterList(self.arguments["list"] as? [String: AnyObject] ?? [:]) } var dictionaryValue: NSDictionary { return [ Constants.type : type.rawValue, Constants.userID : userID, Constants.arguments : arguments ] } }
mit
4ac7eefce2f913b0da406d72092d8a38
24.333333
93
0.593985
4.433333
false
false
false
false
LemonRuss/TableComponents
TableComponents/Classes/Common/UIColor+Helper.swift
1
686
// // UIColor+Helper.swift // EFS // // Created by Artur Guseynov on 20.06.16. // Copyright © 2016 Sberbank. All rights reserved. // import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(hex: Int) { self.init(red: (hex >> 16) & 0xff, green: (hex >> 8) & 0xff, blue: hex & 0xff) } }
mit
b163ccedb3196968316c316312bc28d6
23.464286
82
0.588321
3.142202
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Settings/AppSettingsOptions.swift
1
49234
/* 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 Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var accessibilityIdentifier: String? { return "SignInToSync" } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.imageView?.image = UIImage.templateImageNamed("FxA-Default") cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 cell.imageView?.layer.masksToBounds = true } } class SyncNowSetting: WithAccountSetting { let imageView = UIImageView(frame: CGRect(width: 30, height: 30)) let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear) let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20)) let syncIcon: UIImage? = { let image = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20)) return ThemeManager.instance.currentName == .dark ? image?.tinted(withColor: .white) : image }() // Animation used to rotate the Sync icon 360 degrees while syncing is in progress. let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation") override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil) } fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { if !DeviceInfo.hasConnectivity() { return NSAttributedString( string: Strings.FxANoInternetConnection, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultMediumFont ] ) } return NSAttributedString( string: Strings.FxASyncNow, attributes: [ NSAttributedString.Key.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)]) func startRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey") } } @objc func stopRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.removeAllAnimations() } } override var accessoryType: UITableViewCell.AccessoryType { return .none } override var image: UIImage? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncIcon } switch syncStatus { case .inProgress: return syncBlueIcon default: return syncIcon } } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var hidden: Bool { return !enabled } override var enabled: Bool { if !DeviceInfo.hasConnectivity() { return false } return profile.hasSyncableAccount() } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: .roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity() // Animation that loops continously until stopped continuousRotateAnimation.fromValue = 0.0 continuousRotateAnimation.toValue = CGFloat(Double.pi) continuousRotateAnimation.isRemovedOnCompletion = true continuousRotateAnimation.duration = 0.5 continuousRotateAnimation.repeatCount = .infinity // To ensure sync icon is aligned properly with user's avatar, an image is created with proper // dimensions and color, then the scaled sync icon is added as a subview. imageView.contentMode = .center imageView.image = image cell.imageView?.subviews.forEach({ $0.removeFromSuperview() }) cell.imageView?.image = syncIconWrapper cell.imageView?.addSubview(imageView) if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .inProgress: self.startRotateSyncIcon() default: self.stopRotateSyncIcon() } } } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { if !DeviceInfo.hasConnectivity() { return } NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil) } @objc func updateAccount(notification: Notification) { DispatchQueue.main.async { self.settings.tableView.reloadData() } } override var image: UIImage? { if let image = profile.getAccount()?.fxaProfile?.avatar.image { return image.createScaled(CGSize(width: 30, height: 30)) } let image = UIImage(named: "placeholder-avatar") return image?.createScaled(CGSize(width: 30, height: 30)) } override var accessoryType: UITableViewCell.AccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: // We link to the resend verification email page. return .disclosureIndicator case .needsPassword: // We link to the re-enter password page. return .disclosureIndicator case .none: // We link to FxA web /settings. return .disclosureIndicator case .needsUpgrade: // In future, we'll want to link to an upgrade page. return .none } } return .disclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { if let displayName = account.fxaProfile?.displayName { return NSAttributedString(string: displayName, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } if let email = account.fxaProfile?.email { return NSAttributedString(string: email, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } return NSAttributedString(string: account.email, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { var string: String switch account.actionNeeded { case .none: return nil case .needsVerification: string = Strings.FxAAccountVerifyEmail break case .needsPassword: string = Strings.FxAAccountVerifyPassword break case .needsUpgrade: string = Strings.FxAAccountUpgradeFirefox break } let orange = UIColor.theme.tableView.warningText let range = NSRange(location: 0, length: string.count) let attrs = [NSAttributedString.Key.foregroundColor: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } return nil } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .none: let viewController = SyncContentSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) return case .needsVerification: var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = cs?.url { viewController.url = url } case .needsPassword: var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = cs?.url { viewController.url = url } case .needsUpgrade: // In future, we'll want to link to an upgrade page. return } } navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let imageView = cell.imageView { imageView.subviews.forEach({ $0.removeFromSuperview() }) imageView.frame = CGRect(width: 30, height: 30) imageView.layer.cornerRadius = (imageView.frame.height) / 2 imageView.layer.masksToBounds = true imageView.image = image } } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.hasPrefix("browser.") || file.hasPrefix("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } class ExportLogDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Logger.copyPreviousLogsToDocuments() } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Sentry.shared.crash() } } class SlowTheDatabase: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: simulate slow database operations", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { debugSimulateSlowDBOperations = !debugSimulateSlowDBOperations } } class SentryIDSetting: HiddenSetting { let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: "SentryDeviceAppHash") ?? "0000000000000000000000000000000000000000" override var title: NSAttributedString? { return NSAttributedString(string: "Debug: \(deviceAppHash)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10)]) } override func onClick(_ navigationController: UINavigationController?) { copyAppDeviceIDAndPresentAlert(by: navigationController) } func copyAppDeviceIDAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = deviceAppHash navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController override var accessibilityIdentifier: String? { return "FxVersion" } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } override func onLongPress(_ navigationController: UINavigationController?) { copyAppVersionAndPresentAlert(by: navigationController) } func copyAppVersionAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = self.title?.string navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } // Opens the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "\(InternalURL.baseUrl)/\(AboutLicenseHandler.path)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { let statusText = NSMutableAttributedString() statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight])) statusText.append(NSAttributedString(string: " ")) statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.general.highlightBlue])) super.init( prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle), attributedStatusText: statusText, settingDidChange: { AdjustIntegration.setEnabled($0) LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0]) LeanPlumClient.shared.set(enabled: $0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController super.init(title: NSAttributedString(string: Strings.LoginsAndPasswordsTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { deselectRow() guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let navController = navigationController else { return } LoginListViewController.create(authenticateInNavigationController: navController, profile: profile, settingsDelegate: appDelegate.browserViewController).uponQueue(.main) { loginsVC in guard let loginsVC = loginsVC else { return } LeanPlumClient.shared.track(event: .openedLogins) navController.pushViewController(loginsVC, animated: true) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let localAuthContext = LAContext() let title: String if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { if localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class ContentBlockerSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TrackingProtection" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ContentBlockerSettingViewController(prefs: profile.prefs) viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsDataManagementSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) } } class StageSyncServiceDebugSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } var prefKey: String = "useStageSyncService" override var accessibilityIdentifier: String? { return "DebugStageSync" } override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return true } return false } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { let configurationURL = profile.accountConfiguration.authEndpointURL return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? false cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) settings.tableView.reloadData() } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getNewTabPage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabContentSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class HomeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Home" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getHomePage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.AppMenuOpenHomePageTitleString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 12.0, *) class SiriPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "SiriSettings" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SiriSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } override var status: NSAttributedString { guard let provider = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), provider != "mailto:" else { return NSAttributedString(string: "") } if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { let mailProvider = dictRoot.compactMap({$0 as? NSDictionary }).first { (dict) -> Bool in return (dict["scheme"] as? String) == provider } return NSAttributedString(string: (mailProvider?["name"] as? String) ?? "") } return NSAttributedString(string: "") } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class AdvancedAccountSetting: HiddenSetting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "AdvancedAccount.Setting" } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsAdvancedAccountTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdvancedAccountSettingViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override var hidden: Bool { return !ShowDebugSettings || profile.hasAccount() } } class ThemeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "DisplayThemeOption" } override var status: NSAttributedString { if ThemeManager.instance.automaticBrightnessIsOn { return NSAttributedString(string: Strings.DisplayThemeAutomaticStatusLabel) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(ThemeSettingsController(), animated: true) } } class TranslationSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "TranslationOption" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingTranslateSnackBarTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(TranslationSettingsController(profile), animated: true) } }
mpl-2.0
7c72f4ef32e44a7208644a2c1fd457a0
40.976109
329
0.700504
5.675588
false
false
false
false
apple/swift-docc-symbolkit
Tests/SymbolKitTests/SymbolGraph/ModuleTests.swift
1
3048
/* This source file is part of the Swift.org open source project Copyright (c) 2022 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 Swift project authors */ import XCTest import SymbolKit extension SymbolGraph.Module { func roundTripDecode() throws -> Self { let encoder = JSONEncoder() let encoded = try encoder.encode(self) let decoder = JSONDecoder() return try decoder.decode(SymbolGraph.Module.self, from: encoded) } } class ModuleTests: XCTestCase { static let os = SymbolGraph.OperatingSystem(name: "macOS", minimumVersion: .init(major: 10, minor: 9, patch: 0)) static let platform = SymbolGraph.Platform(architecture: "arm64", vendor: "Apple", operatingSystem: os) func testFullRoundTripCoding() throws { let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, bystanders: ["A"], isVirtual: true) let decodedModule = try module.roundTripDecode() XCTAssertEqual(module, decodedModule) } func testOptionalBystanders() throws { do { // bystanders = nil let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertNil(decodedModule.bystanders) } do { // bystanders = ["A"] let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, bystanders: ["A"]) let decodedModule = try module.roundTripDecode() XCTAssertEqual(["A"], decodedModule.bystanders) } } func testOptionalIsVirtual() throws { do { // isVirtual = false let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertFalse(decodedModule.isVirtual) } do { // isVirtual = true let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, isVirtual: true) let decodedModule = try module.roundTripDecode() XCTAssertTrue(decodedModule.isVirtual) } } func testOptionalVersion() throws { do { // version = nil let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertNil(decodedModule.version) } do { // version = 1.0.0 let version = SymbolGraph.SemanticVersion(major: 1, minor: 0, patch: 0) let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, version: version) let decodedModule = try module.roundTripDecode() XCTAssertEqual(version, decodedModule.version) } } }
apache-2.0
da8b0711341d38228b1028b25a70d3ca
36.62963
121
0.633858
4.948052
false
true
false
false
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/AppDelegate.swift
2
1761
// // AppDelegate.swift // SwiftNetworkImages // // Created by Arseniy Kuznetsov on 30/4/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit /// The App Delegate @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds).configure { $0.backgroundColor = .white $0.rootViewController = configureTopViewController() $0.makeKeyAndVisible() } return true } } extension AppDelegate { /// Configures top level view controller and its dependencies func configureTopViewController() -> UIViewController { // Images info loader let imagesInfoLoader = ImagesInfoLoader() // Network image service let imageService = NSURLSessionNetworkImageService() var imageFetcher = ImageFetcher() imageFetcher.inject(imageService) // Images info data source var imagesDataSource = ImagesDataSource() imagesDataSource.inject((imagesInfoLoader, imageFetcher)) // Delegate / Data Source for the collection view let dataSourceDelegate = SampleImagesDataSourceDelegate() // Top-level view controller let viewController = SampleImagesViewController() dataSourceDelegate.inject((imagesDataSource, viewController)) viewController.inject(dataSourceDelegate) return viewController } }
mit
7f848bb0ccd822505827609e425ff69b
25.268657
106
0.647159
5.945946
false
true
false
false
regini/inSquare
inSquareAppIOS/inSquareAppIOS/FavoriteSquareViewController.swift
1
7399
// // FavoriteSquareViewController.swift // inSquare // // Created by Alessandro Steri on 02/03/16. // Copyright © 2016 Alessandro Steri. All rights reserved. // import UIKit import GoogleMaps import Alamofire class FavoriteSquareViewController: UIViewController, UITableViewDelegate { var favouriteSquare = JSON(data: NSData()) { didSet { self.tableView.reloadData() } } //values to pass by cell chatButton tap, updated when the button is tapped var squareId:String = String() var squareName:String = String() var squareLatitude:Double = Double() var squareLongitude:Double = Double() @IBOutlet var tableView: UITableView! @IBOutlet var tabBar: UITabBarItem! @IBAction func unwindToFav(segue: UIStoryboardSegue) { } override func viewDidLoad() { super.viewDidLoad() //UIApplication.sharedApplication().statusBarStyle = .Default // let tabBarHeight = self.tabBarController!.tabBar.frame.height // con.constant = viewSquare.frame.height request(.GET, "\(serverMainUrl)/favouritesquares/\(serverId)").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { // print("FAVOURITESQUARES \(value)") self.favouriteSquare = JSON(value) // print("FAVOURITESQUARES2 \(self.favouriteSquare[0]["_source"])") self.tableView.reloadData() } case .Failure(let error): print(error) } }//ENDREQUEST }//END VDL func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favouriteSquare.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let cell = FavouriteCellTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "favCell") let cell = self.tableView.dequeueReusableCellWithIdentifier("favCell", forIndexPath: indexPath) as! FavouriteCellTableViewCell // print("qwerty \(self.favouriteSquare[indexPath.row]["_source"]["lastMessageDate"])") cell.squareName.text = self.favouriteSquare[indexPath.row]["_source"]["name"].string let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let date = dateFormatter.dateFromString("\(self.favouriteSquare[indexPath.row]["_source"]["lastMessageDate"].string!)") // print(date) let newDateFormatter = NSDateFormatter() newDateFormatter.locale = NSLocale.currentLocale() newDateFormatter.dateFormat = "hh:mm (dd-MMM)" var convertedDate = newDateFormatter.stringFromDate(date!) cell.squareActive.text = "Active: \(convertedDate)" //cell.goInSquare(cell) cell.tapped = { [unowned self] (selectedCell) -> Void in let path = tableView.indexPathForRowAtPoint(selectedCell.center)! let selectedSquare = self.favouriteSquare[path.row] // print("the selected item is \(selectedSquare)") self.squareId = selectedSquare["_id"].string! self.squareName = selectedSquare["_source"]["name"].string! let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",") let latitude = (coordinates[0] as NSString).doubleValue let longitude = (coordinates[1] as NSString).doubleValue self.squareLatitude = latitude self.squareLongitude = longitude self.performSegueWithIdentifier("chatFromFav", sender: self) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPath = tableView.indexPathForSelectedRow let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as! FavouriteCellTableViewCell let selectedSquare = self.favouriteSquare[indexPath!.row] //let path = tableView.indexPathForRowAtPoint(selectedCell.center)! print("the selected item is \(selectedSquare)") self.squareId = selectedSquare["_id"].string! self.squareName = selectedSquare["_source"]["name"].string! let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",") let latitude = (coordinates[0] as NSString).doubleValue let longitude = (coordinates[1] as NSString).doubleValue self.squareLatitude = latitude self.squareLongitude = longitude self.performSegueWithIdentifier("chatFromFav", sender: self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //inutile? //updateFavouriteSquares() //viewDidLoad() request(.GET, "\(serverMainUrl)/favouritesquares/\(serverId)").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { // print("FAVOURITESQUARES \(value)") self.favouriteSquare = JSON(value) // print("FAVOURITESQUARES2 \(self.favouriteSquare[0]["_source"])") self.tableView.reloadData() } case .Failure(let error): print(error) } }//ENDREQUEST } // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // // //inutile? // tableView.reloadData() // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }//END DRMW override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "chatFromFav") { //Checking identifier is crucial as there might be multiple // segues attached to same view print("chatFromFav") print(squareId) print(squareName) print(squareLatitude) print(squareLongitude) //var detailVC = segue!.destinationViewController as! SquareMessViewController //var detailVC = segue!.destinationViewController as! NavigationToJSQViewController // let detailVC = detailNC.topViewController as! inSquareViewController let navVC = segue.destinationViewController as! UINavigationController let detailVC = navVC.viewControllers.first as! SquareMessViewController detailVC.viewControllerNavigatedFrom = segue.sourceViewController detailVC.squareName = self.squareName detailVC.squareId = self.squareId detailVC.squareLatitude = self.squareLatitude detailVC.squareLongitude = self.squareLongitude } } }// END VC
mit
2e3a0853b29c593ce96ee6ccab2f3ec9
35.623762
134
0.613274
5.562406
false
false
false
false
austinzheng/swift
test/DebugInfo/mangling.swift
11
1925
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // Type: // Swift.Dictionary<Swift.Int64, Swift.String> func markUsed<T>(_ t: T) {} // Variable: // mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String> // CHECK: !DIGlobalVariable(name: "myDict", // CHECK-SAME: linkageName: "$s8mangling6myDictSDys5Int64VSSGvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[DT:[0-9]+]] // CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary" var myDict = Dictionary<Int64, String>() myDict[12] = "Hello!" // mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple1", // CHECK-SAME: linkageName: "$s8mangling8myTuple1SS4Name_s5Int64V2Idtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT1:[0-9]+]] // CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS4Name_s5Int64V2IdtD" var myTuple1 : (Name: String, Id: Int64) = ("A", 1) // mangling.myTuple2 : (Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple2", // CHECK-SAME: linkageName: "$s8mangling8myTuple2SS_s5Int64V2Idtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT2:[0-9]+]] // CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64V2IdtD" var myTuple2 : ( String, Id: Int64) = ("B", 2) // mangling.myTuple3 : (Swift.String, Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple3", // CHECK-SAME: linkageName: "$s8mangling8myTuple3SS_s5Int64Vtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT3:[0-9]+]] // CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64VtD" var myTuple3 : ( String, Int64) = ("C", 3) markUsed(myTuple1.Id) markUsed(myTuple2.Id) markUsed({ $0.1 }(myTuple3))
apache-2.0
32f4c794dad1f541527d20d50423b9ca
44.833333
97
0.62026
2.899096
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTAnalog.swift
1
1243
// // GATTAnalog.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Analog The Analog characteristic is used to read or write the value of one of the IO Module’s analog signals. - SeeAlso: [Analog](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.analog.xml) */ @frozen public struct GATTAnalog: GATTCharacteristic, Equatable, Hashable { internal static let length = MemoryLayout<UInt16>.size public static var uuid: BluetoothUUID { return .analog} public var analog: UInt16 public init(analog: UInt16) { self.analog = analog } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.init(analog: UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))) } public var data: Data { let bytes = analog.littleEndian.bytes return Data([bytes.0, bytes.1]) } } extension GATTAnalog: CustomStringConvertible { public var description: String { return analog.description } }
mit
e625bbe1d04ac1262df3196c905be69f
22.396226
131
0.63629
4.290657
false
false
false
false
auth0/Lock.swift
Lock/Style.swift
1
6686
// Style.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit /** * Define Auth0 Lock style and allows to customise it. */ public struct Style { /// Title used in Header public var title = "Auth0".i18n(key: "com.auth0.lock.header.default_title", comment: "Header Title") /// Primary color of Lock used in the principal components like the Primary Button public var primaryColor = UIColor.a0_orange /// Lock background color public var backgroundColor = UIColor.white /// Lock background image public var backgroundImage: UIImage? /// Lock disabled component color public var disabledColor = UIColor(red: 0.8902, green: 0.898, blue: 0.9059, alpha: 1.0) /// Lock disabled component text color public var disabledTextColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Primary button tint color public var buttonTintColor = UIColor.white /// Header background color. By default it has no color but a blur public var headerColor: UIColor? /// Blur effect style used. It can be any value defined in `UIBlurEffectStyle` public var headerBlur: A0BlurEffectStyle = .light /// Header close button image public var headerCloseIcon: UIImage? = UIImage(named: "ic_close", in: bundleForLock()) /// Header back button image public var headerBackIcon: UIImage? = UIImage(named: "ic_back", in: bundleForLock()) /// Header title color public var titleColor = UIColor.black /// Hide header title (show only logo). By default is false public var hideTitle = false { didSet { hideButtonTitle = false } } /// Main body text color public var textColor = UIColor.black /// Hide primary button title (show only icon). By default is false public var hideButtonTitle = false /// Header logo image public var logo: UIImage? = UIImage(named: "ic_auth0", in: bundleForLock()) /// OAuth2 custom connection styles by mapping a connection name with an `AuthStyle` public var oauth2: [String: AuthStyle] = [:] /// Social seperator label public var seperatorTextColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.54) /// Input field text color public var inputTextColor = UIColor.black /// Input field placeholder text color public var inputPlaceholderTextColor = UIColor(red: 0.780, green: 0.780, blue: 0.804, alpha: 1.00) // #C7C7CD /// Input field border color default public var inputBorderColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Input field border color invalid public var inputBorderColorError = UIColor.red /// Input field background color public var inputBackgroundColor = UIColor.white /// Input field icon background color public var inputIconBackgroundColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Input field icon color public var inputIconColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Password rule text color default public var ruleTextColor = UIColor(red: 0.016, green: 0.016, blue: 0.016, alpha: 1.0) /// Password rule text color valid public var ruleTextColorSuccess = UIColor(red: 0.502, green: 0.820, blue: 0.208, alpha: 1.0) /// Password rule text color invalid public var ruleTextColorError = UIColor(red: 0.745, green: 0.271, blue: 0.153, alpha: 1.0) /// Secondary button color public var secondaryButtonColor = UIColor.black /// Terms of Use and Privacy Policy button color public var termsButtonColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Terms of Use and Privacy Policy button title color public var termsButtonTitleColor = UIColor.black /// Database login Tab Text Color public var tabTextColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Database login selected Tab Text Color public var selectedTabTextColor = UIColor.black /// Database login Tab Tint Color public var tabTintColor = UIColor.black /// Lock Controller Status bar update animation public var statusBarUpdateAnimation: UIStatusBarAnimation = .none /// Lock Controller Status bar hidden public var statusBarHidden = false /// Lock Controller Status bar style public var statusBarStyle: UIStatusBarStyle = .default /// Passwordless search bar style public var searchBarStyle: A0SearchBarStyle = .default /// iPad Modal Presentation Style public var modalPopup = true var headerMask: UIImage? { let image = self.logo if Style.Auth0.logo == image { return image?.withRenderingMode(.alwaysTemplate) } return image } func primaryButtonColor(forState state: A0ControlState) -> UIColor { if state.contains(.highlighted) { return self.primaryColor.a0_darker(0.20) } if state.contains(.disabled) { return self.disabledColor } return self.primaryColor } func primaryButtonTintColor(forState state: A0ControlState) -> UIColor { if state.contains(.disabled) { return self.disabledTextColor } return self.buttonTintColor } static let Auth0 = Style() } protocol Stylable { func apply(style: Style) }
mit
9a2ad90375a60c8e0fd64390e057a0d0
35.140541
113
0.676039
4.469251
false
false
false
false
sweetmans/SMInstagramPhotoPicker
SMInstagramPhotoPicker/Classes/SMPhotoPickerLibraryView+CollectionViewDelegate.swift
2
3627
// // SMPhotoPickerLibraryView+CollectionViewDelegate.swift // SMInstagramPhotosPicker // // Created by MacBook Pro on 2017/4/18. // Copyright © 2017年 Sweetman, Inc. All rights reserved. // import Foundation import UIKit import Photos extension SMPhotoPickerLibraryView { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SMPhotoPickerImageCell", for: indexPath) as! SMPhotoPickerImageCell let asset = self.images[(indexPath as NSIndexPath).item] PHImageManager.default().requestImage(for: asset, targetSize: cellSize, contentMode: .aspectFill, options: nil) { (image, info) in cell.image = image } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images == nil ? 0 : images.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let width = (collectionView.frame.width - 3) / 4.00 //print("Cell Width", width, collectionView.frame.width) return CGSize(width: width, height: width) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let asset = images[(indexPath as NSIndexPath).row] currentAsset = asset isOnDownloadingImage = true let targetSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) //print(asset.sourceType) if currentImageRequestID != nil { //print("cancel loading image from icloud. ID:\(self.currentImageRequestID!)") PHImageManager.default().cancelImageRequest(self.currentImageRequestID!) } progressView.isHidden = true let op = PHImageRequestOptions() op.isNetworkAccessAllowed = true op.progressHandler = {(progress, err, pointer, info) in DispatchQueue.main.async { if self.progressView.isHidden { self.progressView.isHidden = false } self.progressView.progress = CGFloat(progress) if progress == 1.0 { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3, execute: { self.progressView.progress = 0.0 self.progressView.isHidden = true }) } } //print(progress) } DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { self.currentImageRequestID = PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: op) { (image, info) in if let isInCloud = info?[PHImageResultIsInCloudKey] as? Bool { self.isOnDownloadingImage = isInCloud } if image != nil { //self.isOnDownloadingImage = false DispatchQueue.main.async { self.setupFirstLoadingImageAttrabute(image: image!) } } } } } }
mit
d5720297be9bd76835dfbf1945ecf480
31.945455
172
0.578918
5.835749
false
false
false
false
EZ-NET/ESSwim
Sources/Function/Collection.swift
1
3245
// // Collection.swift // ESSwim // // Created by Tomohiro Kumagai on H27/04/24. // // extension CollectionType { /** Returns the first index where `predicate` become true in `domain` or `nil` if `value` is not found. */ public func indexOf(predicate:(Generator.Element) -> Bool) -> Index? { let predicateWithIndex = { index in predicate(self[index]) ? Optional(index) : nil } return self.indices.traverse(predicateWithIndex) } /// Make indexes of `domain` by distances. public func indexesOf(distances:[Index.Distance]) -> [Index] { let start = self.startIndex let indexes = distances.map { advance(start, $0, self)! } return indexes } /// Get filtered Array by exclude the `indexes`. public func filter(excludeIndexes indexes:[Index]) -> [Generator.Element] { var result = Array<Generator.Element>() for index in self.indices { if !indexes.contains(index) { result.append(self[index]) } } return result } } extension CollectionType where Index.Distance : IntegerType { // Make indexes of `domain` to meet `predicate`. public func indexesOf(@noescape predicate:(Generator.Element) -> Bool) -> [Index] { typealias Distance = Index.Distance var distances = Array<Distance>() for element in self.enumerate() { if predicate(element.1) { let index = Distance(element.0.toIntMax()) distances.append(index) } } return self.indexesOf(distances) } } extension CollectionType where Generator.Element : Equatable { /// Get elements that same element appeared more than once. public func elementsAppearedDupplicately() -> [Generator.Element] { typealias Element = Generator.Element typealias Elements = [Element] var _exists = Elements() var _dupplicated = Elements() let appendToResults:(Element) -> Void = { if !_dupplicated.contains($0) { _dupplicated.append($0) } } let isElementDupplicated:(Element)->Bool = { if _exists.contains($0) { return true } else { _exists.append($0) return false } } for element in self { if isElementDupplicated(element) { appendToResults(element) } } return _dupplicated } /// Get an Array that has distinct elements. /// If same element found, leaved the first element only. public func distinct() -> [Generator.Element] { typealias Element = Generator.Element typealias Elements = [Element] var results = Elements() for element in self { if !results.contains(element) { results.append(element) } } return results } } extension RangeReplaceableCollectionType where Index.Distance : SignedIntegerType { /// Remove elements at `indexes` from `domain`. public mutating func remove(indexes:[Index]) { let comparator:(Index, Index) -> Bool = { compareIndex($0, $1).isAscending } for index in indexes.distinct().sort(comparator).reverse() { self.removeAtIndex(index) } } } extension CollectionType where Generator.Element : ExistenceDeterminationable { public func existingElements() -> [Generator.Element] { return self.filter { $0.isExists } } }
mit
839707fd5d8f8b7d1f5b24491f84a9ab
18.431138
100
0.656086
3.729885
false
false
false
false
tianbinbin/DouYuShow
DouYuShow/DouYuShow/Classes/Main/View/PageTitleView.swift
1
6099
// // PageTitleView.swift // DouYuShow // // Created by 田彬彬 on 2017/5/30. // Copyright © 2017年 田彬彬. All rights reserved. // import UIKit private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) // 灰色 private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) // 橘色 //协议代理 protocol PageTitleViewDelegate:class{ // selectindex index selectindex 作为外部参数 index 作为内部参数 func pageTitle(titleView:PageTitleView,selectindex index:Int) } class PageTitleView: UIView { // mark: 定义属性 fileprivate var titles : [String] fileprivate var currentIndex:Int = 0 weak var delegate : PageTitleViewDelegate? // mark: 懒加载属性 fileprivate lazy var titlelabels:[UILabel] = [UILabel]() fileprivate lazy var scrollView:UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.isPagingEnabled = false scrollView.bounces = false return scrollView }() // mark: 滚动的线 fileprivate lazy var ScrollLine:UIView = { let ScrollLine = UIView() ScrollLine.backgroundColor = UIColor.orange return ScrollLine }() // mark: 自定义构造函数 init(frame: CGRect,titles:[String]) { self.titles = titles super.init(frame:frame) //1.设置UI界面 SetUPUI() } // 重写 init 构造函数一定要实现这个方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func SetUPUI(){ // 1.添加scrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加label SetUpTitleLabels() // 3.设置底线和滚动的滑块 SetUpBootomlineAndScrollLine() } private func SetUpTitleLabels(){ let labelW:CGFloat = frame.width/CGFloat(titles.count) let labelH:CGFloat = frame.height - kScrollLineH let labelY:CGFloat = 0 for (index,title) in titles.enumerated() { // 1.创建lb let label = UILabel() label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 ) label.textAlignment = .center let labelX:CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titlelabels.append(label) // 2.给lb添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titltLabelClick(_:))) label.addGestureRecognizer(tapGes) } } private func SetUpBootomlineAndScrollLine(){ //1.添加底线 let bootomLine = UIView() bootomLine.backgroundColor = UIColor.lightGray let lineH:CGFloat = 0.5 bootomLine.frame = CGRect(x: 0, y: frame.height-lineH, width: frame.width, height: lineH) addSubview(bootomLine) //2.添加滚动的线 //2.1 获取第一个lable guard let firstlabel = titlelabels.first else { return } firstlabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //2.2 设置ScrollLine的属性 scrollView.addSubview(ScrollLine) ScrollLine.frame = CGRect(x: firstlabel.frame.origin.x, y: frame.height-kScrollLineH, width: firstlabel.frame.width, height: kScrollLineH) } } extension PageTitleView{ @objc fileprivate func titltLabelClick(_ tapGes:UITapGestureRecognizer){ //1. 获取当前label 的 下标值 guard let currentlb = tapGes.view as? UILabel else { return } //2. 获取之前的lb let olderLabel = titlelabels[currentIndex] //3. 保存最新lb的下标值 currentIndex = currentlb.tag //4. 切换文字的颜色 currentlb.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) olderLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 ) //5. 滚动条的位置发生改变 let scrollLinePosition = CGFloat(currentlb.tag) * ScrollLine.frame.width UIView.animate(withDuration: 0.25) { self.ScrollLine.frame.origin.x = scrollLinePosition } //6.通知代理 delegate?.pageTitle(titleView: self, selectindex: currentIndex) } } // 对外暴漏的方法 extension PageTitleView{ func SetTitleViewProgress(progress:CGFloat,sourceIndex:Int,targetIndex:Int) { //1.取出对应的sourcelabel/targetlabel let sourcelabel = titlelabels[sourceIndex] let targetlabel = titlelabels[targetIndex] //2.处理滑块逻辑 let moveTotalX = targetlabel.frame.origin.x - sourcelabel.frame.origin.x let moveX = moveTotalX * progress ScrollLine.frame.origin.x = sourcelabel.frame.origin.x + moveX //3.颜色渐变( 复杂 ) let colorDelta = (kSelectColor.0-kNormalColor.0,kSelectColor.1-kNormalColor.1,kSelectColor.2-kNormalColor.2) sourcelabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.0 * progress, b: kSelectColor.2 - colorDelta.0 * progress) targetlabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.0 * progress, b: kNormalColor.2 - colorDelta.0 * progress) currentIndex = targetIndex } }
mit
0af3a5bb81ff8a1af78349f9a298921e
30.07027
174
0.622129
4.473152
false
false
false
false
panyam/SwiftHTTP
Sources/Utils/Crypto.swift
2
879
// // Crypto.swift // SwiftHTTP // // Created by Sriram Panyam on 12/27/15. // Copyright © 2015 Sriram Panyam. All rights reserved. // import Foundation import CommonCrypto extension String { func SHA1Bytes() -> NSData { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) return NSData(bytes: digest, length: Int(CC_SHA1_DIGEST_LENGTH)) } func SHA1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joinWithSeparator("") } }
apache-2.0
914e11052391a5fb1689cbdfc162eeb4
29.275862
80
0.649203
3.526104
false
false
false
false
jedlewison/MockURLSession
TestApp/NetworkModel.swift
2
1522
// // NetworkModel.swift // Interceptor // // Created by Jed Lewison on 2/12/16. // Copyright © 2016 Magic App Factory. All rights reserved. // import Foundation import Alamofire class SillyNetworkModel { var requestResult: String? var error: ErrorType? func startAlamofire(url: NSURL) { Alamofire.request(NSURLRequest(URL: url)).responseString { (response) -> Void in print("*******************************", __FUNCTION__) switch response.result { case .Failure(let error): self.error = error case .Success(let value): self.requestResult = value } } } func startURLRequest(url: NSURL) { let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url)) { responses in if let data = responses.0 { self.requestResult = String(data: data, encoding: NSUTF8StringEncoding) } self.error = responses.2 } dataTask.resume() } func startURL(url: NSURL) { let dataTask = NSURLSession.sharedSession().dataTaskWithURL(url) { responses in if let data = responses.0 { self.requestResult = String(data: data, encoding: NSUTF8StringEncoding) } self.error = responses.2 } dataTask.resume() } }
mit
4286789a7370f97b9c61d4481ba83f02
24.79661
97
0.5286
5.121212
false
false
false
false
bravelocation/daysleft
daysleft/Models/DisplayValues.swift
1
1808
// // DisplayValues.swift // DaysLeft // // Created by John Pollard on 26/09/2022. // Copyright © 2022 Brave Location Software. All rights reserved. // import Foundation /// Display values used in the UI of the app struct DisplayValues { /// Number of days left let daysLeft: Int /// Display title let title: String /// Description of days left let description: String /// Are we counting weekdays only? let weekdaysOnly: Bool /// Percenatge of the count done let percentageDone: Double /// Start date let start: Date /// End date let end: Date /// Current percentage left as a string let currentPercentageLeft: String /// Duration title used on the watch let watchDurationTitle: String /// Full title, used in shortchts etc. let fullTitle: String /// Days left description let daysLeftDescription: String /// Initialiser /// - Parameters: /// - appSettings: App settings used in initialisation /// - date: Current date - default is now init(appSettings: AppSettings, date: Date = Date()) { self.daysLeft = appSettings.daysLeft(date) self.title = appSettings.title self.weekdaysOnly = appSettings.weekdaysOnly self.description = appSettings.description(date) self.percentageDone = appSettings.percentageDone(date: date) self.start = appSettings.start self.end = appSettings.end self.currentPercentageLeft = appSettings.currentPercentageLeft(date: date) self.watchDurationTitle = appSettings.watchDurationTitle(date: date) self.fullTitle = appSettings.fullTitle(date: date) self.daysLeftDescription = appSettings.daysLeftDescription(date) } }
mit
bc7acf4ce025077ee7d039649c3948fb
27.68254
82
0.66021
4.621483
false
false
false
false
fqhuy/minimind
minimind/core/hyperbolic.swift
4
3409
// Hyperbolic.swift // // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // 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 Accelerate // MARK: Hyperbolic Sine public func sinh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvsinhf(&results, x, [Int32(x.count)]) return results } public func sinh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvsinh(&results, x, [Int32(x.count)]) return results } // MARK: Hyperbolic Cosine public func cosh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvcoshf(&results, x, [Int32(x.count)]) return results } public func cosh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvcosh(&results, x, [Int32(x.count)]) return results } // MARK: Hyperbolic Tangent public func tanh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvtanhf(&results, x, [Int32(x.count)]) return results } public func tanh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvtanh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Sine public func asinh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvasinhf(&results, x, [Int32(x.count)]) return results } public func asinh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvasinh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Cosine public func acosh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvacoshf(&results, x, [Int32(x.count)]) return results } public func acosh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvacosh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Tangent public func atanh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvatanhf(&results, x, [Int32(x.count)]) return results } public func atanh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvatanh(&results, x, [Int32(x.count)]) return results }
mit
f62784f3f1a8ce88c29033c58b73a7a1
27.630252
80
0.667449
3.437941
false
false
false
false
theMatys/myWatch
myWatch/Source/Core/myWatch.swift
1
7376
// // myWatch.swift // myWatch // // Created by Máté on 2017. 04. 09.. // Copyright © 2017. theMatys. All rights reserved. // import UIKit /// A boolean which indicates whether the application is being launched for the first time. fileprivate var firstLaunch: Bool = false /// The application's main class. class myWatch { //MARK: Instance variables /// A boolean which indicates whether debug mode should be used in the application. var debugMode: Bool = false //MARK: Static variables /// The singleton instance of the `myWatch` class. static let shared: myWatch = myWatch() //MARK: Initializers /// Required for the singleton instance. private init() {} } //MARK: - @UIApplicationMain fileprivate class MWApplicationDelegate: UIResponder, UIApplicationDelegate { //MARK: Instance variables /// The `UIWindow` of the application. /// /// Required for `UIApplicationDelegate`. var window: UIWindow? private var settings: MWSettings = MWSettings.shared //MARK: - Inherited functions from: UIApplicationDelegate internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /*if(firstLaunch) { firstLaunch() }*/ return true } internal 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } internal 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. } internal func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } internal 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. } internal func applicationWillTerminate(_ application: UIApplication) { MWIO.save(settings, to: MWFileLocations.settingsFile) } //MARK: Instance functions /// Determines whether the application is launched for the first time. /// /// If the application is launched for the first time, it prepares the first launch. /// /// If the application is not launched for the first time, it loads the settings and prepares a regular launch. private func firstLaunch() { //Prepare for the first launch let storyboard: UIStoryboard = UIStoryboard(name: "myWatch", bundle: Bundle(for: type(of: self))) let firstLaunchViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: MWIdentifiers.ControllerIdentifiers.firstLaunchNC) self.window!.rootViewController = firstLaunchViewController } } //MARK: - /// The shared settings of the application. /// /// Written to an own settings file upon termination. /// /// Attempted to be read from the file upon lauch. /// /// The success of the reading process determines whether the application is launched for the first time. /// /// - See: `launchSetup()` in `MWApplicationDelegate`. internal class MWSettings: NSObject, NSCoding { //MARK: Instance variables /// Holds the current device that the application uses to retrieve its data. var device: MWDevice! /// Holds a boolean which determines whether the application should be exporting its data to Apple Health. var exportToAppleHealth: Bool = false //MARK: Static variables /// The (shared) singleton instance of `MWSettings`. static let shared: MWSettings = create() //MARK: - Inherited intializers fomr: NSCoding required internal init?(coder aDecoder: NSCoder) { //Decode properties self.device = aDecoder.decodeObject(forKey: PropertyKey.device) as! MWDevice self.exportToAppleHealth = aDecoder.decodeObject(forKey: PropertyKey.exportToAppleHealth) as! Bool } //MARK: Initializers /// Basic initializer for creating an empty instance for first launch. override private init() { /* No-operation */ } //MARK: Inherited functions from: NSCoding func encode(with aCoder: NSCoder) { //Encode properties aCoder.encode(device, forKey: PropertyKey.device) aCoder.encode(exportToAppleHealth, forKey: PropertyKey.exportToAppleHealth) } //MARK: Static functions /// Either creates an empty settings instance or loads the settings from a saved settings file. /// /// - Returns: An `MWSettings` instance. private static func create() -> MWSettings { //Create a default return value let ret: MWSettings = MWSettings() /*//Attempt to load the settings let loadedSettings: MWSettings? = MWIO.load(from: MWFileLocations.defaultSaveLocation) //Check whether the load was successful loadedSettings ??= { //If it was not, create the myWatch directory and settings file if(!FileManager().fileExists(atPath: MWFileLocations.defaultSaveLocation.path)) { do { try FileManager().createDirectory(atPath: MWFileLocations.defaultSaveLocation.path, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { MWLError("Unable to create myWatch directory: \(error.localizedDescription)", module: .moduleCore) } } //Set the application to first launch mode firstLaunch = true } >< { //If it was, set the settings to the loaded settings ret = loadedSettings! }*/ return ret } //MARK: - /// The structure which holds the property names used in the files to identify the properties of this object. private struct PropertyKey { //MARK: Prefixes /// The prefix of the property keys. private static let prefix: String = "MWSettings" //MARK: Property keys static let device: String = prefix + "Device" static let exportToAppleHealth: String = prefix + "ExportToAppleHealth" } }
gpl-3.0
ba036791382439c4779eb3f2a63f954a
35.142157
285
0.668385
5.358285
false
false
false
false
wolfmasa/JTenki
JTenki/WeatherDetail.swift
1
494
// // WeatherDetail.swift // JTenki // // Created by ICP223G on 2015/03/30. // Copyright (c) 2015年 ProjectJ. All rights reserved. // import UIKit class WeatherDetail : UIViewController { var label: String = "" var image: UIImage? = nil @IBOutlet weak var myLabel: UILabel! @IBOutlet weak var weatherImage: UIImageView! override func viewDidLoad() { myLabel.text = label if let img = image { weatherImage.image = img } } }
mit
1ff02e5681dee0ee6e9b17df8f9d1a9a
17.923077
54
0.621951
3.874016
false
false
false
false
f22x/AntialiasImageX
AntialiasImage/AntialiasImage/File.swift
1
1211
// // File.swift // AntialiasImage // // Created by xinglei on 15/9/10. // Copyright © 2015年 Zplay. All rights reserved. // import Foundation import UIKit extension UIImage { func antialiasImage() ->UIImage { // 边界距离 let border: CGFloat = 1.0 // 比原图小1px的图 let rect: CGRect = CGRectMake(border, border, size.width-2*border, size.height-2*border) // 原图 var img = UIImage() // 创造一个小1px的环境 UIGraphicsBeginImageContext(CGSizeMake(rect.size.width, rect.size.height)) // 但是画的时候是原图的范围 self.drawInRect(CGRectMake(-1, -1, size.width, size.height)) // 构建原图 img = UIGraphicsGetImageFromCurrentImageContext() // 终止画 UIGraphicsEndImageContext() // 依靠原图构建环境 UIGraphicsBeginImageContext(size) // 在原图的基础上画小1px的图 img.drawInRect(rect) // 构建小图 let antialiasImage = UIGraphicsGetImageFromCurrentImageContext() // 构建完关闭 UIGraphicsEndImageContext() // 返回这个小1px的图 return antialiasImage; } }
mit
6c1836df58edf0941730ffd2db121c27
26.205128
96
0.626415
3.719298
false
false
false
false
mojidabckuu/CRUDRecord
CRUDRecord/Classes/Alamofire/Request.swift
1
13543
// // Request.swift // Pods // // Created by Vlad Gorbenko on 7/27/16. // // import Foundation import Alamofire import ApplicationSupport import ObjectMapper public extension MultipartFormData { func appendBodyPart(value: String, name: String) { if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { self.appendBodyPart(data: data, name: name) } } func appendBodyPart<T: RawRepresentable>(value: T, name: String) { if let value = value.rawValue as? String { self.appendBodyPart(value, name: name) } } } extension Alamofire.Request { public func debugLog() -> Self { #if DEBUG debugPrint(self) #endif return self } } typealias ModelCompletion = (Response<Record.Type, NSError> -> Void) typealias ModelsCompletion = (Response<Record.Type, NSError> -> Void) extension Alamofire.Request { public static func JSONParseSerializer<Model: Record>(model: Model? = nil, options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<Model, NSError> { return ResponseSerializer { request, response, data, error in let jsonResponse = JSONResponseSerializer().serializeResponse(request, response, data, error) if CRUD.Configuration.defaultConfiguration.loggingEnabled { print("JSON: \(jsonResponse)") } guard let error = jsonResponse.error else { var model: Model = Model() if var item = jsonResponse.value as? JSONObject { if CRUD.Configuration.defaultConfiguration.traitRoot { let key = Model.resourceName.lowercaseString item = (item[key] as? JSONObject) ?? item } model.attributes = item.pure } return .Success(model) } return .Failure(error) } } public static func JSONParseSerializer<Model: Record>(options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<[Model], NSError> { return ResponseSerializer { request, response, data, error in let jsonResponse = JSONResponseSerializer().serializeResponse(request, response, data, error) if CRUD.Configuration.defaultConfiguration.loggingEnabled { print("JSON: \(jsonResponse)") } guard let error = jsonResponse.error else { var models: [Model] = [] if let items = jsonResponse.value as? JSONArray { models = items.map({ (json) -> Model in var model = Model() model.attributes = json.pure return model }) } else if var item = jsonResponse.value as? JSONObject { let key = Model.resourceName.pluralized.lowercaseString if let items = (item[key] as? JSONArray) where CRUD.Configuration.defaultConfiguration.traitRoot { models = items.map({ (json) -> Model in var model = Model() model.attributes = json.pure return model }) } } return .Success(models) } return .Failure(error) } } } extension Alamofire.Request { public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response<[Model], NSError> -> Void) -> Self { if CRUD.Configuration.defaultConfiguration.loggingEnabled { } return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(options: options), completionHandler: completionHandler) } public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (Response<Model, NSError> -> Void)) -> Self { return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(options: options), completionHandler: completionHandler) } public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, model: Model, completionHandler: (Response<Model, NSError> -> Void)) -> Self { return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(model, options: options), completionHandler: completionHandler) } } extension Alamofire.Request { internal static func newError(code: Error.Code, failureReason: String) -> NSError { let errorDomain = "com.alamofireobjectmapper.error" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo) return returnError } public static func ObjectMapperSerializer<T: Record>(keyPath: String?, mapToObject object: T? = nil, context: MapContext? = nil, mapper: MapOf<T>? = nil) -> ResponseSerializer<T, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { if let data = data, let string = String(data: data, encoding: NSUTF8StringEncoding) { var json = JSONParser(string).parse() as? [String: Any] if let errors = json?["errors"] as? [String: Any] where !errors.isEmpty { if let key = errors.keys.first, errorInfo = errors[key] as? [[String: Any]], message = errorInfo.first?["message"] as? String { let info = [NSLocalizedDescriptionKey: message] let error = NSError(domain: "com.json.ahahah", code: 0, userInfo: info) return .Failure(error) } } } return .Failure(error!) } guard let _ = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } var OriginalJSONToMap: [String: Any]? if let data = data { if let string = String(data: data, encoding: NSUTF8StringEncoding) { OriginalJSONToMap = JSONParser(string).parse() as? [String: Any] } } CRUDLog.warning("Response: \(response?.statusCode) : \n" + "\(OriginalJSONToMap)") let JSONToMap: Any? if var keyPath = keyPath { if keyPath.isEmpty { keyPath = T.resourceName.pluralized.lowercaseString } JSONToMap = OriginalJSONToMap?[keyPath] } else { let resourceName = T.resourceName JSONToMap = OriginalJSONToMap?[resourceName] ?? OriginalJSONToMap } if let object = object { Mapper<T>(mapper: mapper).map(JSONToMap, toObject: object) return .Success(object) } else if let parsedObject = Mapper<T>(context: context, mapper: mapper).map(JSONToMap){ return .Success(parsedObject) } let failureReason = "ObjectMapper failed to serialize response." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter keyPath: The key path where object mapping should be performed - parameter object: An object to perform the mapping on to - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - returns: The request. */ public func responseObject<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, mapper: MapOf<T>? = nil, context: MapContext? = nil, completionHandler: Response<T, NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Alamofire.Request.ObjectMapperSerializer(keyPath, mapToObject: object, context: context), completionHandler: completionHandler) } public static func ObjectMapperArraySerializer<T: Record>(keyPath: String?, context: MapContext? = nil, mapper: MapOf<T>? = nil) -> ResponseSerializer<[T], NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { if let data = data, let string = String(data: data, encoding: NSUTF8StringEncoding) { var json = JSONParser(string).parse() as? [String: Any] if let errors = json?["errors"] as? [String: Any] where !errors.isEmpty { if let key = errors.keys.first, errorInfo = errors[key] as? [[String: Any]], message = errorInfo.first?["message"] as? String { let info = [NSLocalizedDescriptionKey: message] let error = NSError(domain: "com.json.ahahah", code: 0, userInfo: info) return .Failure(error) } } } return .Failure(error!) } guard let _ = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } var OriginalJSONToMap: [[String: Any]] = [] if let data = data { if let string = String(data: data, encoding: NSUTF8StringEncoding) { let json = JSONParser(string).parse() if let object = json as? [String: Any] { if var keyPath = keyPath { if keyPath.isEmpty { keyPath = T.resourceName.pluralized.lowercaseString } OriginalJSONToMap = (object[keyPath] as? [[String: Any]]) ?? [] } else { let resourceName = T.resourceName.pluralized.lowercaseString OriginalJSONToMap = (object[resourceName] as? [[String: Any]]) ?? object as? [[String: Any]] ?? [] } } else { OriginalJSONToMap = (json as? [[String: Any]]) ?? [] } } } CRUDLog.warning("Response: \(response?.statusCode) : \n" + "\(OriginalJSONToMap)") if let parsedObject = Mapper<T>(context: context, mapper: mapper).mapArray(OriginalJSONToMap){ return .Success(parsedObject) } let failureReason = "ObjectMapper failed to serialize response." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter keyPath: The key path where object mapping should be performed - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - returns: The request. */ public func responseArray<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Request.ObjectMapperArraySerializer(keyPath, context: context), completionHandler: completionHandler) } // Map utils public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self { return self.responseArray(queue: queue, keyPath: keyPath, context: context, completionHandler: completionHandler) } public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, mapper: MapOf<T>? = nil, completionHandler: Response<T, NSError> -> Void) -> Self { return self.responseObject(queue: queue, keyPath: keyPath, context: context, completionHandler: completionHandler) } public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, object: T, completionHandler: Response<T, NSError> -> Void) -> Self { return self.responseObject(queue: queue, keyPath: keyPath, mapToObject: object, context: context, completionHandler: completionHandler) } }
mit
8310489a5fc352aa71383bce23c31c27
49.537313
245
0.589751
5.255336
false
false
false
false
orcudy/archive
ios/razzle/map-view/COMapView/COMapView.swift
1
4980
// // MapView.swift // COMapView // // Created by Chris Orcutt on 8/23/15. // Copyright (c) 2015 Chris Orcutt. All rights reserved. // import UIKit import MapKit import AddressBook class COMapView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var footerLabel: UILabel! // MARK: MapViewProperties var annotation: MKPointAnnotation? var region: MKCoordinateRegion? { didSet { if let region = region { mapView.region = region if let annotation = annotation { annotation.coordinate = region.center } else { annotation = MKPointAnnotation() annotation!.coordinate = region.center mapView.addAnnotation(annotation!) } } } } var latitude: Float? { didSet { if let latitude = latitude { mapView.region.center.latitude = CLLocationDegrees(latitude) region = mapView.region } } } var longitude: Float? { didSet { if let longitude = longitude { mapView.region.center.longitude = CLLocationDegrees(longitude) region = mapView.region } } } var span: Float? { didSet { if let span = span { mapView.region.span = MKCoordinateSpan(latitudeDelta: CLLocationDegrees(span), longitudeDelta: CLLocationDegrees(span)) region = mapView.region } } } //MARK: AddressBookProperties var name: String? var address = [NSObject : AnyObject]() { didSet { var text = "" if let name = name { text += "\(name)" } if let street = street { text += ", \(street)" } if let city = city { text += ", \(city)" } if let state = state { text += ", \(state)" } if let ZIP = ZIP { text += ", \(ZIP)" } if let country = country { text += ", \(country)" } footerLabel.text = text } } var street: String? { didSet { if let street = street { address[kABPersonAddressStreetKey] = street } } } var city: String? { didSet { if let city = city { address[kABPersonAddressCityKey] = city } } } var state: String? { didSet { if let state = state { address[kABPersonAddressStateKey] = state } } } var ZIP: String? { didSet { if let ZIP = ZIP { address[kABPersonAddressZIPKey] = ZIP } } } var country: String? { didSet { if let country = country { address[kABPersonAddressCountryKey] = country } } } //MARK: Initialization func baseInit() { NSBundle.mainBundle().loadNibNamed("COMapView", owner: self, options: nil) mapView.delegate = self self.footerView.layer.cornerRadius = 2 self.footerView.layer.shadowColor = UIColor.grayColor().CGColor self.footerView.layer.shadowOffset = CGSize(width: 1, height: 1) self.footerView.layer.shadowOpacity = 1 self.footerView.layer.shadowRadius = 1 self.footerView.layer.masksToBounds = false self.footerView.alpha = 0.90 self.view.frame = bounds self.addSubview(self.view) } override init(frame: CGRect) { super.init(frame: frame) baseInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) baseInit() } //MARK: MapsApp @IBAction func openMapsApp(sender: AnyObject) { if let latitude = region?.center.latitude, longitude = region?.center.longitude, name = name { let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: address) var mapItem = MKMapItem(placemark: placemark) mapItem.name = name mapItem.openInMapsWithLaunchOptions(nil) } } } //MARK: MKMapViewDelegate extension COMapView: MKMapViewDelegate { func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { var annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "custom") annotationView.image = UIImage(named: "Marker") return annotationView } }
gpl-3.0
3e03b75c68c43fd4bcad17bb19c13d38
28.122807
135
0.531526
5.165975
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/QImageTitleDetailComposition.swift
1
5456
// // Quickly // open class QImageTitleDetailComposable : QComposable { public var imageStyle: QImageViewStyleSheet public var imageWidth: CGFloat public var imageSpacing: CGFloat public var titleStyle: QLabelStyleSheet public var titleSpacing: CGFloat public var detailStyle: QLabelStyleSheet public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, imageStyle: QImageViewStyleSheet, imageWidth: CGFloat = 96, imageSpacing: CGFloat = 4, titleStyle: QLabelStyleSheet, titleSpacing: CGFloat = 4, detailStyle: QLabelStyleSheet ) { self.imageStyle = imageStyle self.imageWidth = imageWidth self.imageSpacing = imageSpacing self.titleStyle = titleStyle self.titleSpacing = titleSpacing self.detailStyle = detailStyle super.init(edgeInsets: edgeInsets) } } open class QImageTitleDetailComposition< Composable: QImageTitleDetailComposable > : QComposition< Composable > { public private(set) lazy var imageView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var titleView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false view.setContentHuggingPriority( horizontal: UILayoutPriority(rawValue: 252), vertical: UILayoutPriority(rawValue: 252) ) self.contentView.addSubview(view) return view }() public private(set) lazy var detailView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _imageSpacing: CGFloat? private var _titleSpacing: CGFloat? private var _imageWidth: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } private var _imageConstraints: [NSLayoutConstraint] = [] { willSet { self.imageView.removeConstraints(self._imageConstraints) } didSet { self.imageView.addConstraints(self._imageConstraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth)) let titleTextSize = composable.titleStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing)) let detailTextSize = composable.detailStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing)) return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(imageSize.height, titleTextSize.height + composable.titleSpacing + detailTextSize.height) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing { self._edgeInsets = composable.edgeInsets self._imageSpacing = composable.imageSpacing self._titleSpacing = composable.titleSpacing self._constraints = [ self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.titleView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing), self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.detailView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } if self._imageWidth != composable.imageWidth { self._imageWidth = composable.imageWidth self._imageConstraints = [ self.imageView.widthLayout == composable.imageWidth ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.imageView.apply(composable.imageStyle) self.titleView.apply(composable.titleStyle) self.detailView.apply(composable.detailStyle) } }
mit
32bcf5c02cadb6e18bda870e7df0fc75
45.237288
172
0.694098
5.5
false
false
false
false